From 770e4ba2f58a18bb56ee843d1eb7d9b3d51fb9f5 Mon Sep 17 00:00:00 2001 From: Emmanuel Christophe <emmanuel.christophe@orfeo-toolbox.org> Date: Tue, 1 Sep 2009 15:18:39 +0800 Subject: [PATCH] ITK: update ITK to 3.14.0 with otb patches --- Utilities/ITK/CMake/CTestCustom.ctest.in | 2 + Utilities/ITK/CMake/InsightValgrind.supp | 80 + .../ITK/CMake/itkSampleBuildTest.cmake.in | 4 + Utilities/ITK/CMakeLists.txt | 79 +- ...nisotropicFourthOrderLevelSetImageFilter.h | 6 +- .../itkAntiAliasBinaryImageFilter.h | 8 +- .../Code/Algorithms/itkBalloonForceFilter.h | 16 +- .../Code/Algorithms/itkBalloonForceFilter.txx | 10 +- .../itkBayesianClassifierImageFilter.h | 10 +- .../itkBayesianClassifierImageFilter.txx | 23 +- ...esianClassifierInitializationImageFilter.h | 15 +- ...ianClassifierInitializationImageFilter.txx | 20 +- .../Algorithms/itkBinaryMask3DMeshSource.h | 8 +- .../Algorithms/itkBinaryMask3DMeshSource.txx | 17 +- .../Algorithms/itkBinaryMedialNodeMetric.h | 8 +- .../Algorithms/itkBinaryMedialNodeMetric.txx | 5 +- .../itkBinaryMinMaxCurvatureFlowImageFilter.h | 6 +- .../Algorithms/itkBinaryPruningImageFilter.h | 6 +- Utilities/ITK/Code/Algorithms/itkBioCell.h | 6 +- .../ITK/Code/Algorithms/itkBioCellBase.h | 6 +- .../Code/Algorithms/itkBioCellularAggregate.h | 6 +- .../Algorithms/itkBioCellularAggregateBase.h | 6 +- Utilities/ITK/Code/Algorithms/itkBioGene.cxx | 8 +- Utilities/ITK/Code/Algorithms/itkBioGene.h | 11 +- .../itkCollidingFrontsImageFilter.h | 20 +- .../itkCollidingFrontsImageFilter.txx | 23 +- .../itkCompareHistogramImageToImageMetric.h | 12 +- .../itkCompareHistogramImageToImageMetric.txx | 22 +- .../itkConnectedRegionsMeshFilter.h | 6 +- ...mImageToUnaryCorrespondenceMatrixProcess.h | 10 +- ...mageToUnaryCorrespondenceMatrixProcess.txx | 6 +- ...onCoefficientHistogramImageToImageMetric.h | 13 +- ...CoefficientHistogramImageToImageMetric.txx | 7 +- .../Algorithms/itkCurvatureFlowImageFilter.h | 6 +- .../Algorithms/itkDeformableMesh3DFilter.h | 19 +- .../Algorithms/itkDeformableMesh3DFilter.txx | 15 +- ...eformableSimplexMesh3DBalloonForceFilter.h | 8 +- ...ormableSimplexMesh3DBalloonForceFilter.txx | 5 +- .../itkDeformableSimplexMesh3DFilter.h | 28 +- .../itkDeformableSimplexMesh3DFilter.txx | 79 +- ...mplexMesh3DGradientConstraintForceFilter.h | 8 +- ...lexMesh3DGradientConstraintForceFilter.txx | 7 +- .../Algorithms/itkDemonsRegistrationFilter.h | 6 +- .../itkEuclideanDistancePointMetric.h | 6 +- .../itkFEMFiniteDifferenceFunctionLoad.h | 6 +- .../Algorithms/itkFEMRegistrationFilter.h | 6 +- .../Algorithms/itkFEMRegistrationFilter.txx | 12 +- .../itkFFTComplexConjugateToRealImageFilter.h | 6 +- ...itkFFTWComplexConjugateToRealImageFilter.h | 6 +- .../itkFastChamferDistanceImageFilter.h | 6 +- .../itkFastChamferDistanceImageFilter.txx | 8 +- .../Algorithms/itkFastMarchingImageFilter.h | 6 +- .../itkGradientVectorFlowImageFilter.h | 10 +- .../Algorithms/itkHistogramAlgorithmBase.h | 6 +- .../itkHistogramImageToImageMetric.h | 15 +- .../itkHistogramImageToImageMetric.txx | 38 +- .../itkHistogramMatchingImageFilter.h | 14 +- .../itkHistogramMatchingImageFilter.txx | 21 +- .../Code/Algorithms/itkImageClassifierBase.h | 6 +- .../itkImageGaussianModelEstimator.h | 6 +- .../Algorithms/itkImageKmeansModelEstimator.h | 14 +- .../itkImageKmeansModelEstimator.txx | 11 +- .../itkImagePCADecompositionCalculator.h | 6 +- .../itkImagePCAShapeModelEstimator.h | 10 +- .../Algorithms/itkImageRegistrationMethod.h | 6 +- .../itkIsoContourDistanceImageFilter.h | 10 +- .../itkIsoContourDistanceImageFilter.txx | 12 +- .../itkIsolatedWatershedImageFilter.h | 16 +- ...kIsotropicFourthOrderLevelSetImageFilter.h | 6 +- .../itkKappaStatisticImageToImageMetric.h | 8 +- .../itkLevelSetNeighborhoodExtractor.h | 10 +- .../ITK/Code/Algorithms/itkMRFImageFilter.h | 12 +- .../ITK/Code/Algorithms/itkMRFImageFilter.txx | 15 +- .../itkMRIBiasFieldCorrectionFilter.h | 16 +- .../itkMatchCardinalityImageToImageMetric.h | 6 +- .../itkMatchCardinalityImageToImageMetric.txx | 8 +- ...procalSquareDifferenceImageToImageMetric.h | 8 +- ...calSquareDifferencePointSetToImageMetric.h | 6 +- ...lSquareDifferencePointSetToImageMetric.txx | 6 +- ...tkMeanSquaresHistogramImageToImageMetric.h | 8 +- .../itkMedialNodePairCorrespondenceProcess.h | 6 +- ...tkMedialNodeTripletCorrespondenceProcess.h | 6 +- .../itkMinMaxCurvatureFlowFunction.txx | 38 +- .../itkMinMaxCurvatureFlowImageFilter.h | 6 +- ...tkMultiResolutionImageRegistrationMethod.h | 8 +- ...MultiResolutionImageRegistrationMethod.txx | 8 +- .../itkMultiResolutionPyramidImageFilter.h | 25 +- .../itkMultiResolutionPyramidImageFilter.txx | 67 +- ...alInformationHistogramImageToImageMetric.h | 8 +- ...InformationHistogramImageToImageMetric.txx | 19 +- .../itkMutualInformationImageToImageMetric.h | 6 +- ...alInformationHistogramImageToImageMetric.h | 8 +- ...InformationHistogramImageToImageMetric.txx | 22 +- .../itkOtsuMultipleThresholdsCalculator.h | 13 +- .../itkOtsuMultipleThresholdsCalculator.txx | 8 +- .../itkOtsuThresholdImageCalculator.h | 8 +- .../Algorithms/itkOtsuThresholdImageFilter.h | 12 +- .../itkPDEDeformableRegistrationFilter.h | 12 +- .../Code/Algorithms/itkRGBGibbsPriorFilter.h | 20 +- .../Algorithms/itkRGBGibbsPriorFilter.txx | 6 +- .../itkRayCastInterpolateImageFunction.h | 8 +- ...cursiveMultiResolutionPyramidImageFilter.h | 9 +- ...rsiveMultiResolutionPyramidImageFilter.txx | 74 +- .../Algorithms/itkRegularSphereMeshSource.h | 12 +- .../Algorithms/itkRegularSphereMeshSource.txx | 8 +- .../itkReinitializeLevelSetImageFilter.h | 12 +- .../itkReinitializeLevelSetImageFilter.txx | 8 +- .../Code/Algorithms/itkSTAPLEImageFilter.h | 12 +- .../itkScalarImageKmeansImageFilter.h | 44 +- .../itkScalarImageKmeansImageFilter.txx | 51 +- .../itkSegmentationLevelSetImageFilter.h | 8 +- .../Algorithms/itkShapePriorMAPCostFunction.h | 8 +- ...hapePriorSegmentationLevelSetImageFilter.h | 6 +- .../itkSimplexMeshVolumeCalculator.h | 8 +- .../Code/Algorithms/itkSphereMeshSource.txx | 42 +- .../Code/Algorithms/itkStructHashFunction.h | 6 +- ...oldMaximumConnectedComponentsImageFilter.h | 16 +- .../Algorithms/itkUnaryMedialNodeMetric.h | 6 +- .../itkUnsharpMaskLevelSetImageFilter.h | 6 +- .../ITK/Code/Algorithms/itkVoronoiDiagram2D.h | 6 +- .../Algorithms/itkVoronoiDiagram2DGenerator.h | 6 +- .../itkVoronoiDiagram2DGenerator.txx | 6 +- .../itkVoronoiPartitioningImageFilter.h | 6 +- .../itkVoronoiSegmentationImageFilter.h | 16 +- .../itkVoronoiSegmentationImageFilterBase.h | 24 +- .../itkVoronoiSegmentationImageFilterBase.txx | 20 +- .../itkVoronoiSegmentationRGBImageFilter.h | 6 +- .../Algorithms/itkWatershedBoundaryResolver.h | 6 +- .../Code/Algorithms/itkWatershedImageFilter.h | 8 +- ...tkWatershedMiniPipelineProgressCommand.cxx | 11 +- .../itkWatershedMiniPipelineProgressCommand.h | 11 +- .../Code/Algorithms/itkWatershedRelabeler.h | 6 +- .../Code/Algorithms/itkWatershedSegmentTree.h | 12 +- .../itkWatershedSegmentTreeGenerator.h | 12 +- .../itkWatershedSegmentTreeGenerator.txx | 14 +- .../Code/Algorithms/itkWatershedSegmenter.h | 12 +- .../ITK/Code/BasicFilters/itkAbsImageFilter.h | 6 +- .../itkAbsoluteValueDifferenceImageFilter.h | 6 +- .../BasicFilters/itkAccumulateImageFilter.h | 8 +- .../Code/BasicFilters/itkAcosImageFilter.h | 6 +- .../Code/BasicFilters/itkAdaptImageFilter.h | 6 +- ...AdaptiveHistogramEqualizationImageFilter.h | 10 +- .../ITK/Code/BasicFilters/itkAddImageFilter.h | 6 +- .../ITK/Code/BasicFilters/itkAndImageFilter.h | 6 +- .../itkAnisotropicDiffusionImageFilter.h | 14 +- ...kApproximateSignedDistanceMapImageFilter.h | 8 +- .../Code/BasicFilters/itkAsinImageFilter.h | 6 +- .../Code/BasicFilters/itkAtan2ImageFilter.h | 6 +- .../Code/BasicFilters/itkAtanImageFilter.h | 6 +- .../itkBSplineDecompositionImageFilter.h | 24 +- .../itkBSplineDecompositionImageFilter.txx | 50 +- .../itkBSplineInterpolateImageFunction.h | 6 +- .../itkBSplineInterpolateImageFunction.txx | 80 +- .../itkBSplineResampleImageFilterBase.h | 6 +- .../itkBSplineResampleImageFilterBase.txx | 27 +- .../BasicFilters/itkBilateralImageFilter.h | 14 +- .../itkBinaryDilateImageFilter.txx | 16 +- .../itkBinaryMagnitudeImageFilter.h | 6 +- .../itkBinaryMaskToNarrowBandPointSetFilter.h | 6 +- .../itkBinaryThresholdImageFilter.h | 6 +- .../BasicFilters/itkBinomialBlurImageFilter.h | 6 +- ...tImageToBloxBoundaryProfileImageFilter.txx | 56 +- .../itkBoundedReciprocalImageFilter.h | 6 +- .../itkCannyEdgeDetectionImageFilter.h | 18 +- .../itkCannyEdgeDetectionImageFilter.txx | 36 +- .../Code/BasicFilters/itkCastImageFilter.h | 6 +- .../itkChainCodeToFourierSeriesPathFilter.txx | 8 +- .../itkChangeInformationImageFilter.h | 16 +- .../BasicFilters/itkChangeLabelImageFilter.h | 11 +- .../itkComplexToImaginaryImageFilter.h | 6 +- .../itkComplexToModulusImageFilter.h | 6 +- .../itkComplexToPhaseImageFilter.h | 6 +- .../itkComplexToRealImageFilter.h | 6 +- .../itkCompose2DCovariantVectorImageFilter.h | 6 +- .../itkCompose2DVectorImageFilter.h | 6 +- .../itkCompose3DCovariantVectorImageFilter.h | 6 +- .../itkCompose3DVectorImageFilter.h | 6 +- .../BasicFilters/itkComposeRGBImageFilter.h | 6 +- .../itkConfidenceConnectedImageFilter.h | 27 +- .../itkConfidenceConnectedImageFilter.txx | 34 +- .../itkConnectedComponentImageFilter.h | 27 +- .../itkConnectedComponentImageFilter.txx | 36 +- .../itkConnectedThresholdImageFilter.h | 30 +- .../itkConnectedThresholdImageFilter.txx | 34 +- .../BasicFilters/itkConstantPadImageFilter.h | 6 +- .../itkConstrainedValueAdditionImageFilter.h | 6 +- ...itkConstrainedValueDifferenceImageFilter.h | 6 +- ...tkContourDirectedMeanDistanceImageFilter.h | 6 +- .../itkContourMeanDistanceImageFilter.h | 6 +- .../ITK/Code/BasicFilters/itkCosImageFilter.h | 8 +- .../Code/BasicFilters/itkCropImageFilter.h | 8 +- ...urvatureNDAnisotropicDiffusionFunction.txx | 14 +- .../itkDanielssonDistanceMapImageFilter.txx | 6 +- ...eformationFieldJacobianDeterminantFilter.h | 6 +- .../BasicFilters/itkDerivativeImageFilter.h | 10 +- ...DifferenceOfGaussiansGradientImageFilter.h | 6 +- ...ffusionTensor3DReconstructionImageFilter.h | 6 +- ...usionTensor3DReconstructionImageFilter.txx | 8 +- .../itkDilateObjectMorphologyImageFilter.h | 11 +- .../itkDilateObjectMorphologyImageFilter.txx | 8 +- .../itkDirectedHausdorffDistanceImageFilter.h | 8 +- .../itkDiscreteGaussianImageFilter.h | 14 +- ...splacementFieldJacobianDeterminantFilter.h | 6 +- .../Code/BasicFilters/itkDivideImageFilter.h | 6 +- .../itkDoubleThresholdImageFilter.h | 16 +- .../itkEdgePotentialImageFilter.h | 6 +- .../itkErodeObjectMorphologyImageFilter.h | 13 +- .../ITK/Code/BasicFilters/itkExpImageFilter.h | 6 +- .../BasicFilters/itkExpNegativeImageFilter.h | 6 +- .../Code/BasicFilters/itkExpandImageFilter.h | 21 +- .../BasicFilters/itkExpandImageFilter.txx | 31 +- .../Code/BasicFilters/itkExtractImageFilter.h | 6 +- .../Code/BasicFilters/itkFlipImageFilter.h | 8 +- .../BasicFilters/itkGaussianImageSource.h | 12 +- .../itkGetAverageSliceImageFilter.h | 6 +- .../BasicFilters/itkGradientImageFilter.h | 8 +- ...dientImageToBloxBoundaryPointImageFilter.h | 6 +- ...entImageToBloxBoundaryPointImageFilter.txx | 117 +- .../itkGradientMagnitudeImageFilter.h | 6 +- .../itkGradientMagnitudeImageFilter.txx | 6 +- ...entMagnitudeRecursiveGaussianImageFilter.h | 6 +- ...tMagnitudeRecursiveGaussianImageFilter.txx | 10 +- ...GradientNDAnisotropicDiffusionFunction.txx | 9 +- .../itkGradientRecursiveGaussianImageFilter.h | 8 +- .../itkGradientToMagnitudeImageFilter.h | 6 +- .../itkGrayscaleConnectedClosingImageFilter.h | 6 +- .../itkGrayscaleConnectedOpeningImageFilter.h | 6 +- .../itkGrayscaleDilateImageFilter.h | 11 +- .../itkGrayscaleDilateImageFilter.txx | 10 +- .../itkGrayscaleErodeImageFilter.h | 11 +- .../itkGrayscaleErodeImageFilter.txx | 10 +- .../itkGrayscaleFunctionDilateImageFilter.h | 13 +- .../itkGrayscaleFunctionDilateImageFilter.txx | 10 +- .../itkGrayscaleFunctionErodeImageFilter.h | 13 +- .../itkGrayscaleFunctionErodeImageFilter.txx | 10 +- .../itkGrayscaleGeodesicDilateImageFilter.h | 8 +- .../itkGrayscaleGeodesicErodeImageFilter.h | 8 +- ...GrayscaleMorphologicalClosingImageFilter.h | 11 +- ...GrayscaleMorphologicalOpeningImageFilter.h | 11 +- .../BasicFilters/itkHConcaveImageFilter.h | 6 +- .../Code/BasicFilters/itkHConvexImageFilter.h | 6 +- .../Code/BasicFilters/itkHMaximaImageFilter.h | 6 +- .../Code/BasicFilters/itkHMinimaImageFilter.h | 6 +- .../itkHausdorffDistanceImageFilter.h | 8 +- ...kHessian3DToVesselnessMeasureImageFilter.h | 8 +- .../itkHessianRecursiveGaussianImageFilter.h | 6 +- .../itkHoughTransform2DCirclesImageFilter.h | 16 +- .../itkHoughTransform2DCirclesImageFilter.txx | 6 +- .../itkHoughTransform2DLinesImageFilter.h | 14 +- .../itkHoughTransform2DLinesImageFilter.txx | 6 +- .../itkImageToVectorImageFilter.h | 8 +- .../itkImplicitManifoldNormalVectorFilter.h | 18 +- .../itkIntensityWindowingImageFilter.h | 6 +- .../BasicFilters/itkInterpolateImageFilter.h | 6 +- .../itkInterpolateImageFilter.txx | 6 +- .../itkInterpolateImagePointsFilter.h | 6 +- .../itkInverseDeformationFieldImageFilter.h | 6 +- .../itkInvertIntensityImageFilter.h | 6 +- .../itkIsolatedConnectedImageFilter.h | 42 +- .../itkIsolatedConnectedImageFilter.txx | 70 +- ...rativeInverseDeformationFieldImageFilter.h | 8 +- .../Code/BasicFilters/itkJoinImageFilter.h | 18 +- .../BasicFilters/itkJoinSeriesImageFilter.h | 8 +- .../itkLabelStatisticsImageFilter.h | 25 +- .../itkLabelStatisticsImageFilter.txx | 26 +- .../BasicFilters/itkLaplacianImageFilter.h | 6 +- ...itkLaplacianRecursiveGaussianImageFilter.h | 6 +- .../itkLaplacianSharpeningImageFilter.h | 6 +- .../Code/BasicFilters/itkLog10ImageFilter.h | 6 +- .../ITK/Code/BasicFilters/itkLogImageFilter.h | 6 +- .../Code/BasicFilters/itkMaskImageFilter.h | 6 +- .../BasicFilters/itkMaskNegatedImageFilter.h | 6 +- .../itkMaskNeighborhoodOperatorImageFilter.h | 6 +- .../itkMatrixIndexSelectionImageFilter.h | 6 +- .../Code/BasicFilters/itkMaximumImageFilter.h | 6 +- .../Code/BasicFilters/itkMinimumImageFilter.h | 6 +- .../itkMinimumMaximumImageCalculator.h | 8 +- .../itkMinimumProjectionImageFilter.h | 6 +- .../Code/BasicFilters/itkModulusImageFilter.h | 6 +- .../itkMorphologicalGradientImageFilter.h | 11 +- .../BasicFilters/itkMorphologyImageFilter.h | 6 +- .../BasicFilters/itkMultiplyImageFilter.h | 6 +- .../ITK/Code/BasicFilters/itkNarrowBand.txx | 7 +- .../itkNarrowBandImageFilterBase.h | 8 +- .../itkNarrowBandImageFilterBase.txx | 7 +- .../Code/BasicFilters/itkNaryAddImageFilter.h | 6 +- .../itkNaryFunctorImageFilter.txx | 70 +- .../BasicFilters/itkNaryMaximumImageFilter.h | 6 +- .../itkNeighborhoodConnectedImageFilter.h | 30 +- .../itkNeighborhoodConnectedImageFilter.txx | 34 +- .../Code/BasicFilters/itkNoiseImageFilter.txx | 6 +- .../itkNonThreadedShrinkImageFilter.h | 84 +- .../itkNonThreadedShrinkImageFilter.txx | 267 --- .../itkNormalVectorDiffusionFunction.h | 8 +- .../ITK/Code/BasicFilters/itkNotImageFilter.h | 6 +- .../itkObjectMorphologyImageFilter.h | 10 +- .../ITK/Code/BasicFilters/itkOrImageFilter.h | 6 +- .../Code/BasicFilters/itkOrientImageFilter.h | 6 +- ...tkParallelSparseFieldLevelSetImageFilter.h | 8 +- .../Code/BasicFilters/itkPasteImageFilter.h | 8 +- .../Code/BasicFilters/itkPathToImageFilter.h | 10 +- .../BasicFilters/itkPointSetToImageFilter.h | 10 +- .../itkRGBToLuminanceImageFilter.h | 6 +- .../Code/BasicFilters/itkRandomImageSource.h | 8 +- .../itkRecursiveGaussianImageFilter.h | 10 +- .../itkRecursiveSeparableImageFilter.h | 6 +- .../itkRecursiveSeparableImageFilter.txx | 8 +- .../Code/BasicFilters/itkReflectImageFilter.h | 6 +- .../itkRegionOfInterestImageFilter.h | 6 +- .../itkRelabelComponentImageFilter.h | 50 +- .../itkRelabelComponentImageFilter.txx | 31 +- .../BasicFilters/itkResampleImageFilter.h | 67 +- .../BasicFilters/itkResampleImageFilter.txx | 114 +- .../itkRescaleIntensityImageFilter.h | 6 +- .../itkScalarConnectedComponentImageFilter.h | 6 +- .../BasicFilters/itkShiftScaleImageFilter.h | 12 +- .../itkShiftScaleInPlaceImageFilter.h | 12 +- .../Code/BasicFilters/itkShrinkImageFilter.h | 10 +- .../BasicFilters/itkShrinkImageFilter.txx | 163 +- .../Code/BasicFilters/itkSigmoidImageFilter.h | 6 +- ...tkSignedDanielssonDistanceMapImageFilter.h | 13 +- ...SignedDanielssonDistanceMapImageFilter.txx | 38 +- .../itkSignedMaurerDistanceMapImageFilter.h | 6 +- .../itkSignedMaurerDistanceMapImageFilter.txx | 12 +- .../itkSimilarityIndexImageFilter.h | 6 +- .../itkSimplexMeshAdaptTopologyFilter.h | 12 +- .../itkSimplexMeshAdaptTopologyFilter.txx | 9 +- .../itkSimplexMeshToTriangleMeshFilter.h | 6 +- .../ITK/Code/BasicFilters/itkSinImageFilter.h | 6 +- ...itkSmoothingRecursiveGaussianImageFilter.h | 8 +- .../Code/BasicFilters/itkSparseFieldLayer.txx | 8 +- .../itkSparseFieldLevelSetImageFilter.h | 12 +- .../itkSpatialObjectToImageFilter.h | 14 +- .../itkSpatialObjectToImageFilter.txx | 8 +- ...SpatialObjectToImageStatisticsCalculator.h | 6 +- ...atialObjectToImageStatisticsCalculator.txx | 46 +- .../itkSpatialObjectToPointSetFilter.h | 8 +- .../Code/BasicFilters/itkSqrtImageFilter.h | 6 +- .../Code/BasicFilters/itkSquareImageFilter.h | 6 +- .../itkSquaredDifferenceImageFilter.h | 6 +- ...tkStandardDeviationProjectionImageFilter.h | 6 +- .../BasicFilters/itkSubtractImageFilter.h | 6 +- .../itkSymmetricEigenAnalysisImageFilter.h | 6 +- .../ITK/Code/BasicFilters/itkTanImageFilter.h | 6 +- ...itkTensorFractionalAnisotropyImageFilter.h | 6 +- .../itkTensorRelativeAnisotropyImageFilter.h | 6 +- .../BasicFilters/itkTernaryAddImageFilter.h | 6 +- .../itkTernaryMagnitudeImageFilter.h | 6 +- .../itkTernaryMagnitudeSquaredImageFilter.h | 6 +- .../BasicFilters/itkThresholdImageFilter.h | 10 +- .../itkThresholdLabelerImageFilter.h | 10 +- .../Code/BasicFilters/itkTileImageFilter.h | 8 +- .../itkTriangleMeshToBinaryImageFilter.h | 14 +- .../itkTriangleMeshToBinaryImageFilter.txx | 16 +- .../itkTriangleMeshToSimplexMeshFilter.h | 6 +- .../itkTwoOutputExampleImageFilter.h | 6 +- .../ITK/Code/BasicFilters/itkVTKImageImport.h | 32 +- .../itkVectorConfidenceConnectedImageFilter.h | 10 +- .../itkVectorConnectedComponentImageFilter.h | 6 +- ...urvatureNDAnisotropicDiffusionFunction.txx | 19 +- .../BasicFilters/itkVectorExpandImageFilter.h | 11 +- .../itkVectorExpandImageFilter.txx | 29 +- .../itkVectorGradientMagnitudeImageFilter.h | 8 +- .../itkVectorGradientMagnitudeImageFilter.txx | 6 +- ...GradientNDAnisotropicDiffusionFunction.txx | 16 +- .../itkVectorIndexSelectionCastImageFilter.h | 8 +- .../itkVectorResampleImageFilter.h | 6 +- .../itkVectorRescaleIntensityImageFilter.h | 6 +- .../Code/BasicFilters/itkWarpImageFilter.h | 41 +- .../Code/BasicFilters/itkWarpImageFilter.txx | 251 ++- .../BasicFilters/itkWarpVectorImageFilter.h | 9 +- .../BasicFilters/itkWarpVectorImageFilter.txx | 21 +- .../BasicFilters/itkWeightedAddImageFilter.h | 6 +- .../BasicFilters/itkWhiteTopHatImageFilter.h | 11 +- .../ITK/Code/BasicFilters/itkXorImageFilter.h | 6 +- ...eroCrossingBasedEdgeDetectionImageFilter.h | 12 +- .../BasicFilters/itkZeroCrossingImageFilter.h | 8 +- .../ITK/Code/Common/itkAffineTransform.h | 15 +- .../ITK/Code/Common/itkAffineTransform.txx | 29 +- .../ITK/Code/Common/itkAnnulusOperator.txx | 6 +- ...tkAzimuthElevationToCartesianTransform.txx | 16 +- .../Common/itkBSplineDeformableTransform.h | 9 +- .../Common/itkBSplineDeformableTransform.txx | 132 +- .../itkBSplineInterpolationWeightFunction.h | 8 +- .../ITK/Code/Common/itkBloxCoreAtomImage.h | 8 +- Utilities/ITK/Code/Common/itkBoundingBox.txx | 6 +- .../Code/Common/itkCenteredAffineTransform.h | 15 +- .../Common/itkCenteredAffineTransform.txx | 23 +- .../Code/Common/itkCenteredEuler3DTransform.h | 15 +- .../Common/itkCenteredEuler3DTransform.txx | 23 +- .../Code/Common/itkCenteredRigid2DTransform.h | 15 +- .../Common/itkCenteredRigid2DTransform.txx | 35 +- .../Common/itkCenteredSimilarity2DTransform.h | 15 +- .../itkCenteredSimilarity2DTransform.txx | 37 +- .../itkCentralDifferenceImageFunction.h | 6 +- Utilities/ITK/Code/Common/itkColorTable.h | 6 +- ...onicShellInteriorExteriorSpatialFunction.h | 14 +- .../itkCoreAtomImageToDistanceMatrixProcess.h | 6 +- .../itkDenseFiniteDifferenceImageFilter.txx | 6 +- .../Code/Common/itkDifferenceImageFilter.h | 16 +- .../ITK/Code/Common/itkDiffusionTensor3D.h | 6 +- ...asticBodyReciprocalSplineKernelTransform.h | 6 +- .../itkElasticBodySplineKernelTransform.h | 6 +- ...EllipsoidInteriorExteriorSpatialFunction.h | 8 +- .../ITK/Code/Common/itkEuler2DTransform.h | 15 +- .../ITK/Code/Common/itkEuler2DTransform.txx | 36 +- .../ITK/Code/Common/itkEuler3DTransform.txx | 10 +- Utilities/ITK/Code/Common/itkEventObject.h | 10 +- .../ITK/Code/Common/itkFileOutputWindow.h | 8 +- .../Common/itkFiniteCylinderSpatialFunction.h | 12 +- .../itkFiniteCylinderSpatialFunction.txx | 8 +- .../itkFiniteDifferenceSparseImageFilter.h | 6 +- .../ITK/Code/Common/itkFourierSeriesPath.txx | 8 +- .../Code/Common/itkFrustumSpatialFunction.h | 16 +- .../Common/itkGaussianBlurImageFunction.h | 11 +- .../Common/itkGaussianBlurImageFunction.txx | 146 +- .../itkGaussianDerivativeSpatialFunction.h | 14 +- .../ITK/Code/Common/itkGaussianOperator.txx | 14 +- .../Code/Common/itkGaussianSpatialFunction.h | 12 +- .../Common/itkGaussianSpatialFunction.txx | 36 +- .../ITK/Code/Common/itkIdentityTransform.h | 15 +- Utilities/ITK/Code/Common/itkImageBase.h | 22 +- Utilities/ITK/Code/Common/itkImageBase.txx | 5 +- .../ITK/Code/Common/itkImageConstIterator.h | 14 +- .../Common/itkImageConstIteratorWithIndex.txx | 14 +- Utilities/ITK/Code/Common/itkImageFunction.h | 11 +- .../ITK/Code/Common/itkImageFunction.txx | 10 +- Utilities/ITK/Code/Common/itkImageRegion.h | 27 +- ...itkImageRegionMultidimensionalSplitter.txx | 10 +- .../Code/Common/itkImageRegionSplitter.txx | 12 +- .../Common/itkImageSliceIteratorWithIndex.h | 6 +- Utilities/ITK/Code/Common/itkImageSource.h | 15 +- Utilities/ITK/Code/Common/itkImageSource.txx | 38 +- .../ITK/Code/Common/itkImageTransformHelper.h | 16 +- .../ITK/Code/Common/itkImportImageContainer.h | 36 +- .../Code/Common/itkImportImageContainer.txx | 66 +- .../ITK/Code/Common/itkInPlaceImageFilter.h | 19 +- .../ITK/Code/Common/itkInPlaceImageFilter.txx | 8 +- Utilities/ITK/Code/Common/itkIndex.h | 20 +- .../ITK/Code/Common/itkKernelTransform.h | 47 +- .../ITK/Code/Common/itkKernelTransform.txx | 52 +- .../itkLandmarkBasedTransformInitializer.txx | 6 +- .../itkLinearInterpolateImageFunction.h | 7 +- .../itkLinearInterpolateImageFunction.txx | 26 +- Utilities/ITK/Code/Common/itkLoggerOutput.h | 6 +- Utilities/ITK/Code/Common/itkMacro.h | 57 +- .../Common/itkMatrixOffsetTransformBase.h | 11 +- .../Common/itkMatrixOffsetTransformBase.txx | 16 +- Utilities/ITK/Code/Common/itkMetaDataObject.h | 6 +- .../ITK/Code/Common/itkMultiThreader.cxx | 6 +- Utilities/ITK/Code/Common/itkMultiThreader.h | 6 +- ...kNearestNeighborExtrapolateImageFunction.h | 10 +- Utilities/ITK/Code/Common/itkNeighborhood.h | 16 +- .../Common/itkNeighborhoodAccessorFunctor.h | 10 +- .../Code/Common/itkNeighborhoodAllocator.h | 5 +- .../Code/Common/itkNumericTraitsVectorPixel.h | 5 +- .../ITK/Code/Common/itkObjectFactoryBase.cxx | 6 +- Utilities/ITK/Code/Common/itkObjectStore.h | 10 +- Utilities/ITK/Code/Common/itkOutputWindow.h | 6 +- .../itkPCAShapeSignedDistanceFunction.h | 8 +- Utilities/ITK/Code/Common/itkPathFunctions.h | 10 +- Utilities/ITK/Code/Common/itkPixelTraits.h | 40 +- Utilities/ITK/Code/Common/itkPoint.h | 43 +- Utilities/ITK/Code/Common/itkPointLocator.h | 38 +- Utilities/ITK/Code/Common/itkPointLocator.txx | 39 +- Utilities/ITK/Code/Common/itkPointSet.h | 18 +- Utilities/ITK/Code/Common/itkPointSet.txx | 12 +- .../Code/Common/itkPolyLineParametricPath.h | 20 +- .../Code/Common/itkPolyLineParametricPath.txx | 12 +- Utilities/ITK/Code/Common/itkPolygonCell.h | 10 +- Utilities/ITK/Code/Common/itkPolygonCell.txx | 84 +- .../Code/Common/itkPostOrderTreeIterator.h | 53 +- .../ITK/Code/Common/itkPreOrderTreeIterator.h | 14 +- .../ITK/Code/Common/itkProcessObject.cxx | 11 +- Utilities/ITK/Code/Common/itkProcessObject.h | 19 +- .../ITK/Code/Common/itkProgressAccumulator.h | 6 +- .../ITK/Code/Common/itkProgressReporter.h | 20 +- .../ITK/Code/Common/itkQuadraticEdgeCell.txx | 39 +- .../Code/Common/itkQuadraticTriangleCell.h | 13 +- .../Code/Common/itkQuadraticTriangleCell.txx | 67 +- .../itkQuadraticTriangleCellTopology.cxx | 5 +- .../Common/itkQuadraticTriangleCellTopology.h | 14 +- .../ITK/Code/Common/itkQuadrilateralCell.txx | 63 +- .../Common/itkQuadrilateralCellTopology.cxx | 9 +- .../Common/itkQuadrilateralCellTopology.h | 13 +- .../Common/itkQuaternionOrientationAdapter.h | 35 +- .../Code/Common/itkQuaternionRigidTransform.h | 13 +- .../Common/itkQuaternionRigidTransform.txx | 12 +- Utilities/ITK/Code/Common/itkRGBAPixel.h | 26 +- Utilities/ITK/Code/Common/itkRGBAPixel.txx | 12 +- Utilities/ITK/Code/Common/itkRGBPixel.h | 32 +- Utilities/ITK/Code/Common/itkRGBPixel.txx | 29 +- .../Common/itkRGBToLuminanceImageAdaptor.h | 14 +- .../Code/Common/itkRGBToVectorImageAdaptor.h | 18 +- .../Code/Common/itkRGBToVectorPixelAccessor.h | 5 +- .../ITK/Code/Common/itkRealTimeClock.cxx | 8 +- Utilities/ITK/Code/Common/itkRealTimeClock.h | 26 +- .../ITK/Code/Common/itkRedPixelAccessor.h | 16 +- Utilities/ITK/Code/Common/itkRegion.cxx | 5 +- Utilities/ITK/Code/Common/itkRegion.h | 5 +- .../Common/itkResourceProbesCollectorBase.txx | 6 +- .../ITK/Code/Common/itkRigid2DTransform.h | 15 +- .../ITK/Code/Common/itkRigid2DTransform.txx | 38 +- .../Common/itkRigid3DPerspectiveTransform.h | 12 +- .../Common/itkRigid3DPerspectiveTransform.txx | 15 +- .../ITK/Code/Common/itkRigid3DTransform.h | 44 +- .../ITK/Code/Common/itkRigid3DTransform.txx | 44 +- .../ITK/Code/Common/itkRootTreeIterator.h | 12 +- .../Code/Common/itkSTLConstContainerAdaptor.h | 17 +- .../ITK/Code/Common/itkSTLContainerAdaptor.h | 38 +- .../Code/Common/itkScalableAffineTransform.h | 44 +- .../Common/itkScalableAffineTransform.txx | 27 +- .../Code/Common/itkScalarToRGBPixelFunctor.h | 12 +- .../Common/itkScalarToRGBPixelFunctor.txx | 10 +- Utilities/ITK/Code/Common/itkScalarVector.h | 6 +- .../Common/itkScaleLogarithmicTransform.h | 13 +- .../Common/itkScaleLogarithmicTransform.txx | 10 +- .../Common/itkScaleSkewVersor3DTransform.h | 15 +- .../Common/itkScaleSkewVersor3DTransform.txx | 25 +- Utilities/ITK/Code/Common/itkScaleTransform.h | 29 +- .../ITK/Code/Common/itkScaleTransform.txx | 24 +- .../Common/itkScatterMatrixImageFunction.h | 23 +- .../Common/itkScatterMatrixImageFunction.txx | 13 +- .../ITK/Code/Common/itkSegmentationBorder.cxx | 5 +- .../ITK/Code/Common/itkSegmentationBorder.h | 10 +- .../Common/itkSegmentationLevelSetFunction.h | 40 +- .../itkSegmentationLevelSetFunction.txx | 10 +- .../ITK/Code/Common/itkSegmentationRegion.cxx | 5 +- Utilities/ITK/Code/Common/itkSemaphore.cxx | 37 +- Utilities/ITK/Code/Common/itkSemaphore.h | 22 +- .../Common/itkShapeSignedDistanceFunction.h | 10 +- .../Common/itkShapedNeighborhoodIterator.h | 79 +- .../Common/itkShapedNeighborhoodIterator.txx | 9 +- .../Code/Common/itkSimilarity2DTransform.h | 30 +- .../Code/Common/itkSimilarity2DTransform.txx | 44 +- .../Code/Common/itkSimilarity3DTransform.h | 9 +- .../Code/Common/itkSimilarity3DTransform.txx | 16 +- .../Common/itkSimpleDataObjectDecorator.h | 15 +- .../Common/itkSimpleDataObjectDecorator.txx | 21 +- .../ITK/Code/Common/itkSimpleFastMutexLock.h | 5 +- .../Code/Common/itkSimpleFilterWatcher.cxx | 5 +- .../ITK/Code/Common/itkSimpleFilterWatcher.h | 62 +- Utilities/ITK/Code/Common/itkSimplexMesh.h | 442 ++-- Utilities/ITK/Code/Common/itkSimplexMesh.txx | 16 +- .../Code/Common/itkSimplexMeshGeometry.cxx | 17 +- .../ITK/Code/Common/itkSimplexMeshGeometry.h | 50 +- Utilities/ITK/Code/Common/itkSize.h | 6 +- Utilities/ITK/Code/Common/itkSliceIterator.h | 44 +- .../ITK/Code/Common/itkSmapsFileParser.cxx | 7 +- Utilities/ITK/Code/Common/itkSmartPointer.h | 20 +- .../Common/itkSmartPointerForwardReference.h | 16 +- .../itkSmartPointerForwardReference.txx | 12 +- ...rtPointerForwardReferenceProcessObject.cxx | 20 +- Utilities/ITK/Code/Common/itkSobelOperator.h | 22 +- .../ITK/Code/Common/itkSobelOperator.txx | 124 +- Utilities/ITK/Code/Common/itkSparseImage.h | 33 +- Utilities/ITK/Code/Common/itkSparseImage.txx | 8 +- .../ITK/Code/Common/itkSpatialFunction.h | 10 +- .../ITK/Code/Common/itkSpatialOrientation.h | 525 +++-- .../Common/itkSpatialOrientationAdapter.cxx | 5 +- .../Common/itkSpatialOrientationAdapter.h | 6 +- .../Code/Common/itkSpecialCoordinatesImage.h | 25 +- .../Common/itkSpecialCoordinatesImage.txx | 10 +- .../Common/itkSphereSignedDistanceFunction.h | 12 +- .../Code/Common/itkSphereSpatialFunction.h | 17 +- .../ITK/Code/Common/itkStdStreamLogOutput.cxx | 19 +- .../ITK/Code/Common/itkStdStreamLogOutput.h | 14 +- .../Common/itkSumOfSquaresImageFunction.h | 25 +- .../Common/itkSumOfSquaresImageFunction.txx | 6 +- .../Code/Common/itkSymmetricEigenAnalysis.h | 275 ++- .../Code/Common/itkSymmetricEigenAnalysis.txx | 35 +- ...EllipsoidInteriorExteriorSpatialFunction.h | 14 +- ...lipsoidInteriorExteriorSpatialFunction.txx | 16 +- .../Common/itkSymmetricSecondRankTensor.h | 10 +- .../Common/itkSymmetricSecondRankTensor.txx | 98 +- .../ITK/Code/Common/itkTanImageAdaptor.h | 14 +- Utilities/ITK/Code/Common/itkTestMain.h | 22 +- .../ITK/Code/Common/itkTetrahedronCell.h | 12 +- .../ITK/Code/Common/itkTetrahedronCell.txx | 87 +- .../Common/itkTetrahedronCellTopology.cxx | 8 +- .../Code/Common/itkTetrahedronCellTopology.h | 14 +- .../itkThinPlateR2LogRSplineKernelTransform.h | 24 +- ...tkThinPlateR2LogRSplineKernelTransform.txx | 8 +- .../itkThinPlateSplineKernelTransform.h | 26 +- .../itkThinPlateSplineKernelTransform.txx | 10 +- Utilities/ITK/Code/Common/itkThreadLogger.cxx | 87 +- Utilities/ITK/Code/Common/itkThreadLogger.h | 21 +- .../Common/itkTimeProbesCollectorBase.cxx | 9 +- Utilities/ITK/Code/Common/itkTimeStamp.cxx | 17 +- Utilities/ITK/Code/Common/itkTimeStamp.h | 6 +- .../itkTorusInteriorExteriorSpatialFunction.h | 19 +- Utilities/ITK/Code/Common/itkTransform.h | 60 +- Utilities/ITK/Code/Common/itkTransform.txx | 10 +- Utilities/ITK/Code/Common/itkTransformBase.h | 10 +- .../ITK/Code/Common/itkTransformFactory.h | 6 +- .../Code/Common/itkTransformFactoryBase.cxx | 10 +- .../ITK/Code/Common/itkTransformFactoryBase.h | 14 +- .../ITK/Code/Common/itkTranslationTransform.h | 44 +- .../Code/Common/itkTranslationTransform.txx | 29 +- .../ITK/Code/Common/itkTreeChangeEvent.h | 47 +- Utilities/ITK/Code/Common/itkTreeContainer.h | 26 +- .../ITK/Code/Common/itkTreeContainer.txx | 11 +- .../ITK/Code/Common/itkTreeContainerBase.h | 13 +- .../ITK/Code/Common/itkTreeIteratorBase.h | 17 +- .../ITK/Code/Common/itkTreeIteratorBase.txx | 55 +- .../ITK/Code/Common/itkTreeIteratorClone.h | 26 +- Utilities/ITK/Code/Common/itkTreeNode.h | 8 +- Utilities/ITK/Code/Common/itkTreeNode.txx | 19 +- Utilities/ITK/Code/Common/itkTriangleCell.h | 10 +- Utilities/ITK/Code/Common/itkTriangleCell.txx | 79 +- .../Code/Common/itkTriangleCellTopology.cxx | 6 +- .../ITK/Code/Common/itkTriangleCellTopology.h | 15 +- .../Common/itkUnaryCorrespondenceMatrix.h | 10 +- .../Code/Common/itkValarrayImageContainer.h | 24 +- .../ITK/Code/Common/itkVariableLengthVector.h | 53 +- .../Code/Common/itkVariableLengthVector.txx | 32 +- .../Code/Common/itkVarianceImageFunction.h | 23 +- .../Code/Common/itkVarianceImageFunction.txx | 8 +- Utilities/ITK/Code/Common/itkVector.cxx | 10 +- Utilities/ITK/Code/Common/itkVector.h | 13 +- Utilities/ITK/Code/Common/itkVector.txx | 18 +- .../ITK/Code/Common/itkVectorContainer.h | 132 +- .../ITK/Code/Common/itkVectorContainer.txx | 14 +- Utilities/ITK/Code/Common/itkVectorImage.h | 17 +- Utilities/ITK/Code/Common/itkVectorImage.txx | 10 +- ...tkVectorImageNeighborhoodAccessorFunctor.h | 10 +- .../Common/itkVectorImageToImageAdaptor.h | 22 +- .../itkVectorInterpolateImageFunction.h | 18 +- .../itkVectorLinearInterpolateImageFunction.h | 10 +- ...tkVectorLinearInterpolateImageFunction.txx | 45 +- .../Code/Common/itkVectorMeanImageFunction.h | 23 +- .../Common/itkVectorMeanImageFunction.txx | 12 +- ...rNearestNeighborInterpolateImageFunction.h | 20 +- .../itkVectorNeighborhoodInnerProduct.h | 12 +- .../itkVectorNeighborhoodInnerProduct.txx | 10 +- .../Code/Common/itkVectorToRGBImageAdaptor.h | 18 +- .../Code/Common/itkVectorToRGBPixelAccessor.h | 5 +- Utilities/ITK/Code/Common/itkVersion.h | 22 +- .../Code/Common/itkVersorRigid3DTransform.h | 8 +- .../ITK/Code/Common/itkVersorTransform.h | 8 +- Utilities/ITK/Code/Common/itkVertexCell.txx | 7 +- .../Common/itkVolumeSplineKernelTransform.h | 57 +- .../itkWindowedSincInterpolateImageFunction.h | 4 +- .../Code/Common/itkXMLFileOutputWindow.cxx | 20 +- .../ITK/Code/Common/itkXMLFilterWatcher.h | 119 +- Utilities/ITK/Code/Common/itk_hashtable.h | 6 +- Utilities/ITK/Code/IO/CMakeLists.txt | 22 +- Utilities/ITK/Code/IO/itkAnalyzeImageIO.cxx | 1043 +++++----- Utilities/ITK/Code/IO/itkBMPImageIO.cxx | 11 +- .../ITK/Code/IO/itkBrains2HeaderBase.cxx | 6 +- .../ITK/Code/IO/itkDICOMSeriesFileNames.h | 6 +- Utilities/ITK/Code/IO/itkGDCMImageIO.cxx | 220 +- Utilities/ITK/Code/IO/itkGDCMImageIO.h | 41 +- .../ITK/Code/IO/itkGDCMSeriesFileNames.h | 10 +- Utilities/ITK/Code/IO/itkGE4ImageIO.cxx | 7 +- Utilities/ITK/Code/IO/itkGiplImageIO.cxx | 6 +- Utilities/ITK/Code/IO/itkIOCommon.cxx | 5 +- Utilities/ITK/Code/IO/itkImageFileReader.txx | 34 +- Utilities/ITK/Code/IO/itkImageIOBase.cxx | 54 +- Utilities/ITK/Code/IO/itkImageIOBase.h | 27 +- Utilities/ITK/Code/IO/itkImageIORegion.cxx | 8 +- Utilities/ITK/Code/IO/itkImageSeriesReader.h | 6 +- .../ITK/Code/IO/itkImageSeriesReader.txx | 6 +- Utilities/ITK/Code/IO/itkImageSeriesWriter.h | 14 +- .../ITK/Code/IO/itkImageSeriesWriter.txx | 128 +- Utilities/ITK/Code/IO/itkJPEGImageIO.cxx | 8 +- Utilities/ITK/Code/IO/itkJPEGImageIO.h | 8 +- Utilities/ITK/Code/IO/itkMetaArrayWriter.h | 8 +- Utilities/ITK/Code/IO/itkMetaImageIO.cxx | 114 +- Utilities/ITK/Code/IO/itkMetaImageIO.h | 6 +- Utilities/ITK/Code/IO/itkNiftiImageIO.cxx | 773 ++++--- Utilities/ITK/Code/IO/itkNiftiImageIO.h | 6 +- .../ITK/Code/IO/itkNumericSeriesFileNames.h | 10 +- Utilities/ITK/Code/IO/itkPNGImageIO.h | 6 +- Utilities/ITK/Code/IO/itkRawImageIO.h | 6 +- .../itkRegularExpressionSeriesFileNames.cxx | 7 +- .../IO/itkRegularExpressionSeriesFileNames.h | 8 +- .../ITK/Code/IO/itkSiemensVisionImageIO.cxx | 10 +- .../ITK/Code/IO/itkSpatialObjectWriter.h | 8 +- Utilities/ITK/Code/IO/itkStimulateImageIO.cxx | 34 +- Utilities/ITK/Code/IO/itkTIFFImageIO.cxx | 6 +- .../ITK/Code/IO/itkTransformFileWriter.h | 6 +- Utilities/ITK/Code/IO/itkVTKImageIO.cxx | 9 +- Utilities/ITK/Code/Numerics/CMakeLists.txt | 7 +- .../itkFEMElement2DC0LinearQuadrilateral.cxx | 6 +- .../Code/Numerics/FEM/itkFEMObjectFactory.h | 5 +- .../FEM/itkFEMSolverCrankNicolson.cxx | 20 +- .../itkGaussianTransferFunction.txx | 6 +- .../Numerics/NeuralNetworks/itkRBFLayer.h | 12 +- .../Numerics/NeuralNetworks/itkRBFNetwork.h | 12 +- .../Code/Numerics/Statistics/CMakeLists.txt | 26 +- .../Statistics/itkChiSquareDistribution.cxx | 106 +- .../Statistics/itkCovarianceCalculator.h | 19 +- .../Statistics/itkCovarianceCalculator.txx | 81 +- .../Statistics/itkDenseFrequencyContainer.cxx | 25 +- .../Statistics/itkDenseFrequencyContainer.h | 49 +- .../Numerics/Statistics/itkDensityFunction.h | 25 +- .../Numerics/Statistics/itkDistanceMetric.h | 36 +- .../Numerics/Statistics/itkDistanceMetric.txx | 17 +- .../itkDistanceToCentroidMembershipFunction.h | 23 +- ...tkDistanceToCentroidMembershipFunction.txx | 18 +- .../Statistics/itkEuclideanDistance.h | 36 +- .../Statistics/itkEuclideanDistance.txx | 55 +- ...ctationMaximizationMixtureModelEstimator.h | 95 +- ...ationMaximizationMixtureModelEstimator.txx | 205 +- .../Statistics/itkGaussianDensityFunction.h | 58 +- .../Statistics/itkGaussianDensityFunction.txx | 70 +- .../Statistics/itkGaussianDistribution.cxx | 114 +- .../Statistics/itkGaussianDistribution.h | 10 +- .../itkGaussianGoodnessOfFitComponent.h | 99 +- .../itkGaussianGoodnessOfFitComponent.txx | 159 +- .../itkGaussianMixtureModelComponent.h | 61 +- .../itkGaussianMixtureModelComponent.txx | 183 +- .../itkGoodnessOfFitComponentBase.h | 157 +- .../itkGoodnessOfFitComponentBase.txx | 222 +- .../Statistics/itkGoodnessOfFitFunctionBase.h | 72 +- .../itkGoodnessOfFitFunctionBase.txx | 57 +- ...itkGoodnessOfFitMixtureModelCostFunction.h | 62 +- ...kGoodnessOfFitMixtureModelCostFunction.txx | 82 +- ...renceMatrixTextureCoefficientsCalculator.h | 253 +-- ...nceMatrixTextureCoefficientsCalculator.txx | 312 +-- .../Code/Numerics/Statistics/itkHistogram.h | 336 ++-- .../Code/Numerics/Statistics/itkHistogram.txx | 277 ++- .../itkHistogramToEntropyImageFilter.h | 17 +- .../Statistics/itkHistogramToImageFilter.h | 4 +- .../itkHistogramToIntensityImageFilter.h | 20 +- .../itkHistogramToLogProbabilityImageFilter.h | 22 +- .../itkHistogramToProbabilityImageFilter.h | 17 +- .../itkHypersphereKernelMeanShiftModeSeeker.h | 45 +- ...tkHypersphereKernelMeanShiftModeSeeker.txx | 49 +- .../itkImageToCooccurrenceListAdaptor.h | 53 +- .../itkImageToCooccurrenceListAdaptor.txx | 51 +- .../Statistics/itkImageToHistogramGenerator.h | 16 +- .../itkImageToHistogramGenerator.txx | 20 +- .../Statistics/itkImageToListAdaptor.h | 130 +- .../Statistics/itkImageToListAdaptor.txx | 15 +- .../itkJointDomainImageToListAdaptor.h | 182 +- .../itkJointDomainImageToListAdaptor.txx | 21 +- .../ITK/Code/Numerics/Statistics/itkKdTree.h | 176 +- .../Code/Numerics/Statistics/itkKdTree.txx | 18 +- .../itkKdTreeBasedKmeansEstimator.h | 205 +- .../itkKdTreeBasedKmeansEstimator.txx | 265 ++- .../Numerics/Statistics/itkKdTreeGenerator.h | 22 +- .../Statistics/itkKdTreeGenerator.txx | 8 +- .../Code/Numerics/Statistics/itkListSample.h | 195 +- .../Numerics/Statistics/itkListSample.txx | 18 +- .../Numerics/Statistics/itkListSampleBase.h | 64 +- .../itkListSampleToHistogramFilter.h | 36 +- .../itkListSampleToHistogramFilter.txx | 34 +- .../itkListSampleToHistogramGenerator.h | 54 +- .../itkListSampleToHistogramGenerator.txx | 52 +- .../itkLogLikelihoodGoodnessOfFitFunction.h | 35 +- .../itkLogLikelihoodGoodnessOfFitFunction.txx | 39 +- ...itkMahalanobisDistanceMembershipFunction.h | 22 +- ...kMahalanobisDistanceMembershipFunction.txx | 28 +- ...geToGreyLevelCooccurrenceMatrixGenerator.h | 142 +- ...ToGreyLevelCooccurrenceMatrixGenerator.txx | 170 +- .../Numerics/Statistics/itkMeanCalculator.h | 33 +- .../Numerics/Statistics/itkMeanCalculator.txx | 31 +- .../Statistics/itkMeanShiftModeCacheMethod.h | 83 +- .../itkMeanShiftModeCacheMethod.txx | 119 +- .../Statistics/itkMeanShiftModeSeekerBase.h | 56 +- .../Statistics/itkMeanShiftModeSeekerBase.txx | 59 +- .../Statistics/itkMeasurementVectorTraits.h | 21 +- .../Statistics/itkMembershipFunctionBase.h | 29 +- .../Numerics/Statistics/itkMembershipSample.h | 178 +- .../Statistics/itkMembershipSample.txx | 82 +- .../Statistics/itkMembershipSampleGenerator.h | 48 +- .../itkMembershipSampleGenerator.txx | 54 +- .../Statistics/itkMixtureModelComponentBase.h | 77 +- .../itkMixtureModelComponentBase.txx | 71 +- .../Statistics/itkNeighborhoodSampler.h | 78 +- .../Statistics/itkNeighborhoodSampler.txx | 72 +- .../Statistics/itkNormalVariateGenerator.cxx | 183 +- .../Statistics/itkNormalVariateGenerator.h | 44 +- .../Statistics/itkPointSetToListAdaptor.h | 126 +- .../Statistics/itkPointSetToListAdaptor.txx | 35 +- .../Statistics/itkProbabilityDistribution.h | 6 +- .../itkRandomVariateGeneratorBase.h | 20 +- .../ITK/Code/Numerics/Statistics/itkSample.h | 46 +- .../Statistics/itkSampleAlgorithmBase.h | 41 +- .../Statistics/itkSampleAlgorithmBase.txx | 13 +- .../Numerics/Statistics/itkSampleClassifier.h | 61 +- .../Statistics/itkSampleClassifier.txx | 82 +- .../Statistics/itkSampleClassifierWithMask.h | 60 +- .../itkSampleClassifierWithMask.txx | 102 +- .../itkSampleMeanShiftBlurringFilter.h | 45 +- .../itkSampleMeanShiftBlurringFilter.txx | 31 +- .../itkSampleMeanShiftClusteringFilter.h | 55 +- .../itkSampleMeanShiftClusteringFilter.txx | 113 +- ...tkSampleSelectiveMeanShiftBlurringFilter.h | 39 +- ...SampleSelectiveMeanShiftBlurringFilter.txx | 39 +- .../itkSampleToHistogramProjectionFilter.h | 78 +- .../itkSampleToHistogramProjectionFilter.txx | 176 +- .../itkScalarImageTextureCalculator.h | 23 +- .../itkScalarImageTextureCalculator.txx | 96 +- ...geToGreyLevelCooccurrenceMatrixGenerator.h | 274 +-- ...ToGreyLevelCooccurrenceMatrixGenerator.txx | 266 +-- .../itkScalarImageToHistogramGenerator.h | 16 +- .../itkScalarImageToHistogramGenerator.txx | 23 +- .../Statistics/itkScalarImageToListAdaptor.h | 22 +- .../itkScalarImageToListAdaptor.txx | 15 +- .../itkSelectiveSubsampleGenerator.h | 52 +- .../itkSelectiveSubsampleGenerator.txx | 50 +- .../itkSparseFrequencyContainer.cxx | 25 +- .../Statistics/itkSparseFrequencyContainer.h | 50 +- .../Statistics/itkStatisticsAlgorithm.h | 35 +- .../Statistics/itkStatisticsAlgorithm.txx | 186 +- .../Code/Numerics/Statistics/itkSubsample.h | 288 ++- .../Code/Numerics/Statistics/itkSubsample.txx | 45 +- .../Numerics/Statistics/itkTDistribution.cxx | 110 +- .../itkVariableDimensionHistogram.h | 321 ++- .../itkVariableDimensionHistogram.txx | 260 ++- .../itkWeightedCentroidKdTreeGenerator.h | 52 +- .../itkWeightedCentroidKdTreeGenerator.txx | 8 +- .../itkWeightedCovarianceCalculator.h | 25 +- .../itkWeightedCovarianceCalculator.txx | 27 +- .../Statistics/itkWeightedMeanCalculator.h | 47 +- .../Statistics/itkWeightedMeanCalculator.txx | 83 +- .../Numerics/itkCacheableScalarFunction.h | 6 +- .../itkCumulativeGaussianCostFunction.cxx | 6 +- .../itkCumulativeGaussianCostFunction.h | 6 +- .../itkCumulativeGaussianOptimizer.cxx | 8 +- .../ITK/Code/Numerics/itkFRPROptimizer.cxx | 6 +- .../itkMultipleValuedVnlCostFunctionAdaptor.h | 6 +- .../itkMultivariateLegendrePolynomial.h | 6 +- .../ITK/Code/Numerics/itkPowellOptimizer.cxx | 12 +- .../ITK/Code/Numerics/itkSPSAOptimizer.cxx | 15 +- .../ITK/Code/Numerics/itkSPSAOptimizer.h | 6 +- .../itkSingleValuedVnlCostFunctionAdaptor.h | 6 +- ...tkActiveShapeModelGradientSearchMethod.txx | 6 +- ...SimpleFuzzyConnectednessRGBImageFilter.txx | 6 +- ...pleFuzzyConnectednessScalarImageFilter.txx | 6 +- ...itkVectorFuzzyConnectednessImageFilter.txx | 6 +- Utilities/ITK/Code/Review/CMakeLists.txt | 4 + .../ITK/Code/Review/Statistics/CMakeLists.txt | 42 + .../Statistics/itkChiSquareDistribution.cxx | 379 ++++ .../Statistics/itkChiSquareDistribution.h | 210 ++ .../Statistics/itkCovarianceSampleFilter.h | 120 ++ .../Statistics/itkCovarianceSampleFilter.txx | 262 +++ .../Review/Statistics/itkDecisionRule.cxx | 40 + .../Code/Review/Statistics/itkDecisionRule.h | 70 + .../itkDenseFrequencyContainer2.cxx | 92 + .../Statistics/itkDenseFrequencyContainer2.h | 124 ++ .../Review/Statistics/itkDistanceMetric.h | 144 ++ .../Review/Statistics/itkDistanceMetric.txx | 81 + .../itkDistanceToCentroidMembershipFunction.h | 103 + ...tkDistanceToCentroidMembershipFunction.txx | 97 + .../Statistics/itkEuclideanDistanceMetric.h | 79 + .../Statistics/itkEuclideanDistanceMetric.txx | 82 + .../itkEuclideanSquareDistanceMetric.h | 72 + .../itkEuclideanSquareDistanceMetric.txx | 74 + ...ctationMaximizationMixtureModelEstimator.h | 200 ++ ...ationMaximizationMixtureModelEstimator.txx | 431 ++++ .../Statistics/itkGaussianDistribution.cxx | 525 +++++ .../Statistics/itkGaussianDistribution.h | 240 +++ .../itkGaussianMembershipFunction.h | 112 ++ .../itkGaussianMembershipFunction.txx | 188 ++ .../itkGaussianMixtureModelComponent.h | 119 ++ .../itkGaussianMixtureModelComponent.txx | 312 +++ .../ITK/Code/Review/Statistics/itkHistogram.h | 501 +++++ .../Code/Review/Statistics/itkHistogram.txx | 746 +++++++ .../itkHistogramToTextureFeaturesFilter.h | 220 ++ .../itkHistogramToTextureFeaturesFilter.txx | 451 +++++ .../Statistics/itkImageClassifierFilter.h | 176 ++ .../Statistics/itkImageClassifierFilter.txx | 213 ++ .../Statistics/itkImageToHistogramFilter.h | 163 ++ .../Statistics/itkImageToHistogramFilter.txx | 147 ++ .../Statistics/itkImageToListSampleAdaptor.h | 304 +++ .../itkImageToListSampleAdaptor.txx | 144 ++ .../Statistics/itkImageToListSampleFilter.h | 144 ++ .../Statistics/itkImageToListSampleFilter.txx | 228 +++ .../itkJointDomainImageToListSampleAdaptor.h | 373 ++++ ...itkJointDomainImageToListSampleAdaptor.txx | 169 ++ .../ITK/Code/Review/Statistics/itkKdTree.h | 760 +++++++ .../ITK/Code/Review/Statistics/itkKdTree.txx | 665 ++++++ .../itkKdTreeBasedKmeansEstimator.h | 324 +++ .../itkKdTreeBasedKmeansEstimator.txx | 506 +++++ .../Review/Statistics/itkKdTreeGenerator.h | 204 ++ .../Review/Statistics/itkKdTreeGenerator.txx | 245 +++ .../Code/Review/Statistics/itkListSample.h | 289 +++ .../Code/Review/Statistics/itkListSample.txx | 162 ++ ...itkMahalanobisDistanceMembershipFunction.h | 143 ++ ...kMahalanobisDistanceMembershipFunction.txx | 257 +++ .../Statistics/itkMahalanobisDistanceMetric.h | 139 ++ .../itkMahalanobisDistanceMetric.txx | 237 +++ .../Statistics/itkManhattanDistanceMetric.h | 75 + .../Statistics/itkManhattanDistanceMetric.txx | 72 + .../Statistics/itkMaximumDecisionRule2.cxx | 46 + .../Statistics/itkMaximumDecisionRule2.h | 65 + .../itkMaximumRatioDecisionRule2.cxx | 103 + .../Statistics/itkMaximumRatioDecisionRule2.h | 92 + .../Review/Statistics/itkMeanSampleFilter.h | 105 + .../Review/Statistics/itkMeanSampleFilter.txx | 150 ++ .../Statistics/itkMeasurementVectorTraits.h | 703 +++++++ .../Statistics/itkMembershipFunctionBase.h | 120 ++ .../Review/Statistics/itkMembershipSample.h | 318 +++ .../Review/Statistics/itkMembershipSample.txx | 170 ++ .../Statistics/itkMinimumDecisionRule2.cxx | 46 + .../Statistics/itkMinimumDecisionRule2.h | 65 + .../Statistics/itkMixtureModelComponentBase.h | 166 ++ .../itkMixtureModelComponentBase.txx | 186 ++ .../Statistics/itkNeighborhoodSampler.h | 93 + .../Statistics/itkNeighborhoodSampler.txx | 80 + .../Statistics/itkNormalVariateGenerator.cxx | 361 ++++ .../Statistics/itkNormalVariateGenerator.h | 148 ++ .../itkPointSetToListSampleAdaptor.h | 287 +++ .../itkPointSetToListSampleAdaptor.txx | 131 ++ .../Statistics/itkProbabilityDistribution.h | 171 ++ .../itkRandomVariateGeneratorBase.h | 55 + .../ITK/Code/Review/Statistics/itkSample.h | 199 ++ .../Statistics/itkSampleClassifierFilter.h | 163 ++ .../Statistics/itkSampleClassifierFilter.txx | 217 ++ .../Statistics/itkSampleToHistogramFilter.h | 149 ++ .../Statistics/itkSampleToHistogramFilter.txx | 325 +++ .../Statistics/itkSampleToSubsampleFilter.h | 101 + .../Statistics/itkSampleToSubsampleFilter.txx | 97 + ...calarImageToCooccurrenceListSampleFilter.h | 131 ++ ...larImageToCooccurrenceListSampleFilter.txx | 191 ++ ...itkScalarImageToCooccurrenceMatrixFilter.h | 211 ++ ...kScalarImageToCooccurrenceMatrixFilter.txx | 413 ++++ .../itkScalarImageToHistogramGenerator.h | 133 ++ .../itkScalarImageToHistogramGenerator.txx | 126 ++ .../itkScalarImageToTextureFeaturesFilter.h | 230 +++ .../itkScalarImageToTextureFeaturesFilter.txx | 357 ++++ .../itkSparseFrequencyContainer2.cxx | 97 + .../Statistics/itkSparseFrequencyContainer2.h | 112 ++ ...tandardDeviationPerComponentSampleFilter.h | 116 ++ ...ndardDeviationPerComponentSampleFilter.txx | 243 +++ .../Statistics/itkStatisticsAlgorithm.h | 149 ++ .../Statistics/itkStatisticsAlgorithm.txx | 708 +++++++ .../ITK/Code/Review/Statistics/itkSubsample.h | 290 +++ .../Code/Review/Statistics/itkSubsample.txx | 249 +++ .../Review/Statistics/itkTDistribution.cxx | 443 ++++ .../Code/Review/Statistics/itkTDistribution.h | 212 ++ .../itkWeightedCentroidKdTreeGenerator.h | 125 ++ .../itkWeightedCentroidKdTreeGenerator.txx | 148 ++ .../itkWeightedCovarianceSampleFilter.h | 113 ++ .../itkWeightedCovarianceSampleFilter.txx | 288 +++ .../Statistics/itkWeightedMeanSampleFilter.h | 105 + .../itkWeightedMeanSampleFilter.txx | 207 ++ .../Review/itkAnchorErodeDilateImageFilter.h | 6 +- .../Review/itkAnchorOpenCloseImageFilter.txx | 24 +- .../ITK/Code/Review/itkAnchorUtilities.txx | 24 +- .../itkAtanRegularizedHeavisideStepFunction.h | 95 + .../itkAttributeMorphologyBaseImageFilter.h | 6 +- .../Code/Review/itkAutumnColormapFunctor.h | 76 + .../Code/Review/itkAutumnColormapFunctor.txx | 56 + ...itkBSplineDeformableTransformInitializer.h | 137 ++ ...kBSplineDeformableTransformInitializer.txx | 154 ++ ...SplineScatteredDataPointSetToImageFilter.h | 20 +- ...lineScatteredDataPointSetToImageFilter.txx | 111 +- .../Code/Review/itkBasicDilateImageFilter.h | 11 +- .../Code/Review/itkBasicDilateImageFilter.txx | 8 +- .../Code/Review/itkBasicErodeImageFilter.h | 11 +- .../Code/Review/itkBasicErodeImageFilter.txx | 10 +- .../Code/Review/itkBinaryContourImageFilter.h | 8 +- .../Review/itkBinaryContourImageFilter.txx | 31 +- ...itkBinaryMorphologicalClosingImageFilter.h | 6 +- ...itkBinaryMorphologicalOpeningImageFilter.h | 8 +- .../ITK/Code/Review/itkBlueColormapFunctor.h | 77 + .../Code/Review/itkBlueColormapFunctor.txx | 49 + .../ITK/Code/Review/itkBruker2DSEQImageIO.cxx | 454 +++-- .../ITK/Code/Review/itkColormapFunctor.h | 153 ++ ...tkComplexBSplineInterpolateImageFunction.h | 152 ++ ...ComplexBSplineInterpolateImageFunction.txx | 104 + .../itkConformalFlatteningMeshFilter.txx | 6 +- ...nedRegionBasedLevelSetFunctionSharedData.h | 190 ++ .../itkContourExtractor2DImageFilter.txx | 20 +- .../ITK/Code/Review/itkCoolColormapFunctor.h | 78 + .../Code/Review/itkCoolColormapFunctor.txx | 56 + .../Code/Review/itkCopperColormapFunctor.h | 78 + .../Code/Review/itkCopperColormapFunctor.txx | 57 + .../itkCoxDeBoorBSplineKernelFunction.h | 6 +- .../itkCoxDeBoorBSplineKernelFunction.txx | 10 +- Utilities/ITK/Code/Review/itkCrossHelper.h | 26 +- .../Code/Review/itkCustomColormapFunctor.h | 112 ++ .../Code/Review/itkCustomColormapFunctor.txx | 98 + ...itkDiffeomorphicDemonsRegistrationFilter.h | 6 +- ...kDiffeomorphicDemonsRegistrationFilter.txx | 7 +- ...tFourierReconstructionImageToImageFilter.h | 174 ++ ...ourierReconstructionImageToImageFilter.txx | 447 +++++ ...itkDiscreteGaussianDerivativeImageFilter.h | 14 +- ...kDiscreteGaussianDerivativeImageFunction.h | 18 +- ...teGradientMagnitudeGaussianImageFunction.h | 16 +- .../itkDiscreteHessianGaussianImageFunction.h | 16 +- ...tkExponentialDeformationFieldImageFilter.h | 10 +- ...ExponentialDeformationFieldImageFilter.txx | 6 +- .../itkFFTComplexToComplexImageFilter.h | 6 +- .../itkFFTWComplexToComplexImageFilter.h | 6 +- .../itkFastApproximateRankImageFilter.h | 6 +- ...ymmetricForcesDemonsRegistrationFilter.txx | 8 +- .../Code/Review/itkFlatStructuringElement.txx | 28 +- .../Review/itkGaussianDerivativeOperator.txx | 15 +- .../ITK/Code/Review/itkGreenColormapFunctor.h | 77 + .../Code/Review/itkGreenColormapFunctor.txx | 49 + .../ITK/Code/Review/itkGreyColormapFunctor.h | 77 + .../Code/Review/itkGreyColormapFunctor.txx | 49 + .../Review/itkGridForwardWarpImageFilter.h | 8 +- .../Review/itkGridForwardWarpImageFilter.txx | 12 +- .../ITK/Code/Review/itkGridImageSource.h | 179 ++ .../ITK/Code/Review/itkGridImageSource.txx | 167 ++ .../ITK/Code/Review/itkHSVColormapFunctor.h | 77 + .../ITK/Code/Review/itkHSVColormapFunctor.txx | 63 + .../Code/Review/itkHeavisideStepFunction.h | 98 + .../Review/itkHeavisideStepFunctionBase.h | 82 + ...itkHessianToObjectnessMeasureImageFilter.h | 20 +- ...kHessianToObjectnessMeasureImageFilter.txx | 19 +- .../ITK/Code/Review/itkHotColormapFunctor.h | 77 + .../ITK/Code/Review/itkHotColormapFunctor.txx | 62 + .../ITK/Code/Review/itkJetColormapFunctor.h | 77 + .../ITK/Code/Review/itkJetColormapFunctor.txx | 62 + .../itkKappaSigmaThresholdImageCalculator.h | 10 +- .../itkKappaSigmaThresholdImageFilter.h | 16 +- .../Code/Review/itkLabelContourImageFilter.h | 6 +- .../Review/itkLabelImageToLabelMapFilter.h | 119 ++ .../Review/itkLabelImageToLabelMapFilter.txx | 187 ++ Utilities/ITK/Code/Review/itkLabelMap.h | 291 +++ Utilities/ITK/Code/Review/itkLabelMap.txx | 507 +++++ Utilities/ITK/Code/Review/itkLabelMapFilter.h | 132 ++ .../ITK/Code/Review/itkLabelMapFilter.txx | 160 ++ .../Review/itkLabelMapToLabelImageFilter.h | 98 + .../Review/itkLabelMapToLabelImageFilter.txx | 72 + Utilities/ITK/Code/Review/itkLabelObject.h | 163 ++ Utilities/ITK/Code/Review/itkLabelObject.txx | 327 +++ .../ITK/Code/Review/itkLabelObjectLine.h | 96 + .../ITK/Code/Review/itkLabelObjectLine.txx | 152 ++ .../Review/itkLabelObjectLineComparator.h | 66 + .../itkMaskedMovingHistogramImageFilter.h | 12 +- .../ITK/Code/Review/itkMaskedRankHistogram.h | 14 +- .../Code/Review/itkMaskedRankImageFilter.h | 6 +- .../ITK/Code/Review/itkMatlabTransformIO.cxx | 14 +- .../itkMorphologicalWatershedImageFilter.h | 6 +- .../itkMovingHistogramImageFilterBase.h | 6 +- .../itkMovingHistogramMorphologyImageFilter.h | 6 +- ...MultiScaleHessianBasedMeasureImageFilter.h | 87 +- ...ltiScaleHessianBasedMeasureImageFilter.txx | 166 +- ...ltiphaseDenseFiniteDifferenceImageFilter.h | 231 +++ ...iphaseDenseFiniteDifferenceImageFilter.txx | 297 +++ ...itkMultiphaseFiniteDifferenceImageFilter.h | 520 +++++ ...kMultiphaseFiniteDifferenceImageFilter.txx | 319 +++ ...tiphaseSparseFiniteDifferenceImageFilter.h | 530 +++++ ...phaseSparseFiniteDifferenceImageFilter.txx | 1363 +++++++++++++ ...AdaptiveHistogramEqualizationImageFilter.h | 10 +- .../itkOptBSplineInterpolateImageFunction.h | 8 +- .../Review/itkOptBlackTopHatImageFilter.h | 6 +- .../Review/itkOptGrayscaleDilateImageFilter.h | 8 +- .../Review/itkOptGrayscaleErodeImageFilter.h | 8 +- ...GrayscaleMorphologicalClosingImageFilter.h | 6 +- ...GrayscaleMorphologicalOpeningImageFilter.h | 6 +- .../itkOptLinearInterpolateImageFunction.h | 7 +- .../itkOptLinearInterpolateImageFunction.txx | 10 +- ...itkOptMatchCardinalityImageToImageMetric.h | 6 +- ...kOptMatchCardinalityImageToImageMetric.txx | 8 +- .../itkOptMorphologicalGradientImageFilter.h | 6 +- .../Code/Review/itkOptMorphologyImageFilter.h | 6 +- .../Code/Review/itkOptNoiseImageFilter.txx | 6 +- .../Code/Review/itkOptResampleImageFilter.h | 8 +- .../Review/itkOptWhiteTopHatImageFilter.h | 6 +- .../Code/Review/itkOverUnderColormapFunctor.h | 77 + .../Review/itkOverUnderColormapFunctor.txx | 69 + Utilities/ITK/Code/Review/itkPhilipsPAR.cxx | 1780 +++++++---------- Utilities/ITK/Code/Review/itkPhilipsPAR.h | 202 +- .../ITK/Code/Review/itkPhilipsRECImageIO.cxx | 237 ++- .../ITK/Code/Review/itkPhilipsRECImageIO.h | 70 +- .../Code/Review/itkPhilipsRECImageIOFactory.h | 8 +- .../Code/Review/itkPriorityQueueContainer.h | 20 +- Utilities/ITK/Code/Review/itkQuadEdge.h | 6 +- Utilities/ITK/Code/Review/itkQuadEdgeMesh.h | 7 +- Utilities/ITK/Code/Review/itkQuadEdgeMesh.txx | 14 +- .../Review/itkQuadEdgeMeshBorderTransform.h | 8 +- .../Review/itkQuadEdgeMeshBorderTransform.txx | 131 +- .../Code/Review/itkQuadEdgeMeshCleanFilter.h | 7 +- .../itkQuadEdgeMeshDecimationCriteria.h | 6 +- .../Review/itkQuadEdgeMeshDecimationFilter.h | 29 +- .../itkQuadEdgeMeshDelaunayConformingFilter.h | 6 +- ...tkQuadEdgeMeshDelaunayConformingFilter.txx | 23 +- ...tkQuadEdgeMeshDiscreteCurvatureEstimator.h | 14 +- ...kQuadEdgeMeshEdgeMergeDecimationFilter.txx | 5 +- ...uadEdgeMeshEulerOperatorFlipEdgeFunction.h | 6 +- ...dEdgeMeshEulerOperatorJoinVertexFunction.h | 8 +- .../Code/Review/itkQuadEdgeMeshNormalFilter.h | 6 +- .../Review/itkQuadEdgeMeshNormalFilter.txx | 55 +- .../ITK/Code/Review/itkQuadEdgeMeshParam.txx | 14 +- .../Code/Review/itkQuadEdgeMeshSmoothing.h | 9 +- .../Code/Review/itkQuadEdgeMeshSmoothing.txx | 51 +- .../itkQuadEdgeMeshToQuadEdgeMeshFilter.h | 6 +- .../itkQuadEdgeMeshToQuadEdgeMeshFilter.txx | 6 +- .../Review/itkQuadEdgeMeshTopologyChecker.h | 6 +- Utilities/ITK/Code/Review/itkRankHistogram.h | 16 +- .../ITK/Code/Review/itkRankImageFilter.h | 6 +- .../ITK/Code/Review/itkRedColormapFunctor.h | 77 + .../ITK/Code/Review/itkRedColormapFunctor.txx | 49 + .../Review/itkRegionBasedLevelSetFunction.h | 395 ++++ .../Review/itkRegionBasedLevelSetFunction.txx | 412 ++++ .../itkRegionBasedLevelSetFunctionData.h | 149 ++ .../itkRegionBasedLevelSetFunctionData.txx | 89 + ...itkRegionBasedLevelSetFunctionSharedData.h | 188 ++ .../itkRegularizedHeavisideStepFunction.h | 117 ++ .../itkRobustAutomaticThresholdCalculator.h | 6 +- .../itkRobustAutomaticThresholdImageFilter.h | 12 +- ...calarChanAndVeseDenseLevelSetImageFilter.h | 156 ++ ...larChanAndVeseDenseLevelSetImageFilter.txx | 134 ++ .../itkScalarChanAndVeseLevelSetFunction.h | 149 ++ .../itkScalarChanAndVeseLevelSetFunction.txx | 194 ++ ...itkScalarChanAndVeseLevelSetFunctionData.h | 123 ++ ...alarChanAndVeseSparseLevelSetImageFilter.h | 157 ++ ...arChanAndVeseSparseLevelSetImageFilter.txx | 139 ++ .../itkScalarRegionBasedLevelSetFunction.h | 153 ++ .../itkScalarRegionBasedLevelSetFunction.txx | 133 ++ .../itkScalarToRGBColormapImageFilter.h | 138 ++ .../itkScalarToRGBColormapImageFilter.txx | 275 +++ ...odFilledFunctionConditionalConstIterator.h | 7 +- ...ledImageFunctionConditionalConstIterator.h | 7 +- ...odFilledImageFunctionConditionalIterator.h | 7 +- .../Review/itkSharedMorphologyUtilities.txx | 23 +- .../itkSinRegularizedHeavisideStepFunction.h | 119 ++ .../Code/Review/itkSliceBySliceImageFilter.h | 8 +- .../Code/Review/itkSpringColormapFunctor.h | 77 + .../Code/Review/itkSpringColormapFunctor.txx | 56 + ...itkStochasticFractalDimensionImageFilter.h | 117 ++ ...kStochasticFractalDimensionImageFilter.txx | 232 +++ .../Code/Review/itkSummerColormapFunctor.h | 77 + .../Code/Review/itkSummerColormapFunctor.txx | 56 + .../itkTransformFileWriterWithFactory.h | 6 +- .../ITK/Code/Review/itkTransformIOBase.h | 9 +- .../itkTransformToDeformationFieldSource.txx | 189 +- Utilities/ITK/Code/Review/itkTriangleHelper.h | 200 +- .../ITK/Code/Review/itkTriangleHelper.txx | 238 +++ .../ITK/Code/Review/itkTxtTransformIO.cxx | 14 +- ...nedRegionBasedLevelSetFunctionSharedData.h | 147 ++ .../ITK/Code/Review/itkVTKPolyDataReader.txx | 5 +- .../ITK/Code/Review/itkVTKPolyDataWriter.txx | 56 +- .../itkValuedRegionalExtremaImageFilter.h | 6 +- ...tkVanHerkGilWermanErodeDilateImageFilter.h | 6 +- .../Review/itkVanHerkGilWermanUtilities.txx | 24 +- .../itkVectorCentralDifferenceImageFunction.h | 23 +- ...tkVectorCentralDifferenceImageFunction.txx | 49 +- ...earestNeighborExtrapolateImageFunction.txx | 10 +- .../Review/itkWarpHarmonicEnergyCalculator.h | 8 +- .../Code/Review/itkWinterColormapFunctor.h | 77 + .../Code/Review/itkWinterColormapFunctor.txx | 56 + .../SpatialObject/itkAffineGeometryFrame.h | 9 +- .../SpatialObject/itkAffineGeometryFrame.txx | 32 +- .../SpatialObject/itkArrowSpatialObject.h | 6 +- .../Code/SpatialObject/itkBlobSpatialObject.h | 6 +- .../SpatialObject/itkBlobSpatialObject.txx | 6 +- .../Code/SpatialObject/itkBoxSpatialObject.h | 6 +- .../SpatialObject/itkContourSpatialObject.h | 6 +- .../itkContourSpatialObjectPoint.h | 6 +- .../itkCylinderSpatialObject.cxx | 5 +- .../SpatialObject/itkCylinderSpatialObject.h | 6 +- .../SpatialObject/itkDTITubeSpatialObject.h | 6 +- .../itkDTITubeSpatialObjectPoint.h | 6 +- .../SpatialObject/itkEllipseSpatialObject.h | 6 +- .../SpatialObject/itkEllipseSpatialObject.txx | 5 +- .../SpatialObject/itkGaussianSpatialObject.h | 26 +- .../itkGaussianSpatialObject.txx | 29 +- .../SpatialObject/itkGroupSpatialObject.h | 6 +- .../SpatialObject/itkImageMaskSpatialObject.h | 6 +- .../SpatialObject/itkImageSpatialObject.h | 6 +- .../SpatialObject/itkImageSpatialObject.txx | 6 +- .../SpatialObject/itkLandmarkSpatialObject.h | 6 +- .../Code/SpatialObject/itkLineSpatialObject.h | 6 +- .../SpatialObject/itkLineSpatialObjectPoint.h | 6 +- .../Code/SpatialObject/itkMeshSpatialObject.h | 6 +- .../SpatialObject/itkMetaArrowConverter.h | 6 +- .../Code/SpatialObject/itkMetaBlobConverter.h | 6 +- .../SpatialObject/itkMetaContourConverter.h | 6 +- .../SpatialObject/itkMetaDTITubeConverter.h | 6 +- .../SpatialObject/itkMetaEllipseConverter.h | 6 +- .../ITK/Code/SpatialObject/itkMetaEvent.h | 6 +- .../SpatialObject/itkMetaGaussianConverter.h | 6 +- .../SpatialObject/itkMetaGroupConverter.h | 6 +- .../SpatialObject/itkMetaImageConverter.h | 6 +- .../SpatialObject/itkMetaLandmarkConverter.h | 6 +- .../Code/SpatialObject/itkMetaLineConverter.h | 6 +- .../Code/SpatialObject/itkMetaMeshConverter.h | 6 +- .../SpatialObject/itkMetaSceneConverter.h | 6 +- .../SpatialObject/itkMetaSurfaceConverter.h | 6 +- .../Code/SpatialObject/itkMetaTubeConverter.h | 6 +- .../itkMetaVesselTubeConverter.h | 6 +- .../SpatialObject/itkPlaneSpatialObject.h | 6 +- .../SpatialObject/itkPlaneSpatialObject.txx | 6 +- .../itkPointBasedSpatialObject.h | 6 +- .../itkPolygonGroupSpatialObject.h | 8 +- .../SpatialObject/itkPolygonSpatialObject.h | 44 +- .../SpatialObject/itkPolygonSpatialObject.txx | 117 +- .../SpatialObject/itkSceneSpatialObject.h | 6 +- .../ITK/Code/SpatialObject/itkSpatialObject.h | 5 +- .../SpatialObject/itkSpatialObjectFactory.h | 6 +- .../itkSpatialObjectFactoryBase.h | 6 +- .../SpatialObject/itkSpatialObjectPoint.h | 6 +- .../itkSpatialObjectTreeContainer.h | 6 +- .../SpatialObject/itkSpatialObjectTreeNode.h | 14 +- .../SpatialObject/itkSurfaceSpatialObject.h | 6 +- .../SpatialObject/itkSurfaceSpatialObject.txx | 6 +- .../itkSurfaceSpatialObjectPoint.h | 6 +- .../Code/SpatialObject/itkTubeSpatialObject.h | 6 +- .../SpatialObject/itkTubeSpatialObjectPoint.h | 6 +- .../itkVesselTubeSpatialObject.h | 6 +- .../itkVesselTubeSpatialObjectPoint.h | 6 +- Utilities/ITK/ITKConfig.cmake.in | 2 + Utilities/ITK/Utilities/CMakeLists.txt | 4 + .../Utilities/DICOMParser/DICOMAppHelper.h | 6 +- .../ITK/Utilities/DICOMParser/DICOMBuffer.cxx | 6 +- .../ITK/Utilities/DICOMParser/DICOMParser.cxx | 6 +- .../ITK/Utilities/DICOMParser/DICOMSource.cxx | 6 +- .../ITK/Utilities/KWStyle/ITKFiles.txt.in | 15 +- .../ITK/Utilities/KWStyle/ITKOverwrite.txt | 12 + .../Utilities/KWStyle/ITKReviewFiles.txt.in | 6 + Utilities/ITK/Utilities/KWStyle/KWStyle.cmake | 4 +- Utilities/ITK/Utilities/MetaIO/.svnrev | 2 +- Utilities/ITK/Utilities/MetaIO/metaImage.cxx | 5 +- .../ITK/Utilities/gdcm/CMake/FindUUID.cmake | 14 +- Utilities/ITK/Utilities/gdcm/CMakeLists.txt | 4 + .../ITK/Utilities/gdcm/src/gdcmDocument.cxx | 43 +- Utilities/ITK/Utilities/gdcm/src/gdcmFile.cxx | 20 +- .../ITK/Utilities/gdcm/src/gdcmFileHelper.cxx | 6 +- .../ITK/Utilities/gdcm/src/gdcmGlobal.cxx | 8 +- .../ITK/Utilities/gdcm/src/gdcmJpeg2000.cxx | 55 +- .../gdcm/src/gdcmPixelReadConvert.cxx | 6 +- .../gdcm/src/gdcmPixelWriteConvert.cxx | 34 +- Utilities/ITK/Utilities/gdcm/src/gdcmUtil.cxx | 27 +- .../ITK/Utilities/itkjpeg/mangle_jpeg8bits.h | 1 + Utilities/ITK/Utilities/kwsys/Base64.h.in | 32 +- .../Utilities/kwsys/CommandLineArguments.cxx | 8 +- Utilities/ITK/Utilities/kwsys/Configure.h.in | 3 + .../ITK/Utilities/kwsys/Configure.hxx.in | 3 - .../ITK/Utilities/kwsys/FundamentalType.h.in | 41 +- Utilities/ITK/Utilities/kwsys/Glob.cxx | 6 +- Utilities/ITK/Utilities/kwsys/MD5.h.in | 40 +- Utilities/ITK/Utilities/kwsys/Process.h.in | 208 +- Utilities/ITK/Utilities/kwsys/ProcessUNIX.c | 50 +- .../ITK/Utilities/kwsys/RegularExpression.cxx | 21 +- .../Utilities/kwsys/RegularExpression.hxx.in | 18 +- Utilities/ITK/Utilities/kwsys/String.h.in | 12 +- Utilities/ITK/Utilities/kwsys/System.h.in | 61 +- .../ITK/Utilities/kwsys/SystemInformation.cxx | 286 ++- .../Utilities/kwsys/SystemInformation.hxx.in | 6 +- Utilities/ITK/Utilities/kwsys/SystemTools.cxx | 91 +- .../ITK/Utilities/kwsys/SystemTools.hxx.in | 8 - Utilities/ITK/Utilities/kwsys/Terminal.c | 1 + Utilities/ITK/Utilities/kwsys/Terminal.h.in | 108 +- .../ITK/Utilities/kwsys/kwsysDateStamp.cmake | 4 +- Utilities/ITK/Utilities/kwsys/kwsysPrivate.h | 6 +- Utilities/ITK/Utilities/kwsys/testIOS.cxx | 28 +- .../Utilities/kwsys/testSystemInformation.cxx | 31 +- Utilities/ITK/Utilities/netlib/CMakeLists.txt | 1 + .../Utilities/netlib/slatec/.NoDartCoverage | 0 .../Utilities/netlib/slatec/CMakeLists.txt | 40 + .../ITK/Utilities/netlib/slatec/README.txt | 4 + .../netlib/slatec}/d1mach.c | 0 .../netlib/slatec}/d1mach.f | 0 .../netlib/slatec}/d9gmit.c | 0 .../netlib/slatec}/d9gmit.f | 0 .../netlib/slatec}/d9lgic.c | 0 .../netlib/slatec}/d9lgic.f | 0 .../netlib/slatec}/d9lgit.c | 0 .../netlib/slatec}/d9lgit.f | 0 .../netlib/slatec}/d9lgmc.c | 0 .../netlib/slatec}/d9lgmc.f | 0 .../netlib/slatec}/d_int.c | 0 .../netlib/slatec}/d_mod.c | 0 .../netlib/slatec}/dbetai.c | 0 .../netlib/slatec}/dbetai.f | 0 .../netlib/slatec}/dcsevl.c | 0 .../netlib/slatec}/dcsevl.f | 0 .../netlib/slatec}/dgami.c | 0 .../netlib/slatec}/dgami.f | 0 .../netlib/slatec}/dgamit.c | 0 .../netlib/slatec}/dgamit.f | 0 .../netlib/slatec}/dgamlm.c | 0 .../netlib/slatec}/dgamlm.f | 0 .../netlib/slatec}/dgamma.c | 0 .../netlib/slatec}/dgamma.f | 0 .../netlib/slatec}/dgamr.c | 0 .../netlib/slatec}/dgamr.f | 0 .../netlib/slatec}/dlbeta.c | 0 .../netlib/slatec}/dlbeta.f | 0 .../netlib/slatec}/dlgams.c | 0 .../netlib/slatec}/dlgams.f | 0 .../netlib/slatec}/dlngam.c | 0 .../netlib/slatec}/dlngam.f | 0 .../netlib/slatec}/dlnrel.c | 0 .../netlib/slatec}/dlnrel.f | 0 .../netlib/slatec}/initds.c | 0 .../netlib/slatec}/initds.f | 0 .../netlib/slatec}/xermsg.c | 0 .../vxl/config/cmake/config/CMakeLists.txt | 34 +- .../cmake/config/vxl_platform_tests.cxx | 8 +- .../vxl/core/testlib/testlib_main.cxx | 2 + .../ITK/Utilities/vxl/core/vnl/CMakeLists.txt | 34 +- .../vxl/core/vnl/tests/test_math.cxx | 151 +- .../vxl/core/vnl/tests/test_matlab.cxx | 61 +- .../Utilities/vxl/core/vnl/vnl_config.h.in | 3 + .../ITK/Utilities/vxl/core/vnl/vnl_math.h | 472 ++++- .../vxl/core/vnl/vnl_matlab_header.h | 43 + .../vxl/core/vnl/vnl_matlab_read.cxx | 63 +- .../Utilities/vxl/core/vnl/vnl_matlab_read.h | 2 +- .../ItkVtkGlue/CMakeLists.txt | 5 + .../ExternalProjects/PyBuffer/itkPyBuffer.h | 4 +- .../ExternalProjects/PyBuffer/itkPyBuffer.txx | 10 +- Utilities/ITK/itkConfigure.h.in | 8 +- Utilities/ITK/itkIncludeDirectories.cmake | 22 +- 1305 files changed, 54760 insertions(+), 15586 deletions(-) delete mode 100644 Utilities/ITK/Code/BasicFilters/itkNonThreadedShrinkImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/CMakeLists.txt create mode 100644 Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkCovarianceSampleFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkCovarianceSampleFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkDecisionRule.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkDecisionRule.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkDenseFrequencyContainer2.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkDenseFrequencyContainer2.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkDistanceMetric.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkDistanceMetric.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkDistanceToCentroidMembershipFunction.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkDistanceToCentroidMembershipFunction.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkEuclideanDistanceMetric.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkEuclideanDistanceMetric.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkEuclideanSquareDistanceMetric.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkEuclideanSquareDistanceMetric.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkExpectationMaximizationMixtureModelEstimator.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkExpectationMaximizationMixtureModelEstimator.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkGaussianMixtureModelComponent.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkGaussianMixtureModelComponent.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkHistogram.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkHistogram.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkHistogramToTextureFeaturesFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkHistogramToTextureFeaturesFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkImageToListSampleAdaptor.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkImageToListSampleAdaptor.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkImageToListSampleFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkImageToListSampleFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkJointDomainImageToListSampleAdaptor.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkJointDomainImageToListSampleAdaptor.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkKdTree.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkKdTree.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkKdTreeGenerator.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkKdTreeGenerator.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkListSample.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkListSample.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMembershipFunction.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMembershipFunction.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMetric.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMetric.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMaximumRatioDecisionRule2.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMaximumRatioDecisionRule2.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMeanSampleFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMeanSampleFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMeasurementVectorTraits.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMembershipFunctionBase.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMembershipSample.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMembershipSample.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMixtureModelComponentBase.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkMixtureModelComponentBase.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkNeighborhoodSampler.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkNeighborhoodSampler.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkNormalVariateGenerator.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkNormalVariateGenerator.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkProbabilityDistribution.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkRandomVariateGeneratorBase.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSample.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSampleClassifierFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSampleClassifierFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSampleToHistogramFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSampleToHistogramFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSampleToSubsampleFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSampleToSubsampleFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceListSampleFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceListSampleFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceMatrixFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceMatrixFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSparseFrequencyContainer2.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSparseFrequencyContainer2.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkStandardDeviationPerComponentSampleFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkStandardDeviationPerComponentSampleFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkStatisticsAlgorithm.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkStatisticsAlgorithm.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSubsample.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkSubsample.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkTDistribution.cxx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkTDistribution.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkWeightedCentroidKdTreeGenerator.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkWeightedCentroidKdTreeGenerator.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkWeightedCovarianceSampleFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkWeightedCovarianceSampleFilter.txx create mode 100644 Utilities/ITK/Code/Review/Statistics/itkWeightedMeanSampleFilter.h create mode 100644 Utilities/ITK/Code/Review/Statistics/itkWeightedMeanSampleFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkAtanRegularizedHeavisideStepFunction.h create mode 100644 Utilities/ITK/Code/Review/itkAutumnColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkAutumnColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkBSplineDeformableTransformInitializer.h create mode 100644 Utilities/ITK/Code/Review/itkBSplineDeformableTransformInitializer.txx create mode 100644 Utilities/ITK/Code/Review/itkBlueColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkBlueColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkComplexBSplineInterpolateImageFunction.h create mode 100644 Utilities/ITK/Code/Review/itkComplexBSplineInterpolateImageFunction.txx create mode 100644 Utilities/ITK/Code/Review/itkConstrainedRegionBasedLevelSetFunctionSharedData.h create mode 100644 Utilities/ITK/Code/Review/itkCoolColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkCoolColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkCopperColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkCopperColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkCustomColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkCustomColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkDirectFourierReconstructionImageToImageFilter.h create mode 100644 Utilities/ITK/Code/Review/itkDirectFourierReconstructionImageToImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkGreenColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkGreenColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkGreyColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkGreyColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkGridImageSource.h create mode 100644 Utilities/ITK/Code/Review/itkGridImageSource.txx create mode 100644 Utilities/ITK/Code/Review/itkHSVColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkHSVColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkHeavisideStepFunction.h create mode 100644 Utilities/ITK/Code/Review/itkHeavisideStepFunctionBase.h create mode 100644 Utilities/ITK/Code/Review/itkHotColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkHotColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkJetColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkJetColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.h create mode 100644 Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkLabelMap.h create mode 100644 Utilities/ITK/Code/Review/itkLabelMap.txx create mode 100644 Utilities/ITK/Code/Review/itkLabelMapFilter.h create mode 100644 Utilities/ITK/Code/Review/itkLabelMapFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.h create mode 100644 Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkLabelObject.h create mode 100644 Utilities/ITK/Code/Review/itkLabelObject.txx create mode 100644 Utilities/ITK/Code/Review/itkLabelObjectLine.h create mode 100644 Utilities/ITK/Code/Review/itkLabelObjectLine.txx create mode 100644 Utilities/ITK/Code/Review/itkLabelObjectLineComparator.h create mode 100644 Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.h create mode 100644 Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.h create mode 100644 Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.h create mode 100644 Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkOverUnderColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkOverUnderColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkRedColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkRedColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.h create mode 100644 Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.txx create mode 100644 Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.h create mode 100644 Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.txx create mode 100644 Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionSharedData.h create mode 100644 Utilities/ITK/Code/Review/itkRegularizedHeavisideStepFunction.h create mode 100644 Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.h create mode 100644 Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.h create mode 100644 Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.txx create mode 100644 Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunctionData.h create mode 100644 Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.h create mode 100644 Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.h create mode 100644 Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.txx create mode 100644 Utilities/ITK/Code/Review/itkScalarToRGBColormapImageFilter.h create mode 100644 Utilities/ITK/Code/Review/itkScalarToRGBColormapImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkSinRegularizedHeavisideStepFunction.h create mode 100644 Utilities/ITK/Code/Review/itkSpringColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkSpringColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkStochasticFractalDimensionImageFilter.h create mode 100644 Utilities/ITK/Code/Review/itkStochasticFractalDimensionImageFilter.txx create mode 100644 Utilities/ITK/Code/Review/itkSummerColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkSummerColormapFunctor.txx create mode 100644 Utilities/ITK/Code/Review/itkTriangleHelper.txx create mode 100644 Utilities/ITK/Code/Review/itkUnconstrainedRegionBasedLevelSetFunctionSharedData.h create mode 100644 Utilities/ITK/Code/Review/itkWinterColormapFunctor.h create mode 100644 Utilities/ITK/Code/Review/itkWinterColormapFunctor.txx mode change 100755 => 100644 Utilities/ITK/Utilities/kwsys/SystemInformation.cxx mode change 100755 => 100644 Utilities/ITK/Utilities/kwsys/SystemInformation.hxx.in mode change 100755 => 100644 Utilities/ITK/Utilities/kwsys/testSystemInformation.cxx create mode 100644 Utilities/ITK/Utilities/netlib/CMakeLists.txt create mode 100644 Utilities/ITK/Utilities/netlib/slatec/.NoDartCoverage create mode 100644 Utilities/ITK/Utilities/netlib/slatec/CMakeLists.txt create mode 100644 Utilities/ITK/Utilities/netlib/slatec/README.txt rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d1mach.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d1mach.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d9gmit.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d9gmit.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d9lgic.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d9lgic.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d9lgit.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d9lgit.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d9lgmc.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d9lgmc.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d_int.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/d_mod.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dbetai.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dbetai.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dcsevl.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dcsevl.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgami.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgami.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgamit.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgamit.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgamlm.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgamlm.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgamma.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgamma.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgamr.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dgamr.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dlbeta.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dlbeta.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dlgams.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dlgams.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dlngam.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dlngam.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dlnrel.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/dlnrel.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/initds.c (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/initds.f (100%) rename Utilities/ITK/{Code/Numerics/Statistics => Utilities/netlib/slatec}/xermsg.c (100%) diff --git a/Utilities/ITK/CMake/CTestCustom.ctest.in b/Utilities/ITK/CMake/CTestCustom.ctest.in index de40135e5e..16be983e74 100644 --- a/Utilities/ITK/CMake/CTestCustom.ctest.in +++ b/Utilities/ITK/CMake/CTestCustom.ctest.in @@ -19,6 +19,8 @@ SET(CTEST_CUSTOM_WARNING_EXCEPTION "itkIOCommonTest.cxx:.*warning:.* is deprecated" "/usr/bin/ld: warning: libnetcdf.so.3, needed by.*may conflict with libnetcdf.so.4" "itkQuadEdgeMeshEdgeMergeDecimationFilter.txx:.*warning: unused parameter.*iEdge.*" + "vnl_diag_matrix.h" + "WARNING non-zero return value in ctest" ) IF(APPLE) diff --git a/Utilities/ITK/CMake/InsightValgrind.supp b/Utilities/ITK/CMake/InsightValgrind.supp index ede11e17b8..28a4cc2981 100644 --- a/Utilities/ITK/CMake/InsightValgrind.supp +++ b/Utilities/ITK/CMake/InsightValgrind.supp @@ -1,3 +1,42 @@ +{ + Nrrd fflush 2.3 + Memcheck:Param + write(buf) + fun:__write_nocancel + fun:_IO_file_write@@GLIBC_2.2.5 + fun:_IO_do_write@@GLIBC_2.2.5 + fun:_IO_file_sync@@GLIBC_2.2.5 + fun:fflush + fun:itk__nrrdEncodingRaw_write + fun:itk__nrrdFormatNRRD_write + fun:itk_nrrdWrite + fun:itk_nrrdSave +} +{ + Some 64 bit suppressions + Memcheck:Param + write(buf) + fun:__write_nocancel + obj:/usr/lib64/libstdc++.so.6.?.? +} +{ + Some more 64 bit suppressions + Memcheck:Param + write(buf) + fun:__write_nocancel + fun:_IO_file_write@@GLIBC_2.2.5 + fun:_IO_do_write@@GLIBC_2.2.5 + fun:_IO_file_sync@@GLIBC_2.2.5 + fun:fflush + fun:itk__nrrdEncodingRaw_write +} +{ + Some zlib suppressions + Memcheck:Cond + fun:longest_match + fun:deflate_slow + fun:itk_zlib_deflate +} { Some dl_relocate_object suppressions Memcheck:Cond @@ -11,6 +50,13 @@ fun:pthread_create@@GLIBC_2.1 fun:_ZN3itk13MultiThreader26DispatchSingleMethodThreadEPNS0_16ThreadInfoStructE } +{ + Another Error from the itk::MultiThreader::DispatchSingleMethodThread + Memcheck:Leak + fun:calloc + fun:_dl_allocate_tls + fun:pthread_create@@GLIBC_2.2.5 +} { Some Error from the itk::MultiThreader::SingleMethodExecute Memcheck:Leak @@ -137,6 +183,40 @@ fun:Tcl_FindExecutable fun:Tcl_Main } + +{ + CrazyTclError7 + Memcheck:Leak + fun:realloc + fun:Tcl_AttemptSetObjLength +} + +{ + CrazyTclError8 + Memcheck:Leak + fun:malloc + fun:Tcl_Alloc + fun:TclCreateExecEnv + fun:Tcl_CreateInterp +} + +{ + CrazyTclError9 + Memcheck:Leak + fun:realloc + fun:Tcl_Realloc + fun:Tcl_SetObjLength +} + +{ + CrazyTclError10 + Memcheck:Leak + fun:malloc + fun:Tcl_Alloc + fun:TclAllocateFreeObjects + fun:Tcl_NewObj +} + { <insert a suppression name here> Memcheck:Leak diff --git a/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in b/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in index 0836e0ca90..d73c3a35a3 100644 --- a/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in +++ b/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in @@ -110,6 +110,10 @@ BUILD_EXAMPLES:BOOL=@BUILD_EXAMPLES@ ITK_USE_PATENTED:BOOL=@ITK_USE_PATENTED@ ITK_USE_REVIEW:BOOL=@ITK_USE_REVIEW@ +ITK_USE_REVIEW_STATISTICS:BOOL=@ITK_USE_REVIEW_STATISTICS@ +ITK_USE_PORTABLE_ROUND:BOOL=@ITK_USE_PORTABLE_ROUND@ +ITK_USE_REGION_VALIDATION_IN_ITERATORS:BOOL=@ITK_USE_REGION_VALIDATION_IN_ITERATORS@ +ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY:BOOL=@ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY@ ITK_USE_CONCEPT_CHECKING:BOOL=@ITK_USE_CONCEPT_CHECKING@ ITK_USE_OPTIMIZED_REGISTRATION_METHODS:BOOL=@ITK_USE_OPTIMIZED_REGISTRATION_METHODS@ ITK_USE_ORIENTED_IMAGE_DIRECTION:BOOL=@ITK_USE_ORIENTED_IMAGE_DIRECTION@ diff --git a/Utilities/ITK/CMakeLists.txt b/Utilities/ITK/CMakeLists.txt index 2911b25324..5afa9c2e6e 100644 --- a/Utilities/ITK/CMakeLists.txt +++ b/Utilities/ITK/CMakeLists.txt @@ -47,7 +47,7 @@ ENDIF("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" MATCHES "^2\\.4$") #----------------------------------------------------------------------------- # ITK version number. An even minor number corresponds to releases. SET(ITK_VERSION_MAJOR "3") -SET(ITK_VERSION_MINOR "12") +SET(ITK_VERSION_MINOR "14") SET(ITK_VERSION_PATCH "0") # Version string should not include patch level. The major.minor is @@ -67,6 +67,7 @@ INCLUDE (${CMAKE_ROOT}/Modules/CMakeBackwardCompatibilityCXX.cmake) # Configure Dart testing support. This should be done before any # MESSAGE(FATAL_ERROR ...) commands are invoked. INCLUDE(${CMAKE_ROOT}/Modules/Dart.cmake) +FIND_PACKAGE(Tclsh) MARK_AS_ADVANCED(TCL_TCLSH DART_ROOT) ENABLE_TESTING() IF(BUILD_TESTING) @@ -208,6 +209,23 @@ MESSAGE("${msg}") ENDIF(ITK_USE_OPTIMIZED_REGISTRATION_METHODS) +#----------------------------------------------------------------------------- +# ITK use the new statistics framework +OPTION( ITK_USE_REVIEW_STATISTICS "Use the experimental statistics framework." OFF) +MARK_AS_ADVANCED( ITK_USE_REVIEW_STATISTICS ) +IF(ITK_USE_REVIEW_STATISTICS) + IF(NOT ITK_USE_REVIEW) + MESSAGE(FATAL_ERROR "ITK_USE_REVIEW is currently OFF but it should be ON if you want to use the experimental statistics framework.") + ENDIF(NOT ITK_USE_REVIEW) + + # Warn the user about the implications of using the new statistics framework. + SET(msg "Attention: You have chosen to use the new statistics framework instead of the existing framework.") + SET(msg "${msg} The statistics classes have been re-designed/refactored and in several") + SET(msg "${msg} cases do not conform to the API of the older framework. You may need to") + SET(msg "${msg} change your code to use the new API.") + MESSAGE("${msg}") +ENDIF(ITK_USE_REVIEW_STATISTICS) + #----------------------------------------------------------------------------- # ITK turn on experimental version of accelerated image registration OPTION(ITK_USE_CONSOLIDATED_MORPHOLOGY "Turn on the experimental consolidated morphology." OFF) @@ -240,6 +258,31 @@ ENDIF(ITK_USE_TRANSFORM_IO_FACTORIES) OPTION(ITK_USE_ORIENTED_IMAGE_DIRECTION "Turn on correct use of oriented images direction in gradient computation and image registration." ON) MARK_AS_ADVANCED(ITK_USE_ORIENTED_IMAGE_DIRECTION) + +#----------------------------------------------------------------------------- +# ITK turn on the correct usage of centered-pixel coordinates. +OPTION(ITK_USE_PORTABLE_ROUND "Turn on round implementation that works in multiple-platforms." OFF) +MARK_AS_ADVANCED(ITK_USE_PORTABLE_ROUND) + + +#----------------------------------------------------------------------------- +# ITK turn on the correct usage of centered-pixel coordinates. +OPTION(ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY "Turn on correct usage of centered-pixel coordinates." OFF) +MARK_AS_ADVANCED(ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY) +IF(ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY) + MESSAGE("Attention: You enabled ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY This feature has not been fully tested and validated.") + IF(NOT ITK_USE_PORTABLE_ROUND) + MESSAGE(FATAL_ERROR "ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY is currently ON but ITK_USE_PORTABLE_ROUND is OFF, you should enable the portable round") + ENDIF(NOT ITK_USE_PORTABLE_ROUND) +ENDIF(ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY) + + +#----------------------------------------------------------------------------- +# ITK turn on the correct usage of centered-pixel coordinates. +OPTION(ITK_USE_REGION_VALIDATION_IN_ITERATORS "Turn on region validation in Iterator constructors." ON) +MARK_AS_ADVANCED(ITK_USE_REGION_VALIDATION_IN_ITERATORS) + + #----------------------------------------------------------------------------- # ITK turn on the use of Template Meta Programming techniques for unrolling loops of array-like operations OPTION(ITK_USE_TEMPLATE_META_PROGRAMMING_LOOP_UNROLLING "Turn on the use of Template Meta-Programming techniques for unrolling for-loops at compile time." ON) @@ -457,6 +500,11 @@ IF(CMAKE_COMPILER_IS_GNUCXX) MARK_AS_ADVANCED(ITK_USE_64BITS_APPLE_TRUNCATION_WARNING) ENDIF(APPLE) + + # gcc must have -msse2 option to enable sse2 support + IF(VNL_CONFIG_ENABLE_SSE2 OR VNL_CONFIG_ENABLE_SSE2_ROUNDING) + SET(ITK_REQUIRED_CXX_FLAGS "${ITK_REQUIRED_CXX_FLAGS} -msse2") + ENDIF(VNL_CONFIG_ENABLE_SSE2 OR VNL_CONFIG_ENABLE_SSE2_ROUNDING) ENDIF(CMAKE_COMPILER_IS_GNUCXX) IF(UNIX) @@ -495,6 +543,17 @@ IF(MINGW) LINK_LIBRARIES(gdi32) ENDIF(MINGW) +# Add flags for the SUN compiler to provide all the methods for std::allocator. +# +INCLUDE(${ITK_SOURCE_DIR}/CMake/itkCheckCXXAcceptsFlags.cmake) +itkCHECK_CXX_ACCEPTS_FLAGS("-features=no%anachronisms" SUN_COMPILER) +IF(SUN_COMPILER) + itkCHECK_CXX_ACCEPTS_FLAGS("-library=stlport4" SUN_COMPILER_HAS_STL_PORT_4) + IF(SUN_COMPILER_HAS_STL_PORT_4) + SET(ITK_REQUIRED_CXX_FLAGS "${ITK_REQUIRED_CXX_FLAGS} -library=stlport4") + ENDIF(SUN_COMPILER_HAS_STL_PORT_4) +ENDIF(SUN_COMPILER) + # for the gnu compiler a -D_PTHREADS is needed on sun # for the native compiler a -mt flag is needed on the sun IF(CMAKE_USE_PTHREADS) @@ -726,7 +785,23 @@ IF(ITK_USE_SYSTEM_GDCM) IF( "${GDCM_MAJOR_VERSION}" LESS 2.0 ) SET(ITK_GDCM_LIBRARIES gdcm) ELSE( "${GDCM_MAJOR_VERSION}" LESS 2.0 ) - SET(ITK_GDCM_LIBRARIES gdcmMSFF) + IF(ITK_USE_SYSTEM_TIFF) + # Long story short. ITKIO is NOT linked to itkjpeg8 explicitely. itkjpeg8 dep is being + # pulled from linking to itktiff. However in case of ITK_SYSTEM_TIFF the FindTIFF module + # do not explicitely link to the system jpeg. One can check however that on most GNU/Linux system + # $ ldd /usr/lib/libtiff.so + # linux-vdso.so.1 => (0x00007fff67fff000) + # libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0x00007f635f9f2000) + # As a side note, ITK_SYSTEM_TIFF is somewhat robust as itkjpeg8 dep can also be pulled from + # linking to the default gdcm libraries since they use the itkjpeg libraries. + # I do not know the correct fix: + # 1. Have FindTIFF link to jpeg8 (which would be the right thing to do for static system libtiff) + # 2. Have ITKIO explicitely link to itkjpeg8 + # For the time being let's explicitely pull the dep to itkjpeg8 ourselves. + SET(ITK_GDCM_LIBRARIES gdcmMSFF itkjpeg8) + ELSE(ITK_USE_SYSTEM_TIFF) + SET(ITK_GDCM_LIBRARIES gdcmMSFF) + ENDIF(ITK_USE_SYSTEM_TIFF) ENDIF( "${GDCM_MAJOR_VERSION}" LESS 2.0 ) ELSE(GDCM_FOUND) MESSAGE(FATAL_ERROR "Must set GDCM_DIR for ITK_USE_SYSTEM_GDCM.") diff --git a/Utilities/ITK/Code/Algorithms/itkAnisotropicFourthOrderLevelSetImageFilter.h b/Utilities/ITK/Code/Algorithms/itkAnisotropicFourthOrderLevelSetImageFilter.h index a2d0760e33..a0c8318b26 100644 --- a/Utilities/ITK/Code/Algorithms/itkAnisotropicFourthOrderLevelSetImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkAnisotropicFourthOrderLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnisotropicFourthOrderLevelSetImageFilter.h,v $ Language: C++ - Date: $Date: 2007-04-20 13:36:35 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-23 03:53:34 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -107,7 +107,7 @@ public: /** The radius type for the neighborhoods. */ typedef typename FunctionType::RadiusType RadiusType; - itkGetMacro(MaxFilterIteration,unsigned int); + itkGetConstMacro(MaxFilterIteration,unsigned int); itkSetMacro(MaxFilterIteration,unsigned int); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkAntiAliasBinaryImageFilter.h b/Utilities/ITK/Code/Algorithms/itkAntiAliasBinaryImageFilter.h index 2870c42971..1d0ef6e6ed 100644 --- a/Utilities/ITK/Code/Algorithms/itkAntiAliasBinaryImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkAntiAliasBinaryImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAntiAliasBinaryImageFilter.h,v $ Language: C++ - Date: $Date: 2007-04-20 13:36:35 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-23 03:53:34 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -128,8 +128,8 @@ public: itkTypeMacro(AntiAliasBinaryImageFilter, SparseFieldLevelSetImageFilter); /** Get the upper and lower binary values in the input image. */ - itkGetMacro(UpperBinaryValue, BinaryValueType); - itkGetMacro(LowerBinaryValue, BinaryValueType); + itkGetConstMacro(UpperBinaryValue, BinaryValueType); + itkGetConstMacro(LowerBinaryValue, BinaryValueType); /** Set/Get the maximum number of iterations allowed for the solver. This * prevents infinite loops if a solution "bounces". */ diff --git a/Utilities/ITK/Code/Algorithms/itkBalloonForceFilter.h b/Utilities/ITK/Code/Algorithms/itkBalloonForceFilter.h index 224d191579..a3fe6311ff 100644 --- a/Utilities/ITK/Code/Algorithms/itkBalloonForceFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkBalloonForceFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBalloonForceFilter.h,v $ Language: C++ - Date: $Date: 2008-05-26 11:34:53 $ - Version: $Revision: 1.39 $ + Date: $Date: 2009-04-23 03:53:34 $ + Version: $Revision: 1.40 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -137,7 +137,7 @@ public: /** Set the output image. */ itkSetMacro(ImageOutput, ImagePointer); - itkGetMacro(ImageOutput, ImagePointer); + itkGetConstMacro(ImageOutput, ImagePointer); itkSetMacro(Gradient, GradientImagePointer); /** Set/Get information for the algorithm. */ @@ -146,14 +146,14 @@ public: itkSetMacro(GradientBegin, int); itkSetMacro(Resolution, int); itkSetMacro(Center, IndexType); - itkGetMacro(Normals, InputMeshPointer); + itkGetConstMacro(Normals, InputMeshPointer); itkSetMacro(DistanceForGradient, float); itkSetMacro(DistanceToStop, float); itkSetMacro(Potential, ImagePointer); - itkGetMacro(Locations, InputMeshPointer); - itkGetMacro(Displacements, InputMeshPointer); - itkGetMacro(Derives, InputMeshPointer); - itkGetMacro(Forces, InputMeshPointer); + itkGetConstMacro(Locations, InputMeshPointer); + itkGetConstMacro(Displacements, InputMeshPointer); + itkGetConstMacro(Derives, InputMeshPointer); + itkGetConstMacro(Forces, InputMeshPointer); protected: BalloonForceFilter(); diff --git a/Utilities/ITK/Code/Algorithms/itkBalloonForceFilter.txx b/Utilities/ITK/Code/Algorithms/itkBalloonForceFilter.txx index 2b1e16a432..eba1607c8d 100644 --- a/Utilities/ITK/Code/Algorithms/itkBalloonForceFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkBalloonForceFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBalloonForceFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-20 21:28:19 $ - Version: $Revision: 1.71 $ + Date: $Date: 2009-04-06 13:46:30 $ + Version: $Revision: 1.73 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -1139,8 +1139,8 @@ BalloonForceFilter<TInputMesh, TOutputMesh> coord[0] = static_cast<IndexValueType>(vec_loc[0]); coord[1] = static_cast<IndexValueType>(vec_loc[1]); - coord2[0] = static_cast<IndexValueType>( (ceil) (vec_loc[0]) ); - coord2[1] = static_cast<IndexValueType>( (ceil) (vec_loc[1]) ); + coord2[0] = static_cast<IndexValueType>( vcl_ceil( vec_loc[0] ) ); + coord2[1] = static_cast<IndexValueType>( vcl_ceil( vec_loc[1] ) ); tmp_co_1[0] = coord2[0]; tmp_co_1[1] = coord[1]; @@ -1235,7 +1235,7 @@ BalloonForceFilter<TInputMesh, TOutputMesh> v2[0]*(v3[1]-v1[1]) + v3[0]*(v1[1]-v2[1])); - absvec = -sqrt ((double) ((coa*coa) + (cob*cob) + (coc*coc))); + absvec = -vcl_sqrt ((double) ((coa*coa) + (cob*cob) + (coc*coc))); assert (absvec != 0); diff --git a/Utilities/ITK/Code/Algorithms/itkBayesianClassifierImageFilter.h b/Utilities/ITK/Code/Algorithms/itkBayesianClassifierImageFilter.h index d2d14743fc..a35a1e7ee5 100755 --- a/Utilities/ITK/Code/Algorithms/itkBayesianClassifierImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkBayesianClassifierImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBayesianClassifierImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-25 18:28:14 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-04-23 03:53:34 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -168,11 +168,11 @@ public: /** Set/ Get macros for the smoothing filter that may optionally be applied * to the posterior image */ void SetSmoothingFilter( SmoothingFilterType * ); - itkGetMacro( SmoothingFilter, SmoothingFilterPointer ); + itkGetConstMacro( SmoothingFilter, SmoothingFilterPointer ); /** Number of iterations to apply the smoothing filter */ itkSetMacro( NumberOfSmoothingIterations, unsigned int ); - itkGetMacro( NumberOfSmoothingIterations, unsigned int ); + itkGetConstMacro( NumberOfSmoothingIterations, unsigned int ); /** This is overloaded to create the Posteriors output image */ virtual DataObjectPointer MakeOutput(unsigned int idx); @@ -206,8 +206,6 @@ protected: /** Here is where the classification is computed. */ virtual void GenerateData(); - /** Allocate Memory for the Output. */ - virtual void AllocateOutputs(); virtual void GenerateOutputInformation(void); /** Methods for computing the labeled map for all combinations of conditions */ diff --git a/Utilities/ITK/Code/Algorithms/itkBayesianClassifierImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkBayesianClassifierImageFilter.txx index 9af48d03ef..b94b725c65 100755 --- a/Utilities/ITK/Code/Algorithms/itkBayesianClassifierImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkBayesianClassifierImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBayesianClassifierImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-25 18:28:13 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-13 14:26:51 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -145,26 +145,11 @@ BayesianClassifierImageFilter<TInputVectorImage, TLabelsType, return; } + // the vector length is part of the output information that must be + // updated here this->GetPosteriorImage()->SetVectorLength( this->GetInput()->GetVectorLength() ); } -template < class TInputVectorImage, class TLabelsType, - class TPosteriorsPrecisionType, class TPriorsPrecisionType > -void -BayesianClassifierImageFilter<TInputVectorImage, TLabelsType, - TPosteriorsPrecisionType, TPriorsPrecisionType > -::AllocateOutputs() -{ - // we overload this methods because outputs are of different types - // the the templated parameter to ImageSource<OutputImageType> - - this->GetOutput()->SetBufferedRegion( this->GetOutput()->GetRequestedRegion() ); - this->GetOutput()->Allocate(); - - this->GetPosteriorImage()->SetBufferedRegion( this->GetPosteriorImage()->GetRequestedRegion() ); - this->GetPosteriorImage()->Allocate(); -} - /** * Compute the posteriors using the Bayes rule. If no priors are available, * then the posteriors are just a copy of the memberships. */ diff --git a/Utilities/ITK/Code/Algorithms/itkBayesianClassifierInitializationImageFilter.h b/Utilities/ITK/Code/Algorithms/itkBayesianClassifierInitializationImageFilter.h index 85325739d8..ad4986a4c3 100644 --- a/Utilities/ITK/Code/Algorithms/itkBayesianClassifierInitializationImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkBayesianClassifierInitializationImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBayesianClassifierInitializationImageFilter.h,v $ Language: C++ - Date: $Date: 2007-04-20 13:36:35 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-05-02 05:43:54 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,11 @@ #include "itkImageToImageFilter.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" +#ifdef ITK_USE_REVIEW_STATISTICS +#include "itkMembershipFunctionBase.h" +#else #include "itkDensityFunction.h" +#endif namespace itk { @@ -118,8 +122,13 @@ public: typedef Vector< InputPixelType, 1 > MeasurementVectorType; /** Type of the density functions */ +#ifdef ITK_USE_REVIEW_STATISTICS + typedef Statistics::MembershipFunctionBase< MeasurementVectorType > MembershipFunctionType; +#else typedef Statistics::DensityFunction< MeasurementVectorType > MembershipFunctionType; +#endif + typedef typename MembershipFunctionType::Pointer MembershipFunctionPointer; /** Membership function container */ @@ -139,7 +148,7 @@ public: /** Set/Get methods for the number of classes. The user must supply this. */ itkSetMacro( NumberOfClasses, unsigned int ); - itkGetMacro( NumberOfClasses, unsigned int ); + itkGetConstMacro( NumberOfClasses, unsigned int ); virtual void GenerateOutputInformation(); diff --git a/Utilities/ITK/Code/Algorithms/itkBayesianClassifierInitializationImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkBayesianClassifierInitializationImageFilter.txx index 68ebc4aa57..6d56d8be88 100644 --- a/Utilities/ITK/Code/Algorithms/itkBayesianClassifierInitializationImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkBayesianClassifierInitializationImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBayesianClassifierInitializationImageFilter.txx,v $ Language: C++ - Date: $Date: 2007-04-20 13:36:35 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-05-02 05:43:54 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,12 @@ #include "itkBayesianClassifierInitializationImageFilter.h" #include "itkScalarImageKmeansImageFilter.h" + +#ifdef ITK_USE_REVIEW_STATISTICS +#include "itkGaussianMembershipFunction.h" +#else #include "itkGaussianDensityFunction.h" +#endif namespace itk { @@ -84,7 +89,12 @@ BayesianClassifierInitializationImageFilter<TInputImage, KMeansOutputImageType > ConstKMeansIteratorType; typedef Array< double > CovarianceArrayType; typedef Array< double > ClassCountArrayType; + +#ifdef ITK_USE_REVIEW_STATISTICS + typedef Statistics::GaussianMembershipFunction< +#else typedef Statistics::GaussianDensityFunction< +#endif MeasurementVectorType > GaussianMembershipFunctionType; typedef VectorContainer< unsigned short, ITK_TYPENAME GaussianMembershipFunctionType::MeanType* > MeanEstimatorsContainerType; @@ -197,8 +207,14 @@ BayesianClassifierInitializationImageFilter<TInputImage, covarianceEstimators->Fill( estimatedCovariances[i] ); typename GaussianMembershipFunctionType::Pointer gaussianDensityFunction = GaussianMembershipFunctionType::New(); +#ifdef ITK_USE_REVIEW_STATISTICS + gaussianDensityFunction->SetMean( *(meanEstimatorsContainer->GetElement( i )) ); + gaussianDensityFunction->SetCovariance( *(covarianceEstimatorsContainer->GetElement( i )) ); +#else gaussianDensityFunction->SetMean( meanEstimatorsContainer->GetElement( i ) ); gaussianDensityFunction->SetCovariance( covarianceEstimatorsContainer->GetElement( i ) ); +#endif + m_MembershipFunctionContainer->InsertElement(i, dynamic_cast< MembershipFunctionType * >( gaussianDensityFunction.GetPointer() ) ); diff --git a/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.h b/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.h index 76d437174d..92de9336bb 100644 --- a/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.h +++ b/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMask3DMeshSource.h,v $ Language: C++ - Date: $Date: 2007-04-20 13:36:35 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-23 03:53:34 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -127,8 +127,8 @@ public: itkSetMacro(ObjectValue, InputPixelType); - itkGetMacro(NumberOfNodes, unsigned long); - itkGetMacro(NumberOfCells, unsigned long); + itkGetConstMacro(NumberOfNodes, unsigned long); + itkGetConstMacro(NumberOfCells, unsigned long); /** accept the input image */ virtual void SetInput( const InputImageType * inputImage ); diff --git a/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.txx b/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.txx index d929c6988b..f4cf71c5e7 100644 --- a/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.txx +++ b/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMask3DMeshSource.txx,v $ Language: C++ -Date: $Date: 2007-12-29 21:01:34 $ -Version: $Revision: 1.28 $ +Date: $Date: 2009-04-12 03:55:23 $ +Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -1025,11 +1025,14 @@ void BinaryMask3DMeshSource<TInputImage,TOutputMesh> ::CreateMesh() { - if (this->GetNumberOfInputs() < 1) - { - std::cout << "BinaryMask3DMeshSource : Binary image mask not set" << std::endl; - return; - } + // NOTE ALEX: this is checked by the new pipeline + // through SetNumberOfRequiredInput + // if (this->GetNumberOfInputs() < 1) + // { + // std::cout << "BinaryMask3DMeshSource : Binary image mask not set"; + // std::cout << std::endl; + // return; + // } // Initialize variables m_NumberOfCells = 0; diff --git a/Utilities/ITK/Code/Algorithms/itkBinaryMedialNodeMetric.h b/Utilities/ITK/Code/Algorithms/itkBinaryMedialNodeMetric.h index e557521bf6..0f76e20fa7 100644 --- a/Utilities/ITK/Code/Algorithms/itkBinaryMedialNodeMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkBinaryMedialNodeMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMedialNodeMetric.h,v $ Language: C++ - Date: $Date: 2007-04-20 13:36:35 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,7 +32,7 @@ namespace itk */ template <int VDimensions> -class BinaryMedialNodeMetric : public LightObject +class ITK_EXPORT BinaryMedialNodeMetric : public LightObject { public: @@ -77,7 +77,7 @@ public: /** Function to return the result of the metric calculations */ double GetResult(){return m_Result;} //itkSetMacro(Result, double); - //itkGetMacro(Result, double); + //itkGetConstMacro(Result, double); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkBinaryMedialNodeMetric.txx b/Utilities/ITK/Code/Algorithms/itkBinaryMedialNodeMetric.txx index cfc44d4413..5c4b2554fd 100644 --- a/Utilities/ITK/Code/Algorithms/itkBinaryMedialNodeMetric.txx +++ b/Utilities/ITK/Code/Algorithms/itkBinaryMedialNodeMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMedialNodeMetric.txx,v $ Language: C++ - Date: $Date: 2007-04-20 13:36:35 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-12 20:21:45 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -199,6 +199,7 @@ BinaryMedialNodeMetric<VDimensions> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); + os << indent << "Result: " << m_Result << std::endl; } diff --git a/Utilities/ITK/Code/Algorithms/itkBinaryMinMaxCurvatureFlowImageFilter.h b/Utilities/ITK/Code/Algorithms/itkBinaryMinMaxCurvatureFlowImageFilter.h index 5184bb5b83..7470a95f42 100644 --- a/Utilities/ITK/Code/Algorithms/itkBinaryMinMaxCurvatureFlowImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkBinaryMinMaxCurvatureFlowImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMinMaxCurvatureFlowImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-20 21:28:20 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-23 03:53:34 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -104,7 +104,7 @@ public: /** Set/Get the threshold value. */ itkSetMacro( Threshold, double ); - itkGetMacro( Threshold, double ); + itkGetConstMacro( Threshold, double ); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Algorithms/itkBinaryPruningImageFilter.h b/Utilities/ITK/Code/Algorithms/itkBinaryPruningImageFilter.h index 7af5b4d666..c6286fbc7d 100644 --- a/Utilities/ITK/Code/Algorithms/itkBinaryPruningImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkBinaryPruningImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryPruningImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-20 21:28:20 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-23 03:53:34 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -97,7 +97,7 @@ public: /** Set/Get the iteration value */ itkSetMacro(Iteration, unsigned int); - itkGetMacro(Iteration, unsigned int); + itkGetConstMacro(Iteration, unsigned int); /** ImageDimension enumeration */ itkStaticConstMacro(InputImageDimension, unsigned int, diff --git a/Utilities/ITK/Code/Algorithms/itkBioCell.h b/Utilities/ITK/Code/Algorithms/itkBioCell.h index feb1bc38d6..a21f5a23bf 100644 --- a/Utilities/ITK/Code/Algorithms/itkBioCell.h +++ b/Utilities/ITK/Code/Algorithms/itkBioCell.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBioCell.h,v $ Language: C++ - Date: $Date: 2008-10-20 21:28:20 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,7 +34,7 @@ namespace bio { */ template<unsigned int NSpaceDimension=3> -class Cell : public CellBase +class ITK_EXPORT Cell : public CellBase { public: typedef CellBase Superclass; diff --git a/Utilities/ITK/Code/Algorithms/itkBioCellBase.h b/Utilities/ITK/Code/Algorithms/itkBioCellBase.h index 7e52216292..60757178a9 100644 --- a/Utilities/ITK/Code/Algorithms/itkBioCellBase.h +++ b/Utilities/ITK/Code/Algorithms/itkBioCellBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBioCellBase.h,v $ Language: C++ - Date: $Date: 2008-10-20 21:28:20 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,7 @@ namespace bio { * \brief non-templated Base class from which the templated Cell classes will be derived. * Derived classes are instantiated for a specific space dimension. */ -class CellBase +class ITK_EXPORT CellBase { public: typedef itk::RGBPixel<float> ColorType; diff --git a/Utilities/ITK/Code/Algorithms/itkBioCellularAggregate.h b/Utilities/ITK/Code/Algorithms/itkBioCellularAggregate.h index 1f2971f075..e6bd06edb5 100644 --- a/Utilities/ITK/Code/Algorithms/itkBioCellularAggregate.h +++ b/Utilities/ITK/Code/Algorithms/itkBioCellularAggregate.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBioCellularAggregate.h,v $ Language: C++ - Date: $Date: 2008-10-20 21:28:20 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,7 +38,7 @@ namespace bio { * including bacterial colonies and pluricellular organisms */ template<unsigned int NSpaceDimension=3> -class CellularAggregate : public CellularAggregateBase +class ITK_EXPORT CellularAggregate : public CellularAggregateBase { public: /** Standard class typedefs. */ diff --git a/Utilities/ITK/Code/Algorithms/itkBioCellularAggregateBase.h b/Utilities/ITK/Code/Algorithms/itkBioCellularAggregateBase.h index 7c63d769c9..da2baaac07 100644 --- a/Utilities/ITK/Code/Algorithms/itkBioCellularAggregateBase.h +++ b/Utilities/ITK/Code/Algorithms/itkBioCellularAggregateBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBioCellularAggregateBase.h,v $ Language: C++ - Date: $Date: 2008-10-20 21:28:20 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -31,7 +31,7 @@ class CellBase; * \brief Base class for the CellularAggregates. This base class is not * templated over the space dimension. */ -class CellularAggregateBase : public Object +class ITK_EXPORT CellularAggregateBase : public Object { public: /** Standard class typedefs. */ diff --git a/Utilities/ITK/Code/Algorithms/itkBioGene.cxx b/Utilities/ITK/Code/Algorithms/itkBioGene.cxx index 09f3c49e87..f806f5227a 100755 --- a/Utilities/ITK/Code/Algorithms/itkBioGene.cxx +++ b/Utilities/ITK/Code/Algorithms/itkBioGene.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBioGene.cxx,v $ Language: C++ - Date: $Date: 2008-10-20 21:28:20 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-05-02 14:24:28 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -115,8 +115,8 @@ Gene ::AddGeneControlDomain( const DomainType & domain, bool type ) { ControlDomainType controlDomain; - controlDomain.domain = domain; - controlDomain.type = type; + controlDomain.m_Domain = domain; + controlDomain.m_Type = type; m_ControlDomains.push_back( controlDomain ); } diff --git a/Utilities/ITK/Code/Algorithms/itkBioGene.h b/Utilities/ITK/Code/Algorithms/itkBioGene.h index 4be7be0688..93cfd2a250 100755 --- a/Utilities/ITK/Code/Algorithms/itkBioGene.h +++ b/Utilities/ITK/Code/Algorithms/itkBioGene.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBioGene.h,v $ Language: C++ - Date: $Date: 2008-10-20 21:28:21 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-02 14:24:28 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,7 +46,12 @@ public: typedef double AffinityType; typedef std::map< DomainType, AffinityType > ProteinDomainsType; - typedef struct { DomainType domain; bool type; } ControlDomainType; + typedef struct + { + DomainType m_Domain; + bool m_Type; + } ControlDomainType; + typedef std::vector< ControlDomainType > GeneControlDomainsType; public: diff --git a/Utilities/ITK/Code/Algorithms/itkCollidingFrontsImageFilter.h b/Utilities/ITK/Code/Algorithms/itkCollidingFrontsImageFilter.h index f4a1c41595..1902563afc 100644 --- a/Utilities/ITK/Code/Algorithms/itkCollidingFrontsImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkCollidingFrontsImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCollidingFrontsImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-23 16:15:23 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,6 +44,11 @@ namespace itk * positive, the two fronts propagate in the same direction. This can be used * to extract the region of space between two sets of points. * + * If StopOnTargets is On, then each front will stop as soon as all seeds of + * the other front have been reached. This can markedly speed up the execution + * of the filter, since wave propagation does not take place on the complete + * image. + * * Optionally, a connectivity criterion can be applied to the resulting dot * product image. In this case, the only negative region in the output image is * the one connected to the seeds. @@ -53,7 +58,7 @@ namespace itk * */ template <typename TInputImage, typename TOutputImage> -class CollidingFrontsImageFilter : +class ITK_EXPORT CollidingFrontsImageFilter : public ImageToImageFilter< TInputImage, TOutputImage > { public: @@ -130,12 +135,16 @@ public: { return m_SeedPoints2; } itkSetMacro(NegativeEpsilon, double); - itkGetMacro(NegativeEpsilon, double); + itkGetConstMacro(NegativeEpsilon, double); itkSetMacro(ApplyConnectivity, bool); - itkGetMacro(ApplyConnectivity, bool); + itkGetConstMacro(ApplyConnectivity, bool); itkBooleanMacro(ApplyConnectivity); + itkSetMacro(StopOnTargets, bool); + itkGetConstMacro(StopOnTargets, bool); + itkBooleanMacro(StopOnTargets); + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(InputHasNumericTraitsCheck, @@ -158,6 +167,7 @@ private: NodeContainerPointer m_SeedPoints1; NodeContainerPointer m_SeedPoints2; + bool m_StopOnTargets; bool m_ApplyConnectivity; double m_NegativeEpsilon; diff --git a/Utilities/ITK/Code/Algorithms/itkCollidingFrontsImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkCollidingFrontsImageFilter.txx index 76fc8483a2..aa11755b35 100644 --- a/Utilities/ITK/Code/Algorithms/itkCollidingFrontsImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkCollidingFrontsImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCollidingFrontsImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-11-07 19:39:43 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-20 13:02:56 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,6 +32,7 @@ CollidingFrontsImageFilter<TInputImage,TOutputImage> { m_SeedPoints1 = NULL; m_SeedPoints2 = NULL; + m_StopOnTargets = false; m_ApplyConnectivity = true; m_NegativeEpsilon = -1E-6; } @@ -50,6 +51,14 @@ CollidingFrontsImageFilter< TInputImage, TOutputImage > fastMarchingFilter1->SetOutputSpacing(this->GetInput()->GetSpacing()); fastMarchingFilter1->SetOutputDirection(this->GetInput()->GetDirection()); fastMarchingFilter1->GenerateGradientImageOn(); + if (m_StopOnTargets) + { + fastMarchingFilter1->SetTargetReachedModeToAllTargets(); + } + else + { + fastMarchingFilter1->SetTargetReachedModeToNoTargets(); + } fastMarchingFilter1->Update(); typename FastMarchingUpwindGradientImageFilterType::Pointer fastMarchingFilter2 = FastMarchingUpwindGradientImageFilterType::New(); @@ -61,6 +70,14 @@ CollidingFrontsImageFilter< TInputImage, TOutputImage > fastMarchingFilter2->SetOutputSpacing(this->GetInput()->GetSpacing()); fastMarchingFilter2->SetOutputDirection(this->GetInput()->GetDirection()); fastMarchingFilter2->GenerateGradientImageOn(); + if (m_StopOnTargets) + { + fastMarchingFilter2->SetTargetReachedModeToAllTargets(); + } + else + { + fastMarchingFilter2->SetTargetReachedModeToNoTargets(); + } fastMarchingFilter2->Update(); typedef itk::MultiplyImageFilter<GradientImageType,GradientImageType,OutputImageType> MultiplyFilterType; @@ -139,6 +156,8 @@ CollidingFrontsImageFilter<TInputImage, TOutputImage> os << indent << "ApplyConnectivity = " << m_ApplyConnectivity << std::endl; os << indent << "SeedPoints1: " << m_SeedPoints1.GetPointer() << std::endl; os << indent << "SeedPoints2: " << m_SeedPoints2.GetPointer() << std::endl; + os << indent << "NegativeEpsilon: " << m_NegativeEpsilon << std::endl; + os << indent << "StopOnTargets: " << m_StopOnTargets << std::endl; } } // end namespace itk diff --git a/Utilities/ITK/Code/Algorithms/itkCompareHistogramImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkCompareHistogramImageToImageMetric.h index 6eed40ad42..6c82a50f52 100644 --- a/Utilities/ITK/Code/Algorithms/itkCompareHistogramImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkCompareHistogramImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCompareHistogramImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2008-10-23 16:15:23 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-02 05:43:54 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -87,7 +87,13 @@ public: typedef typename Superclass::HistogramSizeType HistogramSizeType; typedef typename HistogramType::MeasurementVectorType HistogramMeasurementVectorType; - typedef typename HistogramType::FrequencyType HistogramFrequencyType; +#ifdef ITK_USE_REVIEW_STATISTICS + typedef typename HistogramType::AbsoluteFrequencyType HistogramAbsoluteFrequencyType; +#else + typedef typename HistogramType::FrequencyType HistogramAbsoluteFrequencyType; +#endif + typedef HistogramAbsoluteFrequencyType HistogramFrequencyType; + typedef typename HistogramType::Iterator HistogramIteratorType; typedef typename HistogramType::Pointer HistogramPointerType; diff --git a/Utilities/ITK/Code/Algorithms/itkCompareHistogramImageToImageMetric.txx b/Utilities/ITK/Code/Algorithms/itkCompareHistogramImageToImageMetric.txx index a03cf8fa66..05b3c6753f 100644 --- a/Utilities/ITK/Code/Algorithms/itkCompareHistogramImageToImageMetric.txx +++ b/Utilities/ITK/Code/Algorithms/itkCompareHistogramImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCompareHistogramImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2004-02-20 13:35:13 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-05-05 17:47:30 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -96,12 +96,17 @@ CompareHistogramImageToImageMetric<TFixedImage, TMovingImage> } this->m_TrainingInterpolator->SetInputImage(GetTrainingMovingImage()); -// -// Create the exact histogram structure as the one to be used -// to evaluate the metric. This code is mostly copied -// from itkHistogramImageToImageMetric -// + + // Create the exact histogram structure as the one to be used + // to evaluate the metric. This code is mostly copied + // from itkHistogramImageToImageMetric + this->m_TrainingHistogram = HistogramType::New(); + +#ifdef ITK_USE_REVIEW_STATISTICS + this->m_TrainingHistogram->SetMeasurementVectorSize(2); +#endif + this->m_TrainingHistogram->Initialize(this->Superclass::m_HistogramSize, this->Superclass::m_LowerBound, this->Superclass::m_UpperBound); @@ -139,6 +144,9 @@ CompareHistogramImageToImageMetric<TFixedImage, TMovingImage> NumberOfPixelsCounted++; typename HistogramType::MeasurementVectorType sample; +#ifdef ITK_USE_REVIEW_STATISTICS + sample.SetSize(2); +#endif sample[0] = TrainingFixedValue; sample[1] = TrainingMovingValue; this->m_TrainingHistogram->IncreaseFrequency(sample, 1); diff --git a/Utilities/ITK/Code/Algorithms/itkConnectedRegionsMeshFilter.h b/Utilities/ITK/Code/Algorithms/itkConnectedRegionsMeshFilter.h index 23f2fbf2c2..430a51e6a7 100644 --- a/Utilities/ITK/Code/Algorithms/itkConnectedRegionsMeshFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkConnectedRegionsMeshFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConnectedRegionsMeshFilter.h,v $ Language: C++ - Date: $Date: 2008-10-23 16:15:23 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-23 03:53:34 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -117,7 +117,7 @@ public: * a point be defined. */ itkSetMacro( ExtractionMode, int ); - itkGetMacro( ExtractionMode, int ); + itkGetConstMacro( ExtractionMode, int ); void SetExtractionModeToPointSeededRegions( void ) { diff --git a/Utilities/ITK/Code/Algorithms/itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.h b/Utilities/ITK/Code/Algorithms/itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.h index 1ef338fd9f..9c6b27df4e 100644 --- a/Utilities/ITK/Code/Algorithms/itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.h +++ b/Utilities/ITK/Code/Algorithms/itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.h,v $ Language: C++ - Date: $Date: 2008-10-23 16:15:23 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,7 +40,7 @@ namespace itk * \ingroup */ template< typename TSourceImage > -class CoreAtomImageToUnaryCorrespondenceMatrixProcess : public ProcessObject +class ITK_EXPORT CoreAtomImageToUnaryCorrespondenceMatrixProcess : public ProcessObject { public: /** Number of dimensions. */ @@ -62,8 +62,8 @@ public: itkTypeMacro(CoreAtomImageToUnaryCorrespondenceMatrixProcess, ProcessObject); /** GetMacros for number of rows and columns in the unary correspondence matrix. */ - itkGetMacro(Rows, int); - itkGetMacro(Columns, int); + itkGetConstMacro(Rows, int); + itkGetConstMacro(Columns, int); /** Typedef for core atom image. */ typedef TSourceImage CoreAtomImageType; diff --git a/Utilities/ITK/Code/Algorithms/itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.txx b/Utilities/ITK/Code/Algorithms/itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.txx index ca69812856..9b4d3e6a84 100644 --- a/Utilities/ITK/Code/Algorithms/itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.txx +++ b/Utilities/ITK/Code/Algorithms/itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.txx,v $ Language: C++ - Date: $Date: 2008-10-23 16:15:23 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-05-12 20:21:45 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -262,6 +262,8 @@ CoreAtomImageToUnaryCorrespondenceMatrixProcess< TSourceImage > ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); + os << indent << "Columns: " << this->GetColumns() << std::endl; + os << indent << "Rows: " << this->GetRows() << std::endl; } } // end namespace diff --git a/Utilities/ITK/Code/Algorithms/itkCorrelationCoefficientHistogramImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkCorrelationCoefficientHistogramImageToImageMetric.h index 4d5a6d3409..13559b3cba 100644 --- a/Utilities/ITK/Code/Algorithms/itkCorrelationCoefficientHistogramImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkCorrelationCoefficientHistogramImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCorrelationCoefficientHistogramImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2008-10-23 16:15:23 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-02 05:43:54 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -66,7 +66,14 @@ public: typedef typename Superclass::MovingImageConstPointer MovingImageConstPointer; typedef typename Superclass::HistogramType HistogramType; - typedef typename HistogramType::FrequencyType HistogramFrequencyType; + +#ifdef ITK_USE_REVIEW_STATISTICS + typedef typename HistogramType::AbsoluteFrequencyType HistogramAbsoluteFrequencyType; +#else + typedef typename HistogramType::FrequencyType HistogramAbsoluteFrequencyType; +#endif + typedef HistogramAbsoluteFrequencyType HistogramFrequencyType; + typedef typename HistogramType::Iterator HistogramIteratorType; typedef typename HistogramType::MeasurementVectorType HistogramMeasurementVectorType; diff --git a/Utilities/ITK/Code/Algorithms/itkCorrelationCoefficientHistogramImageToImageMetric.txx b/Utilities/ITK/Code/Algorithms/itkCorrelationCoefficientHistogramImageToImageMetric.txx index 21d65fe06a..8a89fb4e22 100644 --- a/Utilities/ITK/Code/Algorithms/itkCorrelationCoefficientHistogramImageToImageMetric.txx +++ b/Utilities/ITK/Code/Algorithms/itkCorrelationCoefficientHistogramImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCorrelationCoefficientHistogramImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2008-10-23 16:15:23 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-05 17:51:18 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -124,6 +124,9 @@ CorrelationCoefficientHistogramImageToImageMetric<TFixedImage, TMovingImage> for (unsigned int i = 0; i < this->m_HistogramSize[0]; i++) { typename HistogramType::IndexType index; +#ifdef ITK_USE_REVIEW_STATISTICS + index.SetSize(2); +#endif index[0] = i; index[1] = j; diff --git a/Utilities/ITK/Code/Algorithms/itkCurvatureFlowImageFilter.h b/Utilities/ITK/Code/Algorithms/itkCurvatureFlowImageFilter.h index 1b21593d6b..18fbf508a9 100644 --- a/Utilities/ITK/Code/Algorithms/itkCurvatureFlowImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkCurvatureFlowImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCurvatureFlowImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-23 16:15:23 $ - Version: $Revision: 1.37 $ + Date: $Date: 2009-04-23 03:53:34 $ + Version: $Revision: 1.38 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -133,7 +133,7 @@ public: itkSetMacro(TimeStep, TimeStepType); /** Get the timestep parameter. */ - itkGetMacro(TimeStep, TimeStepType); + itkGetConstMacro(TimeStep, TimeStepType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Algorithms/itkDeformableMesh3DFilter.h b/Utilities/ITK/Code/Algorithms/itkDeformableMesh3DFilter.h index e6b536ef4b..b499565849 100644 --- a/Utilities/ITK/Code/Algorithms/itkDeformableMesh3DFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkDeformableMesh3DFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformableMesh3DFilter.h,v $ Language: C++ - Date: $Date: 2008-12-08 16:00:51 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-04-28 17:42:50 $ + Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,6 +38,11 @@ namespace itk * The potential force is derived from the gradient information in the * medical image and it will make the model deform to fit to the boundary * features. + * + * Computations are handled with points assumed to lie in index space, + * not physical space. Reverting to physical space compromises backward + * compatibility. + * * Inputs are: * (1) A deformable triangular model (Mesh). Import using the SetInput method. * (2) A gradient map that make the model deform to fit to the estimated boundary. @@ -132,16 +137,16 @@ public: /** Set/Get routines. */ itkSetMacro(Gradient, GradientImagePointer); - itkGetMacro(Gradient, GradientImagePointer); + itkGetConstMacro(Gradient, GradientImagePointer); itkSetMacro(StepThreshold, int); - itkGetMacro(StepThreshold, int); + itkGetConstMacro(StepThreshold, int); itkSetMacro(Stiffness, double2DVector); - itkGetMacro(Stiffness, double2DVector); + itkGetConstMacro(Stiffness, double2DVector); itkSetMacro(TimeStep, double); - itkGetMacro(TimeStep, double); + itkGetConstMacro(TimeStep, double); itkSetMacro(Scale, double3DVector); @@ -150,7 +155,7 @@ public: itkSetMacro(PotentialOn, unsigned short); itkSetMacro(ObjectLabel, unsigned char); - itkGetMacro(Normals, InputMeshPointer); + itkGetConstMacro(Normals, InputMeshPointer); protected: DeformableMesh3DFilter(); diff --git a/Utilities/ITK/Code/Algorithms/itkDeformableMesh3DFilter.txx b/Utilities/ITK/Code/Algorithms/itkDeformableMesh3DFilter.txx index 0c56276482..761cd4667b 100644 --- a/Utilities/ITK/Code/Algorithms/itkDeformableMesh3DFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkDeformableMesh3DFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformableMesh3DFilter.txx,v $ Language: C++ - Date: $Date: 2008-12-08 16:00:52 $ - Version: $Revision: 1.59 $ + Date: $Date: 2009-05-22 17:54:15 $ + Version: $Revision: 1.64 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,6 +41,11 @@ DeformableMesh3DFilter<TInputMesh, TOutputMesh> m_TimeStep = 0.01; m_PotentialMagnitude = NumericTraits<PixelType>::One; m_GradientMagnitude = NumericTraits<PixelType>::One; + + m_ImageDepth = 0; + m_ImageHeight = 0; + m_ImageWidth = 0; + typename TOutputMesh::Pointer output = TOutputMesh::New(); this->ProcessObject::SetNumberOfRequiredOutputs(1); this->ProcessObject::SetNthOutput(0, output.GetPointer()); @@ -95,6 +100,10 @@ DeformableMesh3DFilter<TInputMesh, TOutputMesh> { os << indent << "Gradient = " << "(None)" << std::endl; } + os << indent << "Step = " << m_Step << std::endl; + os << indent << "ImageDepth = " << m_ImageDepth << std::endl; + os << indent << "ImageHeight = " << m_ImageHeight << std::endl; + os << indent << "ImageWidth = " << m_ImageWidth << std::endl; }/* End PrintSelf. */ /* Set default value of parameters and initialize local data container @@ -798,7 +807,7 @@ DeformableMesh3DFilter<TInputMesh, TOutputMesh> v2[0]*(v3[1]-v1[1]) + v3[0]*(v1[1]-v2[1])); - absvec = -sqrt ((double) ((coa*coa) + (cob*cob) + (coc*coc))); + absvec = -vcl_sqrt ((double) ((coa*coa) + (cob*cob) + (coc*coc))); assert (absvec != 0); diff --git a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DBalloonForceFilter.h b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DBalloonForceFilter.h index 8b81e07ccd..7e7a048dbf 100644 --- a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DBalloonForceFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DBalloonForceFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformableSimplexMesh3DBalloonForceFilter.h,v $ Language: C++ - Date: $Date: 2008-12-08 16:00:52 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -43,7 +43,7 @@ namespace itk * */ template <class TInputMesh, class TOutputMesh> -class DeformableSimplexMesh3DBalloonForceFilter : public DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> +class ITK_EXPORT DeformableSimplexMesh3DBalloonForceFilter : public DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> { public: /** Standard "Self" typedef. */ @@ -79,7 +79,7 @@ public: typedef typename GradientIntensityImageType::Pointer GradientIntensityImagePointer; itkSetMacro(Kappa, double); - itkGetMacro(Kappa, double); + itkGetConstMacro(Kappa, double); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DBalloonForceFilter.txx b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DBalloonForceFilter.txx index 10d611282b..21955dcc47 100644 --- a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DBalloonForceFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DBalloonForceFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformableSimplexMesh3DBalloonForceFilter.txx,v $ Language: C++ - Date: $Date: 2008-12-08 16:00:52 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-05-12 20:21:46 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,6 +51,7 @@ DeformableSimplexMesh3DBalloonForceFilter<TInputMesh, TOutputMesh> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); + os << indent << "Kappa = " << m_Kappa << std::endl; }/* End PrintSelf. */ /** Compute model Displacement according to image gradient forces */ diff --git a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DFilter.h b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DFilter.h index b8c814c40f..abc4e7f672 100644 --- a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformableSimplexMesh3DFilter.h,v $ Language: C++ - Date: $Date: 2008-12-08 16:00:52 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -69,7 +69,7 @@ namespace itk * \ingroup MeshSegmentation */ template <class TInputMesh, class TOutputMesh> -class DeformableSimplexMesh3DFilter : public MeshToMeshFilter<TInputMesh, TOutputMesh> +class ITK_EXPORT DeformableSimplexMesh3DFilter : public MeshToMeshFilter<TInputMesh, TOutputMesh> { public: /** Standard "Self" typedef. */ @@ -150,54 +150,54 @@ public: /** * Getter for gradient image */ - itkGetMacro(Gradient, GradientImagePointer); + itkGetConstMacro(Gradient, GradientImagePointer); /** * Set number of iterations for deformation process */ itkSetMacro(Iterations, int); - itkGetMacro(Iterations, int); + itkGetConstMacro(Iterations, int); /** Set scalar factor for internal force */ itkSetMacro(Alpha, double); /** Get internal force scaling factor */ - itkGetMacro(Alpha, double); + itkGetConstMacro(Alpha, double); /** Set external force scaling factor */ itkSetMacro(Beta, double); /** Get external force scaling factor */ - itkGetMacro(Beta, double); + itkGetConstMacro(Beta, double); /** Set reference metrics update scaling factor */ itkSetMacro(Gamma, double); /** Get reference metrics update scaling factor */ - itkGetMacro(Gamma, double); + itkGetConstMacro(Gamma, double); /** Set reference metrics update scaling factor */ itkSetMacro(Damping, double); /** Get reference metrics update scaling factor */ - itkGetMacro(Damping, double); + itkGetConstMacro(Damping, double); /** control smoothness of the mesh */ itkSetMacro(Rigidity, unsigned int); /** control smoothness of the mesh */ - itkGetMacro(Rigidity, unsigned int); + itkGetConstMacro(Rigidity, unsigned int); itkSetObjectMacro(Data, GeometryMapType ); itkGetObjectMacro(Data, GeometryMapType ); /** Width, height and depth of image */ - itkGetMacro(ImageWidth,int); - itkGetMacro(ImageHeight,int); - itkGetMacro(ImageDepth,int); + itkGetConstMacro(ImageWidth,int); + itkGetConstMacro(ImageHeight,int); + itkGetConstMacro(ImageDepth,int); /** current iteration number */ - itkGetMacro(Step, int); + itkGetConstMacro(Step, int); protected: DeformableSimplexMesh3DFilter(); diff --git a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DFilter.txx b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DFilter.txx index 9533bee2ee..d9717cb543 100644 --- a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformableSimplexMesh3DFilter.txx,v $ Language: C++ - Date: $Date: 2008-12-08 16:00:52 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-05-22 18:02:19 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,6 +49,9 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> m_Damping = 0.65; m_Rigidity = 1; + m_ImageDepth = 0; + m_ImageHeight = 0; + m_ImageWidth = 0; this->ProcessObject::SetNumberOfRequiredInputs(1); @@ -56,9 +59,7 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> this->ProcessObject::SetNumberOfRequiredOutputs(1); this->ProcessObject::SetNthOutput(0, output.GetPointer()); - m_Data = NULL; - - + this->m_Data = NULL; } template <typename TInputMesh, typename TOutputMesh> @@ -75,11 +76,33 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); - os << indent << "alpha = " << m_Alpha << std::endl; - os << indent << "beta = " << m_Beta << std::endl; - os << indent << "gamma = " << m_Gamma << std::endl; - os << indent << "rigidity = " << m_Rigidity << std::endl; - os << indent << "No. of Iterations = " << m_Iterations << std::endl; + os << indent << "Alpha = " << m_Alpha << std::endl; + os << indent << "Beta = " << m_Beta << std::endl; + os << indent << "Gamma = " << m_Gamma << std::endl; + os << indent << "Rigidity = " << m_Rigidity << std::endl; + os << indent << "Iterations = " << m_Iterations << std::endl; + os << indent << "Step = " << m_Step << std::endl; + os << indent << "ImageDepth = " << m_ImageDepth << std::endl; + if( this->m_Gradient.IsNotNull() ) + { + os << indent << "Gradient = " << this->m_Gradient << std::endl; + } + else + { + os << indent << "Gradient = " << "(None)" << std::endl; + } + os << indent << "ImageHeight = " << m_ImageHeight << std::endl; + os << indent << "ImageWidth = " << m_ImageWidth << std::endl; + os << indent << "Damping = " << m_Damping << std::endl; + if( this->m_Data.IsNotNull() ) + { + os << indent << "Data = " << this->m_Data << std::endl; + } + else + { + os << indent << "Data = " << "(None)" << std::endl; + } + }/* End PrintSelf. */ @@ -117,7 +140,7 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> { SimplexMeshGeometry * data; unsigned long idx = points.Index(); - data = m_Data->GetElement(idx); + data = this->m_Data->GetElement(idx); delete data->neighborSet; points++; } @@ -135,9 +158,9 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> InputPointsContainerPointer myPoints = this->GetInput(0)->GetPoints(); InputPointsContainerIterator points = myPoints->Begin(); - if ( m_Gradient.IsNotNull() ) + if ( this->m_Gradient.IsNotNull() ) { - GradientImageSizeType imageSize = m_Gradient->GetBufferedRegion().GetSize(); + GradientImageSizeType imageSize = this->m_Gradient->GetBufferedRegion().GetSize(); m_ImageWidth = imageSize[0]; m_ImageHeight = imageSize[1]; @@ -150,9 +173,9 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> m_ImageDepth = 0; } - if (m_Data.IsNull() ) + if( this->m_Data.IsNull() ) { - m_Data = this->GetInput(0)->GetGeometryData(); + this->m_Data = this->GetInput(0)->GetGeometryData(); } while( points != myPoints->End() ) @@ -160,7 +183,7 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> SimplexMeshGeometry * data; unsigned long idx = points.Index(); - data = m_Data->GetElement(idx); + data = this->m_Data->GetElement(idx); data->pos = points.Value(); // InputMeshType::ArrayType neighbors = this->GetInput(0)->GetNeighbors( points.Index() ); @@ -202,11 +225,11 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> InputMeshPointer inputMesh = this->GetInput(0); - typename GeometryMapType::Iterator dataIt = m_Data->Begin(); + typename GeometryMapType::Iterator dataIt = this->m_Data->Begin(); SimplexMeshGeometry* data; - while ( dataIt != m_Data->End() ) + while ( dataIt != this->m_Data->End() ) { // idx = dataIt.Index(); data = dataIt.Value(); @@ -262,11 +285,11 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> ::ComputeDisplacement() { InputMeshPointer inputMesh = this->GetInput(0); - typename GeometryMapType::Iterator dataIt = m_Data->Begin(); + typename GeometryMapType::Iterator dataIt = this->m_Data->Begin(); SimplexMeshGeometry * data; VectorType displacement; - while( dataIt != m_Data->End() ) + while( dataIt != this->m_Data->End() ) { data = dataIt.Value(); @@ -326,7 +349,7 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> while ( neighborIt != neighborSet->end() ) { - phiRef += m_Data->GetElement(*neighborIt++)->phi; + phiRef += this->m_Data->GetElement(*neighborIt++)->phi; } phiRef /= (double) neighborSet->size(); @@ -435,7 +458,7 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> output->SetPoints(this->GetInput(0)->GetPoints()); output->SetPointData(this->GetInput(0)->GetPointData()); output->SetCells(this->GetInput(0)->GetCells()); - output->SetGeometryData(m_Data); + output->SetGeometryData(this->m_Data); output->SetLastCellId( this->GetInput(0)->GetLastCellId() ); } @@ -455,16 +478,16 @@ DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> double H_N3; double H_Mean; - GeometryMapIterator dataIt = m_Data->Begin(); + GeometryMapIterator dataIt = this->m_Data->Begin(); SimplexMeshGeometry * data; - while ( dataIt != m_Data->End() ) + while ( dataIt != this->m_Data->End() ) { data = dataIt->Value(); - H_N1 =((SimplexMeshGeometry*)(m_Data->GetElement(data->neighborIndices[0])))->meanCurvature; - H_N2 =((SimplexMeshGeometry*)(m_Data->GetElement(data->neighborIndices[1])))->meanCurvature; - H_N3 =((SimplexMeshGeometry*)(m_Data->GetElement(data->neighborIndices[2])))->meanCurvature; + H_N1 =((SimplexMeshGeometry*)(this->m_Data->GetElement(data->neighborIndices[0])))->meanCurvature; + H_N2 =((SimplexMeshGeometry*)(this->m_Data->GetElement(data->neighborIndices[1])))->meanCurvature; + H_N3 =((SimplexMeshGeometry*)(this->m_Data->GetElement(data->neighborIndices[2])))->meanCurvature; H = data->meanCurvature; H_Mean = (H_N1 + H_N2 + H_N3)/3.0; @@ -519,7 +542,7 @@ double DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> double tmpSqr = r2 + r2Minusd2 * tanPhi*tanPhi; if (tmpSqr > 0) { - double denom = eps*(sqrt(tmpSqr) + r); + double denom = eps*(vcl_sqrt(tmpSqr) + r); if ( denom != 0 ) { L = (r2Minusd2 * tanPhi) / denom; diff --git a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.h b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.h index 73db925f30..4af70d3ca4 100644 --- a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformableSimplexMesh3DGradientConstraintForceFilter.h,v $ Language: C++ - Date: $Date: 2007-04-10 19:50:04 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,7 +85,7 @@ public: */ template <class TInputMesh, class TOutputMesh> -class DeformableSimplexMesh3DGradientConstraintForceFilter : public DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> +class ITK_EXPORT DeformableSimplexMesh3DGradientConstraintForceFilter : public DeformableSimplexMesh3DFilter<TInputMesh, TOutputMesh> { public: /** Standard "Self" typedefs. */ @@ -127,7 +127,7 @@ public: typedef typename OriginalImageType::Pointer OriginalImagePointer; /** control the range of search for Bresenham at normal line */ itkSetMacro(Range, int); - itkGetMacro(Range, int); + itkGetConstMacro(Range, int); // full segment or half segment direction enum SIDE diff --git a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.txx b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.txx index bd97d8c6a1..b187f70f04 100644 --- a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformableSimplexMesh3DGradientConstraintForceFilter.txx,v $ Language: C++ - Date: $Date: 2008-02-03 04:05:28 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-05-12 20:21:46 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,6 +49,9 @@ DeformableSimplexMesh3DGradientConstraintForceFilter<TInputMesh, TOutputMesh> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); + os << indent << "Range = " << m_Range << std::endl; + os << indent << "Image = " << m_Image << std::endl; + } template <typename TInputMesh, typename TOutputMesh> diff --git a/Utilities/ITK/Code/Algorithms/itkDemonsRegistrationFilter.h b/Utilities/ITK/Code/Algorithms/itkDemonsRegistrationFilter.h index c56f0377ef..b2474b8b0b 100644 --- a/Utilities/ITK/Code/Algorithms/itkDemonsRegistrationFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkDemonsRegistrationFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDemonsRegistrationFilter.h,v $ Language: C++ - Date: $Date: 2008-12-08 16:00:52 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -112,7 +112,7 @@ public: /** Switch between using the fixed image and moving image gradient * for computing the deformation field updates. */ itkSetMacro( UseMovingImageGradient, bool ); - itkGetMacro( UseMovingImageGradient, bool ); + itkGetConstMacro( UseMovingImageGradient, bool ); itkBooleanMacro( UseMovingImageGradient ); /** Set/Get the threshold below which the absolute difference of diff --git a/Utilities/ITK/Code/Algorithms/itkEuclideanDistancePointMetric.h b/Utilities/ITK/Code/Algorithms/itkEuclideanDistancePointMetric.h index 61b6dd1e89..87cc8a34ce 100644 --- a/Utilities/ITK/Code/Algorithms/itkEuclideanDistancePointMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkEuclideanDistancePointMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEuclideanDistancePointMetric.h,v $ Language: C++ - Date: $Date: 2008-12-17 18:52:03 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,7 +100,7 @@ public: /** Set/Get if the distance should be squared. Default is true for computation speed */ itkSetMacro(ComputeSquaredDistance,bool); - itkGetMacro(ComputeSquaredDistance,bool); + itkGetConstMacro(ComputeSquaredDistance,bool); itkBooleanMacro(ComputeSquaredDistance); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkFEMFiniteDifferenceFunctionLoad.h b/Utilities/ITK/Code/Algorithms/itkFEMFiniteDifferenceFunctionLoad.h index add3728595..c3525fce50 100644 --- a/Utilities/ITK/Code/Algorithms/itkFEMFiniteDifferenceFunctionLoad.h +++ b/Utilities/ITK/Code/Algorithms/itkFEMFiniteDifferenceFunctionLoad.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFEMFiniteDifferenceFunctionLoad.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:10 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -61,7 +61,7 @@ namespace fem * and more functionality will be available (such as scale selection). */ template<class TMoving,class TFixed> -class FiniteDifferenceFunctionLoad : public LoadElement +class ITK_EXPORT FiniteDifferenceFunctionLoad : public LoadElement { FEM_CLASS(FiniteDifferenceFunctionLoad,LoadElement) public: diff --git a/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.h b/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.h index a99dd0a07e..fc4c350e1d 100644 --- a/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFEMRegistrationFilter.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:11 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -542,7 +542,7 @@ protected : /** Set the solver's current load. */ // itkSetMacro( Load, ImageMetricLoadType* ); - itkGetMacro( Load, ImageMetricLoadType* ); + itkGetConstMacro( Load, ImageMetricLoadType* ); void PrintSelf(std::ostream& os, Indent indent) const; diff --git a/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.txx b/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.txx index 4f13638e28..bf0534cf2f 100644 --- a/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFEMRegistrationFilter.txx,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:11 $ - Version: $Revision: 1.57 $ + Date: $Date: 2009-04-05 23:09:18 $ + Version: $Revision: 1.58 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -1747,7 +1747,7 @@ void FEMRegistrationFilter<TMovingImage,TFixedImage>::PrintVectorField(unsigned if ((ct % modnum) == 0) std::cout << " field pix " << fieldIter.Get() << std::endl; for (unsigned int i=0; i<ImageDimension;i++) { - if (fabs(disp[i]) > max ) + if (vcl_fabs(disp[i]) > max ) { max=vcl_fabs(disp[i]); } @@ -1960,7 +1960,7 @@ void FEMRegistrationFilter<TMovingImage,TFixedImage>::FindBracketingTriplet(Solv { r=(bx-ax)*(fb-fc); q=(bx-cx)*(fb-fa); - Float denom=(2.0*mySolver.GSSign(mySolver.GSMax(fabs(q-r),Tiny),q-r)); + Float denom=(2.0*mySolver.GSSign(mySolver.GSMax(vcl_fabs(q-r),Tiny),q-r)); u=(bx)-((bx-cx)*q-(bx-ax)*r)/denom; ulim=bx + Glimit*(cx-bx); if ((bx-u)*(u-cx) > 0.0) @@ -2035,7 +2035,7 @@ Element::Float FEMRegistrationFilter<TMovingImage,TFixedImage>::GoldenSection(So Float x1; Float x2; Float x3=cx; - if (fabs(cx-bx) > vcl_fabs(bx-ax)) + if (vcl_fabs(cx-bx) > vcl_fabs(bx-ax)) { x1=bx; x2=bx+C*(cx-bx); @@ -2049,7 +2049,7 @@ Element::Float FEMRegistrationFilter<TMovingImage,TFixedImage>::GoldenSection(So Float f1=vcl_fabs(EvaluateResidual(mySolver, x1)); Float f2=vcl_fabs(EvaluateResidual(mySolver, x2)); unsigned int iters=0; - while (fabs(x3-x0) > tol*(fabs(x1)+vcl_fabs(x2)) && iters < MaxIters) + while (vcl_fabs(x3-x0) > tol*(vcl_fabs(x1)+vcl_fabs(x2)) && iters < MaxIters) { iters++; if (f2 < f1) diff --git a/Utilities/ITK/Code/Algorithms/itkFFTComplexConjugateToRealImageFilter.h b/Utilities/ITK/Code/Algorithms/itkFFTComplexConjugateToRealImageFilter.h index 42ba298278..d55fec15a2 100644 --- a/Utilities/ITK/Code/Algorithms/itkFFTComplexConjugateToRealImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkFFTComplexConjugateToRealImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFFTComplexConjugateToRealImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:11 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -31,7 +31,7 @@ namespace itk */ template < class TPixel,unsigned int VDimension = 3 > -class FFTComplexConjugateToRealImageFilter : +class ITK_EXPORT FFTComplexConjugateToRealImageFilter : public ImageToImageFilter< Image< std::complex< TPixel > , VDimension >, Image< TPixel,VDimension > > diff --git a/Utilities/ITK/Code/Algorithms/itkFFTWComplexConjugateToRealImageFilter.h b/Utilities/ITK/Code/Algorithms/itkFFTWComplexConjugateToRealImageFilter.h index 31eecaed1e..ab7c404fae 100644 --- a/Utilities/ITK/Code/Algorithms/itkFFTWComplexConjugateToRealImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkFFTWComplexConjugateToRealImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFFTWComplexConjugateToRealImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:11 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -28,7 +28,7 @@ namespace itk { template <typename TPixel,unsigned int VDimension> -class FFTWComplexConjugateToRealImageFilter : +class ITK_EXPORT FFTWComplexConjugateToRealImageFilter : public FFTComplexConjugateToRealImageFilter<TPixel,VDimension> { public: diff --git a/Utilities/ITK/Code/Algorithms/itkFastChamferDistanceImageFilter.h b/Utilities/ITK/Code/Algorithms/itkFastChamferDistanceImageFilter.h index 41c3e1db9b..2891673ec7 100644 --- a/Utilities/ITK/Code/Algorithms/itkFastChamferDistanceImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkFastChamferDistanceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFastChamferDistanceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:11 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -111,7 +111,7 @@ public: /** Maximal computed distance */ itkSetMacro( MaximumDistance, float); - itkGetMacro( MaximumDistance, float); + itkGetConstMacro( MaximumDistance, float); /** */ void SetRegionToProcess( const RegionType &r) diff --git a/Utilities/ITK/Code/Algorithms/itkFastChamferDistanceImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkFastChamferDistanceImageFilter.txx index 1cc0bc9b63..01fe4defc3 100644 --- a/Utilities/ITK/Code/Algorithms/itkFastChamferDistanceImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkFastChamferDistanceImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFastChamferDistanceImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:11 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-05 23:09:19 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -179,7 +179,7 @@ void FastChamferDistanceImageFilter<TInputImage,TOutputImage> // Update the narrow band if (m_NarrowBand.IsNotNull()) { - if (fabs((float)center_value) <= m_NarrowBand->GetTotalRadius()) + if (vcl_fabs((float)center_value) <= m_NarrowBand->GetTotalRadius()) { node.m_Index = it.GetIndex(); //Check node state. @@ -188,7 +188,7 @@ void FastChamferDistanceImageFilter<TInputImage,TOutputImage> { node.m_NodeState += SIGN_MASK; } - if (fabs((float)center_value) < m_NarrowBand->GetInnerRadius()) + if (vcl_fabs((float)center_value) < m_NarrowBand->GetInnerRadius()) { node.m_NodeState += INNER_MASK; } diff --git a/Utilities/ITK/Code/Algorithms/itkFastMarchingImageFilter.h b/Utilities/ITK/Code/Algorithms/itkFastMarchingImageFilter.h index 229c763572..2f4f854878 100644 --- a/Utilities/ITK/Code/Algorithms/itkFastMarchingImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkFastMarchingImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFastMarchingImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:11 $ - Version: $Revision: 1.39 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.40 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -222,7 +222,7 @@ public: factor. This allows the use of images with integer pixel types to represent the speed. */ itkSetMacro( NormalizationFactor, double ); - itkGetMacro( NormalizationFactor, double ); + itkGetConstMacro( NormalizationFactor, double ); /** Set the Fast Marching algorithm Stopping Value. The Fast Marching * algorithm is terminated when the value of the smallest trial point diff --git a/Utilities/ITK/Code/Algorithms/itkGradientVectorFlowImageFilter.h b/Utilities/ITK/Code/Algorithms/itkGradientVectorFlowImageFilter.h index a1d7d7f3f7..da291c9176 100644 --- a/Utilities/ITK/Code/Algorithms/itkGradientVectorFlowImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkGradientVectorFlowImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientVectorFlowImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-11 06:19:49 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,13 +95,13 @@ public: itkSetMacro(LaplacianFilter, LaplacianFilterPointer); itkSetMacro(TimeStep, double); - itkGetMacro(TimeStep, double); + itkGetConstMacro(TimeStep, double); itkSetMacro(NoiseLevel, double); - itkGetMacro(NoiseLevel, double); + itkGetConstMacro(NoiseLevel, double); itkSetMacro(IterationNum, int); - itkGetMacro(IterationNum, int); + itkGetConstMacro(IterationNum, int); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Algorithms/itkHistogramAlgorithmBase.h b/Utilities/ITK/Code/Algorithms/itkHistogramAlgorithmBase.h index b64dbb9fae..66992a74f1 100644 --- a/Utilities/ITK/Code/Algorithms/itkHistogramAlgorithmBase.h +++ b/Utilities/ITK/Code/Algorithms/itkHistogramAlgorithmBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramAlgorithmBase.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:12 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,7 +34,7 @@ namespace itk */ template< class TInputHistogram > -class HistogramAlgorithmBase : public Object +class ITK_EXPORT HistogramAlgorithmBase : public Object { public: /**Standard class typedefs. */ diff --git a/Utilities/ITK/Code/Algorithms/itkHistogramImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkHistogramImageToImageMetric.h index 38c4f25d4e..30148aeca2 100644 --- a/Utilities/ITK/Code/Algorithms/itkHistogramImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkHistogramImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:12 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-05-02 05:43:54 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -71,7 +71,12 @@ public: /** Typedefs for histogram. This should have been defined as Histogram<RealType,2> but a bug in VC++7 produced an internal compiler error with such declaration. */ +#ifdef ITK_USE_REVIEW_STATISTICS + typedef Statistics::Histogram<double> HistogramType; +#else typedef Statistics::Histogram<double, 2> HistogramType; +#endif + typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; typedef typename HistogramType::SizeType HistogramSizeType; typedef typename HistogramType::Pointer HistogramPointer; @@ -93,7 +98,7 @@ public: /** Factor to increase the upper bound for the samples in the histogram. Default value is 0.001 */ itkSetMacro( UpperBoundIncreaseFactor, double ); - itkGetMacro( UpperBoundIncreaseFactor, double ); + itkGetConstMacro( UpperBoundIncreaseFactor, double ); /** The padding value. */ itkSetMacro( PaddingValue, FixedImagePixelType ); @@ -110,13 +115,13 @@ public: should be ignored when calculating the similarity measure. Those pixels in the fixed image which have the padding value will be ignored. */ itkSetMacro( UsePaddingValue, bool ); - itkGetMacro( UsePaddingValue, bool ); + itkGetConstMacro( UsePaddingValue, bool ); /** Sets the step length used to calculate the derivative. */ itkSetMacro( DerivativeStepLength, double ); /** Returns the step length used to calculate the derivative. */ - itkGetMacro( DerivativeStepLength, double ); + itkGetConstMacro( DerivativeStepLength, double ); /** The scales type. */ typedef Array<double> ScalesType; diff --git a/Utilities/ITK/Code/Algorithms/itkHistogramImageToImageMetric.txx b/Utilities/ITK/Code/Algorithms/itkHistogramImageToImageMetric.txx index b9b8f958ac..05a8315d8e 100644 --- a/Utilities/ITK/Code/Algorithms/itkHistogramImageToImageMetric.txx +++ b/Utilities/ITK/Code/Algorithms/itkHistogramImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:12 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-05-05 17:47:30 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,6 +38,9 @@ HistogramImageToImageMetric<TFixedImage,TMovingImage> m_UpperBoundIncreaseFactor = 0.001; m_PaddingValue = NumericTraits<FixedImagePixelType>::Zero; m_Histogram = HistogramType::New(); +#ifdef ITK_USE_REVIEW_STATISTICS + m_Histogram->SetMeasurementVectorSize(2); +#endif m_LowerBoundSetByUser = false; m_UpperBoundSetByUser = false; } @@ -132,12 +135,18 @@ void HistogramImageToImageMetric<TFixedImage, TMovingImage> // Initialize the upper and lower bounds of the histogram. if( !m_LowerBoundSetByUser ) { +#ifdef ITK_USE_REVIEW_STATISTICS + m_LowerBound.SetSize(2); +#endif m_LowerBound[0] = minFixed; m_LowerBound[1] = minMoving; } if( !m_UpperBoundSetByUser ) { +#ifdef ITK_USE_REVIEW_STATISTICS + m_UpperBound.SetSize(2); +#endif m_UpperBound[0] = maxFixed + (maxFixed - minFixed ) * m_UpperBoundIncreaseFactor; m_UpperBound[1] = @@ -200,11 +209,17 @@ HistogramImageToImageMetric<TFixedImage,TMovingImage> DerivativeType::ValueType>::Zero); typename HistogramType::Pointer pHistogram = HistogramType::New(); +#ifdef ITK_USE_REVIEW_STATISTICS + pHistogram->SetMeasurementVectorSize(2); +#endif this->ComputeHistogram(parameters, *pHistogram); for (unsigned int i = 0; i < ParametersDimension; i++) { typename HistogramType::Pointer pHistogram2 = HistogramType::New(); +#ifdef ITK_USE_REVIEW_STATISTICS + pHistogram2->SetMeasurementVectorSize(2); +#endif this->CopyHistogram(*pHistogram2, *pHistogram); TransformParametersType newParameters = parameters; @@ -215,6 +230,9 @@ HistogramImageToImageMetric<TFixedImage,TMovingImage> MeasureType e0 = EvaluateMeasure(*pHistogram2); pHistogram2 = HistogramType::New(); +#ifdef ITK_USE_REVIEW_STATISTICS + pHistogram2->SetMeasurementVectorSize(2); +#endif this->CopyHistogram(*pHistogram2, *pHistogram); newParameters = parameters; @@ -304,6 +322,9 @@ HistogramImageToImageMetric<TFixedImage,TMovingImage> this->m_NumberOfPixelsCounted++; typename HistogramType::MeasurementVectorType sample; +#ifdef ITK_USE_REVIEW_STATISTICS + sample.SetSize(2); +#endif sample[0] = fixedValue; sample[1] = movingValue; histogram.IncreaseFrequency(sample, 1); @@ -328,6 +349,12 @@ HistogramImageToImageMetric<TFixedImage,TMovingImage> { // Initialize the target. typename HistogramType::MeasurementVectorType min, max; + +#ifdef ITK_USE_REVIEW_STATISTICS + min.SetSize(2); + max.SetSize(2); +#endif + typename HistogramType::SizeType size = source.GetSize(); for (unsigned int i = 0; i < min.Size(); i++) @@ -350,7 +377,12 @@ HistogramImageToImageMetric<TFixedImage,TMovingImage> while (sourceIt != sourceEnd && targetIt != targetEnd) { - typename HistogramType::FrequencyType freq = sourceIt.GetFrequency(); +#ifdef ITK_USE_REVIEW_STATISTICS + typename HistogramType::AbsoluteFrequencyType +#else + typename HistogramType::FrequencyType +#endif + freq = sourceIt.GetFrequency(); if (freq > 0) { diff --git a/Utilities/ITK/Code/Algorithms/itkHistogramMatchingImageFilter.h b/Utilities/ITK/Code/Algorithms/itkHistogramMatchingImageFilter.h index c9fa55fb9b..d80c958a68 100644 --- a/Utilities/ITK/Code/Algorithms/itkHistogramMatchingImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkHistogramMatchingImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramMatchingImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:12 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-05-02 05:43:54 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,7 +95,11 @@ public: typedef typename OutputImageType::PixelType OutputPixelType; /** Histogram related typedefs. */ +#ifdef ITK_USE_REVIEW_STATISTICS + typedef Statistics::Histogram<THistogramMeasurement > HistogramType; +#else typedef Statistics::Histogram<THistogramMeasurement, 1> HistogramType; +#endif typedef typename HistogramType::Pointer HistogramPointer; /** Set/Get the source image. */ @@ -110,11 +114,11 @@ public: /** Set/Get the number of histogram levels used. */ itkSetMacro( NumberOfHistogramLevels, unsigned long ); - itkGetMacro( NumberOfHistogramLevels, unsigned long ); + itkGetConstMacro( NumberOfHistogramLevels, unsigned long ); /** Set/Get the number of match points used. */ itkSetMacro( NumberOfMatchPoints, unsigned long ); - itkGetMacro( NumberOfMatchPoints, unsigned long ); + itkGetConstMacro( NumberOfMatchPoints, unsigned long ); /** Set/Get the threshold at mean intensity flag. * If true, only source (reference) pixels which are greater @@ -122,7 +126,7 @@ public: * the histogram matching. If false, all pixels are * used. */ itkSetMacro( ThresholdAtMeanIntensity, bool ); - itkGetMacro( ThresholdAtMeanIntensity, bool ); + itkGetConstMacro( ThresholdAtMeanIntensity, bool ); itkBooleanMacro( ThresholdAtMeanIntensity ); /** This filter requires all of the input to be in the buffer. */ diff --git a/Utilities/ITK/Code/Algorithms/itkHistogramMatchingImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkHistogramMatchingImageFilter.txx index 2a244fa175..efa5ed0568 100644 --- a/Utilities/ITK/Code/Algorithms/itkHistogramMatchingImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkHistogramMatchingImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramMatchingImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:12 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-05-05 17:00:00 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -426,10 +426,18 @@ HistogramMatchingImageFilter<TInputImage,TOutputImage,THistogramMeasurement> { // allocate memory for the histogram typename HistogramType::SizeType size; - size[0] = m_NumberOfHistogramLevels; typename HistogramType::MeasurementVectorType lowerBound; - lowerBound.Fill(minValue); typename HistogramType::MeasurementVectorType upperBound; + +#ifdef ITK_USE_REVIEW_STATISTICS + size.SetSize(1); + lowerBound.SetSize(1); + upperBound.SetSize(1); + histogram->SetMeasurementVectorSize(1); +#endif + + size[0] = m_NumberOfHistogramLevels; + lowerBound.Fill(minValue); upperBound.Fill(maxValue); //Initialize with equally spaced bins. @@ -438,6 +446,11 @@ HistogramMatchingImageFilter<TInputImage,TOutputImage,THistogramMeasurement> } typename HistogramType::MeasurementVectorType measurement; + +#ifdef ITK_USE_REVIEW_STATISTICS + measurement.SetSize(1); +#endif + typedef typename HistogramType::MeasurementType MeasurementType; measurement[0] = NumericTraits<MeasurementType>::Zero; diff --git a/Utilities/ITK/Code/Algorithms/itkImageClassifierBase.h b/Utilities/ITK/Code/Algorithms/itkImageClassifierBase.h index f4eacacb69..67dd513ad0 100644 --- a/Utilities/ITK/Code/Algorithms/itkImageClassifierBase.h +++ b/Utilities/ITK/Code/Algorithms/itkImageClassifierBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageClassifierBase.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:54 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -119,7 +119,7 @@ public: itkSetMacro(ClassifiedImage,ClassifiedImagePointer); /** Get the classified image. */ - itkGetMacro(ClassifiedImage,ClassifiedImagePointer); + itkGetConstMacro(ClassifiedImage,ClassifiedImagePointer); /** Type definition for the vector associated with * input image pixel type. */ diff --git a/Utilities/ITK/Code/Algorithms/itkImageGaussianModelEstimator.h b/Utilities/ITK/Code/Algorithms/itkImageGaussianModelEstimator.h index b1d2a60180..57bdb3ade3 100644 --- a/Utilities/ITK/Code/Algorithms/itkImageGaussianModelEstimator.h +++ b/Utilities/ITK/Code/Algorithms/itkImageGaussianModelEstimator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageGaussianModelEstimator.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:54 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -119,7 +119,7 @@ public: itkSetMacro(TrainingImage,TrainingImagePointer); /** Get the training image. */ - itkGetMacro(TrainingImage,TrainingImagePointer); + itkGetConstMacro(TrainingImage,TrainingImagePointer); protected: ImageGaussianModelEstimator(); diff --git a/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.h b/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.h index 260bc73b50..948498103a 100644 --- a/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.h +++ b/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageKmeansModelEstimator.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:54 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -172,7 +172,7 @@ public: void SetCodebook(CodebookMatrixOfDoubleType InCodebook); /** Get the cluster centers. */ - itkGetMacro(Codebook,CodebookMatrixOfDoubleType); + itkGetConstMacro(Codebook,CodebookMatrixOfDoubleType); /** Get the optimized codebook or the centroids of the clusters. */ CodebookMatrixOfDoubleType GetOutCodebook() @@ -182,25 +182,25 @@ public: itkSetMacro(Threshold,double); /** Get the threshold parameter. */ - itkGetMacro(Threshold,double); + itkGetConstMacro(Threshold,double); /** Set the offset add parameter. */ itkSetMacro(OffsetAdd,double); /** Get the offset add parameter. */ - itkGetMacro(OffsetAdd,double); + itkGetConstMacro(OffsetAdd,double); /** Set the offset multiplication parameter. */ itkSetMacro(OffsetMultiply,double); /** Get the offset multiplication parameter. */ - itkGetMacro(OffsetMultiply,double); + itkGetConstMacro(OffsetMultiply,double); /** Set the maximum number of attempts to split a codeword. */ itkSetMacro(MaxSplitAttempts,int); /** Get the manimum number of attempts to split a codeword. */ - itkGetMacro(MaxSplitAttempts,int); + itkGetConstMacro(MaxSplitAttempts,int); /** Return the codebook/cluster centers. */ CodebookMatrixOfDoubleType GetKmeansResults(void) diff --git a/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.txx b/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.txx index 21274dca5f..f8aafedc03 100644 --- a/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.txx +++ b/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageKmeansModelEstimator.txx,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:55 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-05-02 05:43:54 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -274,8 +274,13 @@ ImageKmeansModelEstimator<TInputImage, TMembershipFunction> for (unsigned int classIndex = 0; classIndex < numberOfModels; classIndex++) { membershipFunction = TMembershipFunction::New(); - membershipFunction->SetNumberOfSamples( 0 ); +#ifdef ITK_USE_REVIEW_STATISTICS + typename TMembershipFunction::CentroidType centroid; + centroid = m_Centroid.get_row( classIndex); + membershipFunction->SetCentroid( centroid ); +#else membershipFunction->SetCentroid(m_Centroid.get_row( classIndex) ); +#endif this->AddMembershipFunction( membershipFunction ); } diff --git a/Utilities/ITK/Code/Algorithms/itkImagePCADecompositionCalculator.h b/Utilities/ITK/Code/Algorithms/itkImagePCADecompositionCalculator.h index 38de30608d..621da8637d 100755 --- a/Utilities/ITK/Code/Algorithms/itkImagePCADecompositionCalculator.h +++ b/Utilities/ITK/Code/Algorithms/itkImagePCADecompositionCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImagePCADecompositionCalculator.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:56 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -124,7 +124,7 @@ public: void Compute(void); /** Return the projection of the image. */ - itkGetMacro(Projection,BasisVectorType); + itkGetConstMacro(Projection,BasisVectorType); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkImagePCAShapeModelEstimator.h b/Utilities/ITK/Code/Algorithms/itkImagePCAShapeModelEstimator.h index 8d81af9658..66d34fc4a9 100644 --- a/Utilities/ITK/Code/Algorithms/itkImagePCAShapeModelEstimator.h +++ b/Utilities/ITK/Code/Algorithms/itkImagePCAShapeModelEstimator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImagePCAShapeModelEstimator.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:56 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -122,14 +122,14 @@ public: * one outputs. Output index 0 represents the mean image and the * remaining outputs the requested principal components. */ virtual void SetNumberOfPrincipalComponentsRequired( unsigned int n ); - itkGetMacro( NumberOfPrincipalComponentsRequired, unsigned int ); + itkGetConstMacro( NumberOfPrincipalComponentsRequired, unsigned int ); /** Set/Get the number of training images in the input. */ virtual void SetNumberOfTrainingImages( unsigned int n ); - itkGetMacro(NumberOfTrainingImages, unsigned int); + itkGetConstMacro(NumberOfTrainingImages, unsigned int); /** Get the eigen values */ - itkGetMacro(EigenValues, VectorOfDoubleType); + itkGetConstMacro(EigenValues, VectorOfDoubleType); protected: ImagePCAShapeModelEstimator(); diff --git a/Utilities/ITK/Code/Algorithms/itkImageRegistrationMethod.h b/Utilities/ITK/Code/Algorithms/itkImageRegistrationMethod.h index 070ae929a6..d8f301dc2d 100644 --- a/Utilities/ITK/Code/Algorithms/itkImageRegistrationMethod.h +++ b/Utilities/ITK/Code/Algorithms/itkImageRegistrationMethod.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageRegistrationMethod.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:56 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -173,7 +173,7 @@ public: itkGetConstReferenceMacro( FixedImageRegion, FixedImageRegionType ); /** True if a region has been defined for the fixed image to which the ImageMetric will limit its computation */ - itkGetMacro( FixedImageRegionDefined, bool ); + itkGetConstMacro( FixedImageRegionDefined, bool ); /** Turn on/off the use of a fixed image region to which the ImageMetric will limit its computation. \warning The region must have been previously defined using the diff --git a/Utilities/ITK/Code/Algorithms/itkIsoContourDistanceImageFilter.h b/Utilities/ITK/Code/Algorithms/itkIsoContourDistanceImageFilter.h index 7c4b1c0e0b..504942e022 100644 --- a/Utilities/ITK/Code/Algorithms/itkIsoContourDistanceImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkIsoContourDistanceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIsoContourDistanceImageFilter.h,v $ Language: C++ - Date: $Date: 2007-12-18 04:01:46 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,18 +100,18 @@ public: /** Set/Get the value of the level set to be located. The default value is * 0. */ itkSetMacro( LevelSetValue, InputPixelType ); - itkGetMacro( LevelSetValue, InputPixelType ); + itkGetConstMacro( LevelSetValue, InputPixelType ); /** Set/Get the value of the level set to be located. The default value is * 0. */ itkSetMacro( FarValue, PixelType ); - itkGetMacro( FarValue, PixelType ); + itkGetConstMacro( FarValue, PixelType ); /** Set/Get the narrowbanding flag. By default, narrowbanding is switched * off. */ itkSetMacro( NarrowBanding, bool ); - itkGetMacro( NarrowBanding, bool ); + itkGetConstMacro( NarrowBanding, bool ); itkBooleanMacro( NarrowBanding ); diff --git a/Utilities/ITK/Code/Algorithms/itkIsoContourDistanceImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkIsoContourDistanceImageFilter.txx index fe5a68e85b..4a293fc3d1 100644 --- a/Utilities/ITK/Code/Algorithms/itkIsoContourDistanceImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkIsoContourDistanceImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIsoContourDistanceImageFilter.txx,v $ Language: C++ - Date: $Date: 2007-12-24 17:31:05 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-05 23:09:19 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -325,11 +325,11 @@ IsoContourDistanceImageFilter<TInputImage,TOutputImage> val0_new = val0*val; val1_new = val1*val; - if(fabs((float)val0_new)<fabs((float)outNeigIt.GetNext(n,0))) + if(vcl_fabs((float)val0_new)<vcl_fabs((float)outNeigIt.GetNext(n,0))) { outNeigIt.SetNext(n,0,static_cast<PixelType>(val0_new) ); } - if(fabs((float)val1_new)<fabs((float)outNeigIt.GetNext(n,1))) + if(vcl_fabs((float)val1_new)<vcl_fabs((float)outNeigIt.GetNext(n,1))) { outNeigIt.SetNext(n,1,static_cast<PixelType>(val1_new) ); } @@ -469,11 +469,11 @@ IsoContourDistanceImageFilter<TInputImage,TOutputImage> val0_new = val0*val; val1_new = val1*val; - if(fabs((float)val0_new) < vcl_fabs((float)outNeigIt.GetNext(n,0))) + if(vcl_fabs((float)val0_new) < vcl_fabs((float)outNeigIt.GetNext(n,0))) { outNeigIt.SetNext(n,0,static_cast<PixelType>(val0_new) ); } - if(fabs((float)val1_new) < vcl_fabs((float)outNeigIt.GetNext(n,1))) + if(vcl_fabs((float)val1_new) < vcl_fabs((float)outNeigIt.GetNext(n,1))) { outNeigIt.SetNext(n,1,static_cast<PixelType>(val1_new) ); } diff --git a/Utilities/ITK/Code/Algorithms/itkIsolatedWatershedImageFilter.h b/Utilities/ITK/Code/Algorithms/itkIsolatedWatershedImageFilter.h index 1d68115ff9..c8105689dd 100644 --- a/Utilities/ITK/Code/Algorithms/itkIsolatedWatershedImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkIsolatedWatershedImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIsolatedWatershedImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:57 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,29 +85,29 @@ public: /** Set/Get the Watershed threshold. The default is 0. */ itkSetMacro(Threshold, double); - itkGetMacro(Threshold, double); + itkGetConstMacro(Threshold, double); /** Set/Get the precision required for the intensity threshold * value. The default is .001. */ itkSetMacro(IsolatedValueTolerance, double); - itkGetMacro(IsolatedValueTolerance, double); + itkGetConstMacro(IsolatedValueTolerance, double); /** Set/Get the limit on the upper waterlevel value. The default is * 1.0. */ itkSetMacro(UpperValueLimit, double); - itkGetMacro(UpperValueLimit, double); + itkGetConstMacro(UpperValueLimit, double); /** Set/Get value to replace Seed1(Seed2) pixels, pixels that are * within the basin that contains Seed1(Seed2) this value. The * default is 1(0). */ itkSetMacro(ReplaceValue1, OutputImagePixelType); - itkGetMacro(ReplaceValue1, OutputImagePixelType); + itkGetConstMacro(ReplaceValue1, OutputImagePixelType); itkSetMacro(ReplaceValue2, OutputImagePixelType); - itkGetMacro(ReplaceValue2, OutputImagePixelType); + itkGetConstMacro(ReplaceValue2, OutputImagePixelType); /** Get value that isolates the two seeds. */ - itkGetMacro(IsolatedValue, double); + itkGetConstMacro(IsolatedValue, double); protected: IsolatedWatershedImageFilter(); diff --git a/Utilities/ITK/Code/Algorithms/itkIsotropicFourthOrderLevelSetImageFilter.h b/Utilities/ITK/Code/Algorithms/itkIsotropicFourthOrderLevelSetImageFilter.h index 7024da8f33..13d2d78c85 100644 --- a/Utilities/ITK/Code/Algorithms/itkIsotropicFourthOrderLevelSetImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkIsotropicFourthOrderLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIsotropicFourthOrderLevelSetImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:57 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -98,7 +98,7 @@ public: /** The radius type for the neighborhoods. */ typedef typename FunctionType::RadiusType RadiusType; - itkGetMacro(MaxFilterIteration,unsigned int); + itkGetConstMacro(MaxFilterIteration,unsigned int); itkSetMacro(MaxFilterIteration,unsigned int); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkKappaStatisticImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkKappaStatisticImageToImageMetric.h index 26008c6821..339674c6e7 100755 --- a/Utilities/ITK/Code/Algorithms/itkKappaStatisticImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkKappaStatisticImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKappaStatisticImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:57 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -107,7 +107,7 @@ public: /** This method allows the user to set the foreground value. The default * value is 255. */ itkSetMacro(ForegroundValue, RealType); - itkGetMacro(ForegroundValue, RealType); + itkGetConstMacro(ForegroundValue, RealType); /** Set/Get whether this metric returns 2*|A&B|/(|A|+|B|) @@ -116,7 +116,7 @@ public: * metric values use ComplementOn(). */ itkSetMacro(Complement, bool); itkBooleanMacro(Complement); - itkGetMacro(Complement, bool); + itkGetConstMacro(Complement, bool); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkLevelSetNeighborhoodExtractor.h b/Utilities/ITK/Code/Algorithms/itkLevelSetNeighborhoodExtractor.h index f34f172498..a9498ac51c 100644 --- a/Utilities/ITK/Code/Algorithms/itkLevelSetNeighborhoodExtractor.h +++ b/Utilities/ITK/Code/Algorithms/itkLevelSetNeighborhoodExtractor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLevelSetNeighborhoodExtractor.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:58 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -96,20 +96,20 @@ public: itkSetMacro( LevelSetValue, double ); /** Get the value of the level set to be located. */ - itkGetMacro( LevelSetValue, double ); + itkGetConstMacro( LevelSetValue, double ); /** Set the narrow band width. Default is 12. */ itkSetClampMacro( NarrowBandwidth, double, 0.0, NumericTraits<double>::max()); /** Get the narrow band width. */ - itkGetMacro( NarrowBandwidth, double ); + itkGetConstMacro( NarrowBandwidth, double ); /** Set the narrowbanding flag. */ itkSetMacro( NarrowBanding, bool ); /** Get the narrowbanding flag. */ - itkGetMacro( NarrowBanding, bool ); + itkGetConstMacro( NarrowBanding, bool ); itkBooleanMacro( NarrowBanding ); /** Set/Get the input narrowband. A narrowband is represented as diff --git a/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.h b/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.h index ab7d65dcc5..57ea195e6b 100644 --- a/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMRFImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:51 $ - Version: $Revision: 1.43 $ + Date: $Date: 2009-04-23 03:53:35 $ + Version: $Revision: 1.44 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -241,22 +241,22 @@ public: /** Set/Get the number of classes. */ itkSetMacro(NumberOfClasses, unsigned int); - itkGetMacro(NumberOfClasses, unsigned int); + itkGetConstMacro(NumberOfClasses, unsigned int); /** Set/Get the number of iteration of the Iterated Conditional Mode * (ICM) algorithm. A default value is set at 50 iterations. */ itkSetMacro(MaximumNumberOfIterations, unsigned int); - itkGetMacro(MaximumNumberOfIterations, unsigned int); + itkGetConstMacro(MaximumNumberOfIterations, unsigned int); /** Set/Get the error tollerance level which is used as a threshold * to quit the iterations */ itkSetMacro(ErrorTolerance, double); - itkGetMacro(ErrorTolerance, double); + itkGetConstMacro(ErrorTolerance, double); /** Set/Get the degree of smoothing desired * */ itkSetMacro(SmoothingFactor, double); - itkGetMacro(SmoothingFactor, double); + itkGetConstMacro(SmoothingFactor, double); /** Set the neighborhood radius */ void SetNeighborhoodRadius(const NeighborhoodRadiusType &); diff --git a/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.txx index f6cf7a1bed..458427397d 100644 --- a/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMRFImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:51 $ - Version: $Revision: 1.65 $ + Date: $Date: 2009-05-26 23:45:01 $ + Version: $Revision: 1.67 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -456,8 +456,15 @@ MRFImageFilter<TInputImage, TClassifiedImage> totalNumberOfPixelsInInputImage *= static_cast<int>(inputImageSize[ i ]); } - int maxNumPixelError = (int) ( vnl_math_rnd (m_ErrorTolerance * - m_TotalNumberOfValidPixelsInOutputImage) ); +#ifdef ITK_USE_PORTABLE_ROUND + int maxNumPixelError = + static_cast<int>( Math::Round( m_ErrorTolerance * + m_TotalNumberOfValidPixelsInOutputImage) ); +#else + int maxNumPixelError = + static_cast<int> ( vnl_math_rnd (m_ErrorTolerance * + m_TotalNumberOfValidPixelsInOutputImage) ); +#endif m_NumberOfIterations = 0; do diff --git a/Utilities/ITK/Code/Algorithms/itkMRIBiasFieldCorrectionFilter.h b/Utilities/ITK/Code/Algorithms/itkMRIBiasFieldCorrectionFilter.h index e07f0e8d91..367e8ce7ee 100644 --- a/Utilities/ITK/Code/Algorithms/itkMRIBiasFieldCorrectionFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkMRIBiasFieldCorrectionFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMRIBiasFieldCorrectionFilter.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:51 $ - Version: $Revision: 1.38 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.39 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -360,7 +360,7 @@ public: /** Set/Get the degree of the bias field estimate. */ itkSetMacro( BiasFieldDegree, int ); - itkGetMacro( BiasFieldDegree, int ); + itkGetConstMacro( BiasFieldDegree, int ); /** Sets the initial 3D bias field estimate coefficients that will be * used for correcting each slab. */ @@ -384,9 +384,9 @@ public: /** Set/Get the maximum iteration termination condition parameter. */ itkSetMacro( VolumeCorrectionMaximumIteration, int ); - itkGetMacro( VolumeCorrectionMaximumIteration, int ); + itkGetConstMacro( VolumeCorrectionMaximumIteration, int ); itkSetMacro( InterSliceCorrectionMaximumIteration, int ); - itkGetMacro( InterSliceCorrectionMaximumIteration, int ); + itkGetConstMacro( InterSliceCorrectionMaximumIteration, int ); /** Set/Get the initial search radius. */ void SetOptimizerInitialRadius(double initRadius) @@ -396,12 +396,12 @@ public: /** Set/Get the search radius grow factor. */ itkSetMacro( OptimizerGrowthFactor, double ); - itkGetMacro( OptimizerGrowthFactor, double ); + itkGetConstMacro( OptimizerGrowthFactor, double ); /** Set/Get the search radius shrink factor. */ itkSetMacro( OptimizerShrinkFactor, double ); - itkGetMacro( OptimizerShrinkFactor, double ); + itkGetConstMacro( OptimizerShrinkFactor, double ); /** Set the number of multi-resolution levels. The matrix containing the @@ -413,7 +413,7 @@ public: void SetNumberOfLevels(unsigned int num); /** Get the number of multi-resolution levels. */ - itkGetMacro(NumberOfLevels, unsigned int); + itkGetConstMacro(NumberOfLevels, unsigned int); /** Set a multi-resolution schedule. The input schedule must have only * ImageDimension number of columns and NumberOfLevels number of rows. For diff --git a/Utilities/ITK/Code/Algorithms/itkMatchCardinalityImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkMatchCardinalityImageToImageMetric.h index 3d7e553127..8c558e0919 100644 --- a/Utilities/ITK/Code/Algorithms/itkMatchCardinalityImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkMatchCardinalityImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMatchCardinalityImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:59 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -129,7 +129,7 @@ public: * (MeasureMatchesOn). */ itkSetMacro(MeasureMatches, bool); itkBooleanMacro(MeasureMatches); - itkGetMacro(MeasureMatches, bool); + itkGetConstMacro(MeasureMatches, bool); /** Get/Set the number of threads to create when executing. */ itkSetClampMacro( NumberOfThreads, int, 1, ITK_MAX_THREADS ); diff --git a/Utilities/ITK/Code/Algorithms/itkMatchCardinalityImageToImageMetric.txx b/Utilities/ITK/Code/Algorithms/itkMatchCardinalityImageToImageMetric.txx index bfa76564e5..e3ca8edae7 100644 --- a/Utilities/ITK/Code/Algorithms/itkMatchCardinalityImageToImageMetric.txx +++ b/Utilities/ITK/Code/Algorithms/itkMatchCardinalityImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMatchCardinalityImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:59 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-06 13:46:31 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -237,8 +237,8 @@ MatchCardinalityImageToImageMetric<TFixedImage, TMovingImage> // determine the actual number of pieces that will be generated typename FixedImageRegionType::SizeType::SizeValueType range = fixedRegionSize[splitAxis]; - int valuesPerThread = (int)::ceil(range/(double)num); - int maxThreadIdUsed = (int)::ceil(range/(double)valuesPerThread) - 1; + int valuesPerThread = (int)vcl_ceil(range/(double)num); + int maxThreadIdUsed = (int)vcl_ceil(range/(double)valuesPerThread) - 1; // Split the region if (i < maxThreadIdUsed) diff --git a/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferenceImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferenceImageToImageMetric.h index a4f0a2ef1a..b926165a2c 100755 --- a/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferenceImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferenceImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanReciprocalSquareDifferenceImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:59 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -90,12 +90,12 @@ public: /** Set/Get Lambda value. This factor regulates the capture radius of this metric */ - itkGetMacro( Lambda, double ); + itkGetConstMacro( Lambda, double ); itkSetMacro( Lambda, double ); /** Set/Get Delta value. This value is used as the differential in the * computation of the metric derivative using the finite differences method. */ - itkGetMacro( Delta, double ); + itkGetConstMacro( Delta, double ); itkSetMacro( Delta, double ); diff --git a/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferencePointSetToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferencePointSetToImageMetric.h index a6b4048001..7da3ec8032 100755 --- a/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferencePointSetToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferencePointSetToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanReciprocalSquareDifferencePointSetToImageMetric.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:59 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,7 +95,7 @@ public: /** Set/Get the lambda distance. (controls the capture radius of the metric). */ itkSetMacro( Lambda, double ); - itkGetMacro( Lambda, double ); + itkGetConstMacro( Lambda, double ); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferencePointSetToImageMetric.txx b/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferencePointSetToImageMetric.txx index 15e414f488..da395422fa 100755 --- a/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferencePointSetToImageMetric.txx +++ b/Utilities/ITK/Code/Algorithms/itkMeanReciprocalSquareDifferencePointSetToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanReciprocalSquareDifferencePointSetToImageMetric.txx,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:59 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-06 16:49:21 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -182,7 +182,7 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet,TMovingImage> //Will it be computationally more efficient to instead calculate the //derivative using finite differences ? sum -= jacobian( dim, par ) * - gradient[dim] / (pow( lambdaSquared + diffSquared , 2)); + gradient[dim] / (vcl_pow( lambdaSquared + diffSquared , 2)); } derivative[par] += diff * sum; } diff --git a/Utilities/ITK/Code/Algorithms/itkMeanSquaresHistogramImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkMeanSquaresHistogramImageToImageMetric.h index d10706db6e..d22ebec431 100644 --- a/Utilities/ITK/Code/Algorithms/itkMeanSquaresHistogramImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkMeanSquaresHistogramImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanSquaresHistogramImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:59 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-02 05:43:54 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -66,7 +66,11 @@ public: typedef typename Superclass::MovingImageConstPointer MovingImageConstPointer; typedef typename Superclass::HistogramType HistogramType; +#ifdef ITK_USE_REVIEW_STATISTICS + typedef typename HistogramType::AbsoluteFrequencyType HistogramFrequencyType; +#else typedef typename HistogramType::FrequencyType HistogramFrequencyType; +#endif typedef typename HistogramType::Iterator HistogramIteratorType; typedef typename HistogramType::MeasurementVectorType HistogramMeasurementVectorType; diff --git a/Utilities/ITK/Code/Algorithms/itkMedialNodePairCorrespondenceProcess.h b/Utilities/ITK/Code/Algorithms/itkMedialNodePairCorrespondenceProcess.h index 1cf8e389cf..06aa2bbed5 100644 --- a/Utilities/ITK/Code/Algorithms/itkMedialNodePairCorrespondenceProcess.h +++ b/Utilities/ITK/Code/Algorithms/itkMedialNodePairCorrespondenceProcess.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMedialNodePairCorrespondenceProcess.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:03:00 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -43,7 +43,7 @@ namespace itk * \ingroup */ template< typename TSourceImage > -class MedialNodePairCorrespondenceProcess : public ProcessObject +class ITK_EXPORT MedialNodePairCorrespondenceProcess : public ProcessObject { public: /** Number of dimensions */ diff --git a/Utilities/ITK/Code/Algorithms/itkMedialNodeTripletCorrespondenceProcess.h b/Utilities/ITK/Code/Algorithms/itkMedialNodeTripletCorrespondenceProcess.h index 6cfd450630..1edf9e3781 100644 --- a/Utilities/ITK/Code/Algorithms/itkMedialNodeTripletCorrespondenceProcess.h +++ b/Utilities/ITK/Code/Algorithms/itkMedialNodeTripletCorrespondenceProcess.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMedialNodeTripletCorrespondenceProcess.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:03:00 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-05-12 17:26:20 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,7 +42,7 @@ namespace itk * \ingroup */ template< typename TSourceImage > -class MedialNodeTripletCorrespondenceProcess : public ProcessObject +class ITK_EXPORT MedialNodeTripletCorrespondenceProcess : public ProcessObject { public: diff --git a/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowFunction.txx b/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowFunction.txx index 9ae773e4f3..93aff70780 100644 --- a/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowFunction.txx +++ b/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMinMaxCurvatureFlowFunction.txx,v $ Language: C++ - Date: $Date: 2009-01-24 20:03:00 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-05-26 23:45:03 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -285,14 +285,26 @@ MinMaxCurvatureFlowFunction<TImage> // Compute first perpendicular point +#ifdef ITK_USE_PORTABLE_ROUND + position[0] = Math::Round( (double)(m_StencilRadius - gradient[1]) ); + position[1] = Math::Round( (double)(m_StencilRadius + gradient[0]) ); +#else position[0] = vnl_math_rnd( (double)(m_StencilRadius - gradient[1]) ); position[1] = vnl_math_rnd( (double)(m_StencilRadius + gradient[0]) ); +#endif + threshold = it.GetPixel( position[0] + stride * position[1] ); // Compute second perpendicular point +#ifdef ITK_USE_PORTABLE_ROUND + position[0] = Math::Round( (double)(m_StencilRadius + gradient[1]) ); + position[1] = Math::Round( (double)(m_StencilRadius - gradient[0]) ); +#else position[0] = vnl_math_rnd( (double)(m_StencilRadius + gradient[1]) ); position[1] = vnl_math_rnd( (double)(m_StencilRadius - gradient[0]) ); +#endif + threshold += it.GetPixel( position[0] + stride * position[1] ); threshold *= 0.5; @@ -391,32 +403,54 @@ MinMaxCurvatureFlowFunction<TImage> double rCosPhi = m_StencilRadius * cosPhi; // Point 1: angle = 0; +#ifdef ITK_USE_PORTABLE_ROUND + position[0] = Math::Round( m_StencilRadius + rCosThetaCosPhi ); + position[1] = Math::Round( m_StencilRadius + rCosThetaSinPhi ); + position[2] = Math::Round( m_StencilRadius - rSinTheta ); +#else position[0] = vnl_math_rnd( m_StencilRadius + rCosThetaCosPhi ); position[1] = vnl_math_rnd( m_StencilRadius + rCosThetaSinPhi ); position[2] = vnl_math_rnd( m_StencilRadius - rSinTheta ); +#endif threshold += it.GetPixel( position[0] + strideY * position[1] + strideZ * position[2] ); // Point 2: angle = 90; +#ifdef ITK_USE_PORTABLE_ROUND + position[0] = Math::Round( m_StencilRadius - rSinPhi ); + position[1] = Math::Round( m_StencilRadius + rCosPhi ); +#else position[0] = vnl_math_rnd( m_StencilRadius - rSinPhi ); position[1] = vnl_math_rnd( m_StencilRadius + rCosPhi ); +#endif position[2] = m_StencilRadius; threshold += it.GetPixel( position[0] + strideY * position[1] + strideZ * position[2] ); // Point 3: angle = 180; +#ifdef ITK_USE_PORTABLE_ROUND + position[0] = Math::Round( m_StencilRadius - rCosThetaCosPhi ); + position[1] = Math::Round( m_StencilRadius - rCosThetaSinPhi ); + position[2] = Math::Round( m_StencilRadius + rSinTheta ); +#else position[0] = vnl_math_rnd( m_StencilRadius - rCosThetaCosPhi ); position[1] = vnl_math_rnd( m_StencilRadius - rCosThetaSinPhi ); position[2] = vnl_math_rnd( m_StencilRadius + rSinTheta ); +#endif threshold += it.GetPixel( position[0] + strideY * position[1] + strideZ * position[2] ); // Point 4: angle = 270; +#ifdef ITK_USE_PORTABLE_ROUND + position[0] = Math::Round( m_StencilRadius + rSinPhi ); + position[1] = Math::Round( m_StencilRadius - rCosPhi ); +#else position[0] = vnl_math_rnd( m_StencilRadius + rSinPhi ); position[1] = vnl_math_rnd( m_StencilRadius - rCosPhi ); +#endif position[2] = m_StencilRadius; threshold += it.GetPixel( position[0] + diff --git a/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowImageFilter.h b/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowImageFilter.h index 395a5fc6ad..e89db8e42e 100644 --- a/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMinMaxCurvatureFlowImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:03:00 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -110,7 +110,7 @@ public: /** Set/Get the stencil radius. */ itkSetMacro( StencilRadius, RadiusValueType ); - itkGetMacro( StencilRadius, RadiusValueType ); + itkGetConstMacro( StencilRadius, RadiusValueType ); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Algorithms/itkMultiResolutionImageRegistrationMethod.h b/Utilities/ITK/Code/Algorithms/itkMultiResolutionImageRegistrationMethod.h index 6eded3cbef..9bb4182966 100644 --- a/Utilities/ITK/Code/Algorithms/itkMultiResolutionImageRegistrationMethod.h +++ b/Utilities/ITK/Code/Algorithms/itkMultiResolutionImageRegistrationMethod.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiResolutionImageRegistrationMethod.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:51 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -186,10 +186,10 @@ public: /** Set/Get the number of multi-resolution levels. */ void SetNumberOfLevels( unsigned long numberOfLevels ); - itkGetMacro( NumberOfLevels, unsigned long ); + itkGetConstMacro( NumberOfLevels, unsigned long ); /** Get the current resolution level being processed. */ - itkGetMacro( CurrentLevel, unsigned long ); + itkGetConstMacro( CurrentLevel, unsigned long ); /** Set/Get the initial transformation parameters. */ itkSetMacro( InitialTransformParameters, ParametersType ); diff --git a/Utilities/ITK/Code/Algorithms/itkMultiResolutionImageRegistrationMethod.txx b/Utilities/ITK/Code/Algorithms/itkMultiResolutionImageRegistrationMethod.txx index e3b91c08c7..5d89d05980 100644 --- a/Utilities/ITK/Code/Algorithms/itkMultiResolutionImageRegistrationMethod.txx +++ b/Utilities/ITK/Code/Algorithms/itkMultiResolutionImageRegistrationMethod.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiResolutionImageRegistrationMethod.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:51 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-05-07 02:15:57 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -254,10 +254,10 @@ MultiResolutionImageRegistrationMethod<TFixedImage,TMovingImage> typedef typename FixedImageRegionType::IndexType IndexType; ScheduleType schedule = m_FixedImagePyramid->GetSchedule(); - std::cout << "FixedImage schedule: " << schedule << std::endl; + itkDebugMacro ( << "FixedImage schedule: " << schedule ); ScheduleType movingschedule = m_MovingImagePyramid->GetSchedule(); - std::cout << "MovingImage schedule: " << movingschedule << std::endl; + itkDebugMacro ( << "MovingImage schedule: " << movingschedule ); SizeType inputSize = m_FixedImageRegion.GetSize(); IndexType inputStart = m_FixedImageRegion.GetIndex(); diff --git a/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.h b/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.h index b137568874..f458353e0d 100644 --- a/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiResolutionPyramidImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-07 21:41:29 $ - Version: $Revision: 1.20 $ + Date: $Date: 2009-05-08 16:34:59 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -87,6 +87,10 @@ namespace itk * using a DiscreteGaussianImageFilter with variance (shrink factor / 2)^2. * The smoothed image is then downsampled using a ResampleImageFilter. * + * Note that even if the shrink factors are all equal to one, a smoothing + * will still be applied. The output at the finest level of the pyramid + * will thus typically be a smoothed version of the input. + * * This class is templated over the input image type and the output image * type. * @@ -142,10 +146,10 @@ public: * 2^(nlevel - 1) for all dimension. These shrink factors are halved for * subsequent levels. The number of levels is clamped to a minimum value * of 1. All shrink factors are also clamped to a minimum value of 1. */ - void SetNumberOfLevels(unsigned int num); + virtual void SetNumberOfLevels(unsigned int num); /** Get the number of multi-resolution levels. */ - itkGetMacro(NumberOfLevels, unsigned int); + itkGetConstMacro(NumberOfLevels, unsigned int); /** Set a multi-resolution schedule. The input schedule must have only * ImageDimension number of columns and NumberOfLevels number of rows. For @@ -153,7 +157,7 @@ public: * subsequent levels. This function will clamp shrink factors to satisify * this condition. All shrink factors less than one will also be clamped * to the value of 1. */ - void SetSchedule( const ScheduleType& schedule ); + virtual void SetSchedule( const ScheduleType& schedule ); /** Get the multi-resolution schedule. */ itkGetConstReferenceMacro(Schedule, ScheduleType); @@ -162,8 +166,8 @@ public: * level. The schedule is then populated with defaults values obtained by * halving the factors at the previous level. All shrink factors are * clamped to a minimum value of 1. */ - void SetStartingShrinkFactors( unsigned int factor ); - void SetStartingShrinkFactors( unsigned int* factors ); + virtual void SetStartingShrinkFactors( unsigned int factor ); + virtual void SetStartingShrinkFactors( unsigned int* factors ); /** Get the starting shrink factors */ const unsigned int * GetStartingShrinkFactors() const; @@ -198,6 +202,11 @@ public: itkSetMacro(MaximumError,double); itkGetConstReferenceMacro(MaximumError,double); + itkSetMacro(UseShrinkImageFilter,bool); + itkGetConstMacro(UseShrinkImageFilter,bool); + itkBooleanMacro(UseShrinkImageFilter); + + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(SameDimensionCheck, @@ -206,6 +215,7 @@ public: (Concept::HasNumericTraits<typename TOutputImage::PixelType>)); /** End concept checking */ #endif + protected: MultiResolutionPyramidImageFilter(); ~MultiResolutionPyramidImageFilter() {}; @@ -217,6 +227,7 @@ protected: double m_MaximumError; unsigned int m_NumberOfLevels; ScheduleType m_Schedule; + bool m_UseShrinkImageFilter; private: MultiResolutionPyramidImageFilter(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.txx index 7bba3da2f8..16f4e812b6 100644 --- a/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiResolutionPyramidImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:51 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-04-07 13:14:19 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,6 +23,7 @@ #include "itkDiscreteGaussianImageFilter.h" #include "itkExceptionObject.h" #include "itkResampleImageFilter.h" +#include "itkShrinkImageFilter.h" #include "itkIdentityTransform.h" #include "vnl/vnl_math.h" @@ -40,6 +41,7 @@ MultiResolutionPyramidImageFilter<TInputImage, TOutputImage> m_NumberOfLevels = 0; this->SetNumberOfLevels( 2 ); m_MaximumError = 0.1; + m_UseShrinkImageFilter = false; } @@ -265,26 +267,49 @@ MultiResolutionPyramidImageFilter<TInputImage, TOutputImage> // Create caster, smoother and resampleShrinker filters typedef CastImageFilter<TInputImage, TOutputImage> CasterType; typedef DiscreteGaussianImageFilter<TOutputImage, TOutputImage> SmootherType; + + typedef ImageToImageFilter<TOutputImage,TOutputImage> ImageToImageType; typedef ResampleImageFilter<TOutputImage,TOutputImage> ResampleShrinkerType; + typedef ShrinkImageFilter<TOutputImage,TOutputImage> ShrinkerType; typename CasterType::Pointer caster = CasterType::New(); typename SmootherType::Pointer smoother = SmootherType::New(); - typename ResampleShrinkerType::Pointer resampleShrinker = ResampleShrinkerType::New(); + typename ImageToImageType::Pointer shrinkerFilter; + // + // only one of these pointers is going to be valid, depending on the + // value of UseShrinkImageFilter flag + typename ResampleShrinkerType::Pointer resampleShrinker; + typename ShrinkerType::Pointer shrinker; + + if(this->GetUseShrinkImageFilter()) + { + shrinker = ShrinkerType::New(); + shrinkerFilter = shrinker.GetPointer(); + } + else + { + resampleShrinker = ResampleShrinkerType::New(); + typedef itk::LinearInterpolateImageFunction< OutputImageType, double > + LinearInterpolatorType; + typename LinearInterpolatorType::Pointer interpolator = + LinearInterpolatorType::New(); + resampleShrinker->SetInterpolator( interpolator ); + resampleShrinker->SetDefaultPixelValue( 0 ); + shrinkerFilter = resampleShrinker.GetPointer(); + } // Setup the filters caster->SetInput( inputPtr ); - smoother->SetUseImageSpacing( true ); + smoother->SetUseImageSpacing( false ); smoother->SetInput( caster->GetOutput() ); smoother->SetMaximumError( m_MaximumError ); - resampleShrinker->SetInput( smoother->GetOutput() ); + shrinkerFilter->SetInput( smoother->GetOutput() ); unsigned int ilevel, idim; unsigned int factors[ImageDimension]; double variance[ImageDimension]; - typedef itk::LinearInterpolateImageFunction< OutputImageType, double > LinearInterpolatorType; - typename LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New(); for( ilevel = 0; ilevel < m_NumberOfLevels; ilevel++ ) { @@ -296,8 +321,6 @@ MultiResolutionPyramidImageFilter<TInputImage, TOutputImage> outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() ); outputPtr->Allocate(); - typedef itk::IdentityTransform<double,OutputImageType::ImageDimension> IdentityTransformType; - typename IdentityTransformType::Pointer identityTransform=IdentityTransformType::New(); // compute shrink factors and variances for( idim = 0; idim < ImageDimension; idim++ ) { @@ -306,19 +329,28 @@ MultiResolutionPyramidImageFilter<TInputImage, TOutputImage> static_cast<float>( factors[idim] ) ); } + if(!this->GetUseShrinkImageFilter()) + { + typedef itk::IdentityTransform<double,OutputImageType::ImageDimension> + IdentityTransformType; + typename IdentityTransformType::Pointer identityTransform = + IdentityTransformType::New(); + resampleShrinker->SetOutputParametersFromImage( outputPtr ); + resampleShrinker->SetTransform(identityTransform); + } + else + { + shrinker->SetShrinkFactors(factors); + } // use mini-pipeline to compute output smoother->SetVariance( variance ); - resampleShrinker->SetInterpolator( interpolator ); - resampleShrinker->SetDefaultPixelValue( 0 ); - resampleShrinker->SetOutputParametersFromImage( outputPtr ); - resampleShrinker->SetTransform(identityTransform); - resampleShrinker->GraftOutput( outputPtr ); + shrinkerFilter->GraftOutput( outputPtr ); // force to always update in case shrink factors are the same - resampleShrinker->Modified(); - resampleShrinker->UpdateLargestPossibleRegion(); - this->GraftNthOutput( ilevel, resampleShrinker->GetOutput() ); + shrinkerFilter->Modified(); + shrinkerFilter->UpdateLargestPossibleRegion(); + this->GraftNthOutput( ilevel, shrinkerFilter->GetOutput() ); } } @@ -336,6 +368,7 @@ MultiResolutionPyramidImageFilter<TInputImage, TOutputImage> os << indent << "No. levels: " << m_NumberOfLevels << std::endl; os << indent << "Schedule: " << std::endl; os << m_Schedule << std::endl; + os << "Use ShrinkImageFilter= " << m_UseShrinkImageFilter << std::endl; } diff --git a/Utilities/ITK/Code/Algorithms/itkMutualInformationHistogramImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkMutualInformationHistogramImageToImageMetric.h index d8056a9cb6..59401822bf 100644 --- a/Utilities/ITK/Code/Algorithms/itkMutualInformationHistogramImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkMutualInformationHistogramImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMutualInformationHistogramImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:51 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -67,7 +67,11 @@ public: MovingImageConstPointer; typedef typename Superclass::HistogramType HistogramType; +#ifdef ITK_USE_REVIEW_STATISTICS + typedef typename HistogramType::AbsoluteFrequencyType HistogramFrequencyType; +#else typedef typename HistogramType::FrequencyType HistogramFrequencyType; +#endif typedef typename HistogramType::Iterator HistogramIteratorType; typedef typename HistogramType::MeasurementVectorType HistogramMeasurementVectorType; diff --git a/Utilities/ITK/Code/Algorithms/itkMutualInformationHistogramImageToImageMetric.txx b/Utilities/ITK/Code/Algorithms/itkMutualInformationHistogramImageToImageMetric.txx index e69353267c..20488b27fe 100644 --- a/Utilities/ITK/Code/Algorithms/itkMutualInformationHistogramImageToImageMetric.txx +++ b/Utilities/ITK/Code/Algorithms/itkMutualInformationHistogramImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMutualInformationHistogramImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:52 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-05-04 18:13:52 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,11 +30,16 @@ MutualInformationHistogramImageToImageMetric<TFixedImage,TMovingImage> MeasureType entropyX = NumericTraits<MeasureType>::Zero; MeasureType entropyY = NumericTraits<MeasureType>::Zero; MeasureType jointEntropy = NumericTraits<MeasureType>::Zero; - HistogramFrequencyType totalFreq = histogram.GetTotalFrequency(); + + typedef typename NumericTraits< HistogramFrequencyType >::RealType HistogramFrequencyRealType; + + HistogramFrequencyRealType totalFreq = + static_cast< HistogramFrequencyRealType >( histogram.GetTotalFrequency() ); for (unsigned int i = 0; i < this->GetHistogramSize()[0]; i++) { - HistogramFrequencyType freq = histogram.GetFrequency(i, 0); + HistogramFrequencyRealType freq = + static_cast< HistogramFrequencyRealType >( histogram.GetFrequency(i, 0) ); if (freq > 0) { entropyX += freq*vcl_log(freq); @@ -45,7 +50,8 @@ MutualInformationHistogramImageToImageMetric<TFixedImage,TMovingImage> for (unsigned int i = 0; i < this->GetHistogramSize()[1]; i++) { - HistogramFrequencyType freq = histogram.GetFrequency(i, 1); + HistogramFrequencyRealType freq = + static_cast< HistogramFrequencyRealType >( histogram.GetFrequency(i, 1) ); if (freq > 0) { entropyY += freq*vcl_log(freq); @@ -58,7 +64,8 @@ MutualInformationHistogramImageToImageMetric<TFixedImage,TMovingImage> HistogramIteratorType end = histogram.End(); while (it != end) { - HistogramFrequencyType freq = it.GetFrequency(); + HistogramFrequencyRealType freq = + static_cast< HistogramFrequencyRealType >( it.GetFrequency() ); if (freq > 0) { jointEntropy += freq*vcl_log(freq); diff --git a/Utilities/ITK/Code/Algorithms/itkMutualInformationImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkMutualInformationImageToImageMetric.h index d3fa925c05..0586ae9251 100644 --- a/Utilities/ITK/Code/Algorithms/itkMutualInformationImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkMutualInformationImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMutualInformationImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:52 $ - Version: $Revision: 1.44 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.45 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -165,7 +165,7 @@ public: * Value is clamped to be always greater than zero. */ itkSetClampMacro( FixedImageStandardDeviation, double, NumericTraits<double>::NonpositiveMin(), NumericTraits<double>::max() ); - itkGetMacro( FixedImageStandardDeviation, double ); + itkGetConstMacro( FixedImageStandardDeviation, double ); /** Set/Get the kernel function. This is used to calculate the joint * probability distribution. Default is the GaussianKernelFunction. */ diff --git a/Utilities/ITK/Code/Algorithms/itkNormalizedMutualInformationHistogramImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkNormalizedMutualInformationHistogramImageToImageMetric.h index f9fd84f917..a9a096a9f5 100644 --- a/Utilities/ITK/Code/Algorithms/itkNormalizedMutualInformationHistogramImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkNormalizedMutualInformationHistogramImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNormalizedMutualInformationHistogramImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:54 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,7 +81,11 @@ public: MovingImageConstPointer; typedef typename Superclass::HistogramType HistogramType; +#ifdef ITK_USE_REVIEW_STATISTICS + typedef typename HistogramType::AbsoluteFrequencyType HistogramFrequencyType; +#else typedef typename HistogramType::FrequencyType HistogramFrequencyType; +#endif typedef typename HistogramType::Iterator HistogramIteratorType; typedef typename HistogramType::MeasurementVectorType HistogramMeasurementVectorType; diff --git a/Utilities/ITK/Code/Algorithms/itkNormalizedMutualInformationHistogramImageToImageMetric.txx b/Utilities/ITK/Code/Algorithms/itkNormalizedMutualInformationHistogramImageToImageMetric.txx index 542f54d917..e315966e24 100644 --- a/Utilities/ITK/Code/Algorithms/itkNormalizedMutualInformationHistogramImageToImageMetric.txx +++ b/Utilities/ITK/Code/Algorithms/itkNormalizedMutualInformationHistogramImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNormalizedMutualInformationHistogramImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:54 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-04 18:13:52 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,11 +32,17 @@ NormalizedMutualInformationHistogramImageToImageMetric<TFixedImage, \ MeasureType entropyX = NumericTraits<MeasureType>::Zero; MeasureType entropyY = NumericTraits<MeasureType>::Zero; MeasureType jointEntropy = NumericTraits<MeasureType>::Zero; - HistogramFrequencyType totalFreq = histogram.GetTotalFrequency(); + + typedef typename NumericTraits< HistogramFrequencyType >::RealType HistogramFrequencyRealType; + + HistogramFrequencyRealType totalFreq = + static_cast< HistogramFrequencyRealType >( histogram.GetTotalFrequency() ); for (unsigned int i = 0; i < this->GetHistogramSize()[0]; i++) { - HistogramFrequencyType freq = histogram.GetFrequency(i, 0); + HistogramFrequencyRealType freq = + static_cast< HistogramFrequencyRealType >( histogram.GetFrequency(i, 0) ); + if (freq > 0) { entropyX += freq*vcl_log(freq); @@ -47,7 +53,9 @@ NormalizedMutualInformationHistogramImageToImageMetric<TFixedImage, \ for (unsigned int i = 0; i < this->GetHistogramSize()[1]; i++) { - HistogramFrequencyType freq = histogram.GetFrequency(i, 1); + HistogramFrequencyRealType freq = + static_cast< HistogramFrequencyRealType >( histogram.GetFrequency(i, 1) ); + if (freq > 0) { entropyY += freq*vcl_log(freq); @@ -60,7 +68,9 @@ NormalizedMutualInformationHistogramImageToImageMetric<TFixedImage, \ HistogramIteratorType end = histogram.End(); while (it != end) { - HistogramFrequencyType freq = it.GetFrequency(); + HistogramFrequencyRealType freq = + static_cast< HistogramFrequencyRealType >( it.GetFrequency() ); + if (freq > 0) { jointEntropy += freq*vcl_log(freq); diff --git a/Utilities/ITK/Code/Algorithms/itkOtsuMultipleThresholdsCalculator.h b/Utilities/ITK/Code/Algorithms/itkOtsuMultipleThresholdsCalculator.h index 4dacb4ef29..0cc41ae75d 100755 --- a/Utilities/ITK/Code/Algorithms/itkOtsuMultipleThresholdsCalculator.h +++ b/Utilities/ITK/Code/Algorithms/itkOtsuMultipleThresholdsCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOtsuMultipleThresholdsCalculator.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:54 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-12 17:26:21 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,7 +37,7 @@ namespace itk */ template< class TInputHistogram > -class OtsuMultipleThresholdsCalculator : +class ITK_EXPORT OtsuMultipleThresholdsCalculator : public HistogramAlgorithmBase< TInputHistogram > { public: @@ -48,7 +48,12 @@ public: typedef SmartPointer<const Self> ConstPointer; typedef typename TInputHistogram::MeasurementType MeasurementType; + +#ifdef ITK_USE_REVIEW_STATISTICS + typedef typename TInputHistogram::AbsoluteFrequencyType FrequencyType; +#else typedef typename TInputHistogram::FrequencyType FrequencyType; +#endif typedef typename NumericTraits<MeasurementType>::RealType MeanType; typedef typename NumericTraits<MeasurementType>::RealType VarianceType; @@ -71,7 +76,7 @@ public: /** Set/Get the number of thresholds. */ itkSetClampMacro(NumberOfThresholds, unsigned long, 1, NumericTraits<unsigned long>::max() ); - itkGetMacro(NumberOfThresholds,unsigned long); + itkGetConstMacro(NumberOfThresholds,unsigned long); protected: OtsuMultipleThresholdsCalculator(); diff --git a/Utilities/ITK/Code/Algorithms/itkOtsuMultipleThresholdsCalculator.txx b/Utilities/ITK/Code/Algorithms/itkOtsuMultipleThresholdsCalculator.txx index 9c4d899680..f33e3e5929 100755 --- a/Utilities/ITK/Code/Algorithms/itkOtsuMultipleThresholdsCalculator.txx +++ b/Utilities/ITK/Code/Algorithms/itkOtsuMultipleThresholdsCalculator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOtsuMultipleThresholdsCalculator.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:54 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -147,7 +147,11 @@ OtsuMultipleThresholdsCalculator<TInputHistogram> // TODO: as an improvement, the class could accept multi-dimensional histograms // and the user could specify the dimension to apply the algorithm to. +#ifdef ITK_USE_REVIEW_STATISTICS + if (histogram->GetSize().Size() != 1) +#else if (histogram->GetSize().GetSizeDimension() != 1) +#endif { itkExceptionMacro(<<"Histogram must be 1-dimensional."); } diff --git a/Utilities/ITK/Code/Algorithms/itkOtsuThresholdImageCalculator.h b/Utilities/ITK/Code/Algorithms/itkOtsuThresholdImageCalculator.h index 16173963e4..68ea599efc 100644 --- a/Utilities/ITK/Code/Algorithms/itkOtsuThresholdImageCalculator.h +++ b/Utilities/ITK/Code/Algorithms/itkOtsuThresholdImageCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOtsuThresholdImageCalculator.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:54 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -77,12 +77,12 @@ public: void Compute(void); /** Return the Otsu's threshold value. */ - itkGetMacro(Threshold,PixelType); + itkGetConstMacro(Threshold,PixelType); /** Set/Get the number of histogram bins. Default is 128. */ itkSetClampMacro( NumberOfHistogramBins, unsigned long, 1, NumericTraits<unsigned long>::max() ); - itkGetMacro( NumberOfHistogramBins, unsigned long ); + itkGetConstMacro( NumberOfHistogramBins, unsigned long ); /** Set the region over which the values will be computed */ void SetRegion( const RegionType & region ); diff --git a/Utilities/ITK/Code/Algorithms/itkOtsuThresholdImageFilter.h b/Utilities/ITK/Code/Algorithms/itkOtsuThresholdImageFilter.h index 5dc462709b..f46c379691 100644 --- a/Utilities/ITK/Code/Algorithms/itkOtsuThresholdImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkOtsuThresholdImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOtsuThresholdImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:54 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -82,22 +82,22 @@ public: itkSetMacro(OutsideValue,OutputPixelType); /** Get the "outside" pixel value. */ - itkGetMacro(OutsideValue,OutputPixelType); + itkGetConstMacro(OutsideValue,OutputPixelType); /** Set the "inside" pixel value. The default value * NumericTraits<OutputPixelType>::max() */ itkSetMacro(InsideValue,OutputPixelType); /** Get the "inside" pixel value. */ - itkGetMacro(InsideValue,OutputPixelType); + itkGetConstMacro(InsideValue,OutputPixelType); /** Set/Get the number of histogram bins. Defaults is 128. */ itkSetClampMacro( NumberOfHistogramBins, unsigned long, 1, NumericTraits<unsigned long>::max() ); - itkGetMacro( NumberOfHistogramBins, unsigned long ); + itkGetConstMacro( NumberOfHistogramBins, unsigned long ); /** Get the computed threshold. */ - itkGetMacro(Threshold,InputPixelType); + itkGetConstMacro(Threshold,InputPixelType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Algorithms/itkPDEDeformableRegistrationFilter.h b/Utilities/ITK/Code/Algorithms/itkPDEDeformableRegistrationFilter.h index 4591242217..50999fef17 100644 --- a/Utilities/ITK/Code/Algorithms/itkPDEDeformableRegistrationFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkPDEDeformableRegistrationFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPDEDeformableRegistrationFilter.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:56 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -148,7 +148,7 @@ public: * deformation field is smoothed with a Gaussian whose standard * deviations are specified with SetStandardDeviations() */ itkSetMacro( SmoothDeformationField, bool ); - itkGetMacro( SmoothDeformationField, bool ); + itkGetConstMacro( SmoothDeformationField, bool ); itkBooleanMacro( SmoothDeformationField ); /** Set the Gaussian smoothing standard deviations for the @@ -168,7 +168,7 @@ public: * update field is smoothed with a Gaussian whose standard * deviations are specified with SetUpdateFieldStandardDeviations() */ itkSetMacro( SmoothUpdateField, bool ); - itkGetMacro( SmoothUpdateField, bool ); + itkGetConstMacro( SmoothUpdateField, bool ); itkBooleanMacro( SmoothUpdateField ); /** Set the Gaussian smoothing standard deviations for the update @@ -190,12 +190,12 @@ public: /** Set/Get the desired maximum error of the Guassian kernel approximate. * \sa GaussianOperator. */ itkSetMacro( MaximumError, double ); - itkGetMacro( MaximumError, double ); + itkGetConstMacro( MaximumError, double ); /** Set/Get the desired limits of the Gaussian kernel width. * \sa GaussianOperator. */ itkSetMacro( MaximumKernelWidth, unsigned int ); - itkGetMacro( MaximumKernelWidth, unsigned int ); + itkGetConstMacro( MaximumKernelWidth, unsigned int ); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.h b/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.h index 905de5a52d..df7db77b46 100644 --- a/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBGibbsPriorFilter.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:56 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-04-23 03:53:36 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -115,7 +115,7 @@ public: itkSetMacro(NumberOfClasses, unsigned int); /** Get the Number of classes. */ - itkGetMacro(NumberOfClasses, unsigned int); + itkGetConstMacro(NumberOfClasses, unsigned int); /** Set/Get the number of iteration of the Iterated Conditional Mode * (ICM) algorithm. A default value is set at 50 iterations. */ @@ -123,7 +123,7 @@ public: /** Get the number of iterations of the Iterated Conditional Mode * (ICM) algorithm. */ - itkGetMacro(MaximumNumberOfIterations, unsigned int); + itkGetConstMacro(MaximumNumberOfIterations, unsigned int); /** Set the threshold for the object size. */ itkSetMacro(ClusterSize, unsigned int); @@ -143,17 +143,17 @@ public: /** set and get the value for Clique weights */ itkSetMacro(CliqueWeight_1, double); - itkGetMacro(CliqueWeight_1, double); + itkGetConstMacro(CliqueWeight_1, double); itkSetMacro(CliqueWeight_2, double); - itkGetMacro(CliqueWeight_2, double); + itkGetConstMacro(CliqueWeight_2, double); itkSetMacro(CliqueWeight_3, double); - itkGetMacro(CliqueWeight_3, double); + itkGetConstMacro(CliqueWeight_3, double); itkSetMacro(CliqueWeight_4, double); - itkGetMacro(CliqueWeight_4, double); + itkGetConstMacro(CliqueWeight_4, double); itkSetMacro(CliqueWeight_5, double); - itkGetMacro(CliqueWeight_5, double); + itkGetConstMacro(CliqueWeight_5, double); itkSetMacro(CliqueWeight_6, double); - itkGetMacro(CliqueWeight_6, double); + itkGetConstMacro(CliqueWeight_6, double); /** Specify the type of matrix to use. */ diff --git a/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.txx b/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.txx index a499739c9c..8563566ba9 100644 --- a/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBGibbsPriorFilter.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:56 $ - Version: $Revision: 1.48 $ + Date: $Date: 2009-04-06 11:15:07 $ + Version: $Revision: 1.49 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -354,7 +354,7 @@ RGBGibbsPriorFilter<TInputImage, TClassifiedImage> { difenergy = energy[label]-energy[1-label]; double rand_num = (double) (rand()/32768.0); - double energy_num = (double) (exp((double) (difenergy*0.5*size/(2*size-m_Temp)))); + double energy_num = (double) (vcl_exp((double) (difenergy*0.5*size/(2*size-m_Temp)))); if ( rand_num < energy_num ) { m_LabelledImage->SetPixel(offsetIndex3D, 1-label); diff --git a/Utilities/ITK/Code/Algorithms/itkRayCastInterpolateImageFunction.h b/Utilities/ITK/Code/Algorithms/itkRayCastInterpolateImageFunction.h index aafafe3c2a..9e8aa93df7 100644 --- a/Utilities/ITK/Code/Algorithms/itkRayCastInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Algorithms/itkRayCastInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRayCastInterpolateImageFunction.h,v $ Language: C++ -Date: $Date: 2008-05-13 15:32:36 $ -Version: $Revision: 1.16 $ +Date: $Date: 2009-04-23 03:53:36 $ +Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -141,12 +141,12 @@ public: /** Connect the Interpolator. */ itkSetMacro( FocalPoint, InputPointType ); /** Get a pointer to the Interpolator. */ - itkGetMacro( FocalPoint, InputPointType ); + itkGetConstMacro( FocalPoint, InputPointType ); /** Connect the Transform. */ itkSetMacro( Threshold, double ); /** Get a pointer to the Transform. */ - itkGetMacro( Threshold, double ); + itkGetConstMacro( Threshold, double ); /** Check if a point is inside the image buffer. * \warning For efficiency, no validity checking of diff --git a/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.h b/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.h index d09c5042fd..779c551ffa 100644 --- a/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRecursiveMultiResolutionPyramidImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:56 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-03-05 17:09:59 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,6 +38,11 @@ namespace itk * * See documentation of MultiResolutionPyramidImageFilter * for information on how to specify a multi-resolution schedule. + * + * Note that unlike the MultiResolutionPyramidImageFilter, + * RecursiveMultiResolutionPyramidImageFilter will not smooth the output at + * the finest level if the shrink factors are all one and the schedule + * is downward divisible. * * This class is templated over the input image type and the output image type. * diff --git a/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.txx index 85e7632544..dffa835c57 100644 --- a/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRecursiveMultiResolutionPyramidImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:57 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-10 19:14:50 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,11 +18,13 @@ #define __itkRecursiveMultiResolutionPyramidImageFilter_txx #include "itkRecursiveMultiResolutionPyramidImageFilter.h" -#include "itkShrinkImageFilter.h" #include "itkGaussianOperator.h" #include "itkCastImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkExceptionObject.h" +#include "itkResampleImageFilter.h" +#include "itkShrinkImageFilter.h" +#include "itkIdentityTransform.h" #include "vnl/vnl_math.h" @@ -36,6 +38,7 @@ template <class TInputImage, class TOutputImage> RecursiveMultiResolutionPyramidImageFilter<TInputImage, TOutputImage> ::RecursiveMultiResolutionPyramidImageFilter() { + this->Superclass::m_UseShrinkImageFilter = true; } /** @@ -57,21 +60,54 @@ RecursiveMultiResolutionPyramidImageFilter<TInputImage, TOutputImage> // Get the input and output pointers InputImageConstPointer inputPtr = this->GetInput(); - // Create caster, smoother and shrinker filters + // Create caster, smoother and resampleShrink filters typedef CastImageFilter<TInputImage, TOutputImage> CasterType; typedef CastImageFilter<TOutputImage, TOutputImage> CopierType; typedef DiscreteGaussianImageFilter<TOutputImage, TOutputImage> SmootherType; + + typedef ImageToImageFilter<TOutputImage,TOutputImage> ImageToImageType; + typedef ResampleImageFilter<TOutputImage,TOutputImage> ResampleShrinkerType; typedef ShrinkImageFilter<TOutputImage,TOutputImage> ShrinkerType; typename CasterType::Pointer caster = CasterType::New(); typename CopierType::Pointer copier = CopierType::New(); typename SmootherType::Pointer smoother = SmootherType::New(); - typename ShrinkerType::Pointer shrinker = ShrinkerType::New(); + + + typename ImageToImageType::Pointer shrinkerFilter; + // + // only one of these pointers is going to be valid, depending on the + // value of UseShrinkImageFilter flag + typename ResampleShrinkerType::Pointer resampleShrinker; + typename ShrinkerType::Pointer shrinker; + + if(this->GetUseShrinkImageFilter()) + { + shrinker = ShrinkerType::New(); + shrinkerFilter = shrinker.GetPointer(); + } + else + { + resampleShrinker = ResampleShrinkerType::New(); + typedef itk::LinearInterpolateImageFunction< OutputImageType, double > + LinearInterpolatorType; + typename LinearInterpolatorType::Pointer interpolator = + LinearInterpolatorType::New(); + typedef itk::IdentityTransform<double,OutputImageType::ImageDimension> + IdentityTransformType; + typename IdentityTransformType::Pointer identityTransform = + IdentityTransformType::New(); + resampleShrinker->SetInterpolator( interpolator ); + resampleShrinker->SetDefaultPixelValue( 0 ); + resampleShrinker->SetTransform(identityTransform); + shrinkerFilter = resampleShrinker.GetPointer(); + } int ilevel; unsigned int idim; unsigned int factors[ImageDimension]; double variance[ImageDimension]; + bool allOnes; OutputImagePointer outputPtr; OutputImagePointer swapPtr; @@ -79,7 +115,7 @@ RecursiveMultiResolutionPyramidImageFilter<TInputImage, TOutputImage> smoother->SetUseImageSpacing( false ); smoother->SetMaximumError( this->GetMaximumError() ); - shrinker->SetInput( smoother->GetOutput() ); + shrinkerFilter->SetInput( smoother->GetOutput() ); // recursively compute outputs starting from the last one @@ -93,7 +129,7 @@ RecursiveMultiResolutionPyramidImageFilter<TInputImage, TOutputImage> outputPtr = this->GetOutput( ilevel ); outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() ); outputPtr->Allocate(); - + // cached a copy of the largest possible region LPRegion = outputPtr->GetLargestPossibleRegion(); @@ -168,15 +204,25 @@ RecursiveMultiResolutionPyramidImageFilter<TInputImage, TOutputImage> smoother->SetVariance( variance ); - shrinker->SetShrinkFactors( factors ); - shrinker->GraftOutput( outputPtr ); + // shrinker->SetShrinkFactors( factors ); + // shrinker->GraftOutput( outputPtr ); + if(!this->GetUseShrinkImageFilter()) + { + resampleShrinker->SetOutputParametersFromImage(outputPtr); + } + else + { + shrinker->SetShrinkFactors(factors); + } + shrinkerFilter->GraftOutput(outputPtr); + shrinkerFilter->Modified(); // ensure only the requested region is updated - shrinker->GetOutput()->UpdateOutputInformation(); - shrinker->GetOutput()->SetRequestedRegion(outputPtr->GetRequestedRegion()); - shrinker->GetOutput()->PropagateRequestedRegion(); - shrinker->GetOutput()->UpdateOutputData(); + shrinkerFilter->GetOutput()->UpdateOutputInformation(); + shrinkerFilter->GetOutput()->SetRequestedRegion(outputPtr->GetRequestedRegion()); + shrinkerFilter->GetOutput()->PropagateRequestedRegion(); + shrinkerFilter->GetOutput()->UpdateOutputData(); - swapPtr = shrinker->GetOutput(); + swapPtr = shrinkerFilter->GetOutput(); } diff --git a/Utilities/ITK/Code/Algorithms/itkRegularSphereMeshSource.h b/Utilities/ITK/Code/Algorithms/itkRegularSphereMeshSource.h index dc6131516d..33a5348b3a 100644 --- a/Utilities/ITK/Code/Algorithms/itkRegularSphereMeshSource.h +++ b/Utilities/ITK/Code/Algorithms/itkRegularSphereMeshSource.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegularSphereMeshSource.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:57 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-05-12 17:26:21 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,7 +37,7 @@ namespace itk * */ template <class TOutputMesh> -class RegularSphereMeshSource : public MeshSource<TOutputMesh> +class ITK_EXPORT RegularSphereMeshSource : public MeshSource<TOutputMesh> { public: /** Standard "Self" typedef. */ @@ -78,17 +78,17 @@ public: /** Set the resolution level to be used for generating cells in the Sphere. * High values of this parameter will produce sphere with more triangles. */ itkSetMacro(Resolution, unsigned int); - itkGetMacro(Resolution, unsigned int); + itkGetConstMacro(Resolution, unsigned int); /** Set/Get Coordinates of the Sphere center. */ itkSetMacro( Center, PointType ); - itkGetMacro( Center, PointType ); + itkGetConstMacro( Center, PointType ); /** Set/Get scales of the Sphere. This is a vector of values that can * actually be used for generating ellipsoids aligned with the coordinate * axis. */ itkSetMacro( Scale, VectorType ); - itkGetMacro( Scale, VectorType ); + itkGetConstMacro( Scale, VectorType ); protected: RegularSphereMeshSource(); diff --git a/Utilities/ITK/Code/Algorithms/itkRegularSphereMeshSource.txx b/Utilities/ITK/Code/Algorithms/itkRegularSphereMeshSource.txx index b0db1166bc..2e7d2d51b9 100644 --- a/Utilities/ITK/Code/Algorithms/itkRegularSphereMeshSource.txx +++ b/Utilities/ITK/Code/Algorithms/itkRegularSphereMeshSource.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegularSphereMeshSource.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:57 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-08 23:03:40 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -137,9 +137,9 @@ RegularSphereMeshSource<TOutputMesh> v_pt[1] = &v[1]; v_pt[2] = &v[2]; const unsigned long *tp; - unsigned long pointIdx,cellIdx=0; + unsigned long cellIdx=0; unsigned long pointIdxOffset = outputMesh->GetNumberOfPoints(); - pointIdx = pointIdxOffset; + unsigned long pointIdx = pointIdxOffset; unsigned long newIdx[3] = {0,1,2}; // container for the processed edges diff --git a/Utilities/ITK/Code/Algorithms/itkReinitializeLevelSetImageFilter.h b/Utilities/ITK/Code/Algorithms/itkReinitializeLevelSetImageFilter.h index 04a2db20b7..a9ccefc74f 100644 --- a/Utilities/ITK/Code/Algorithms/itkReinitializeLevelSetImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkReinitializeLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkReinitializeLevelSetImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:57 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,23 +85,23 @@ public: /** Set/Get the value of the level set to be located. The default value is * 0. */ itkSetMacro( LevelSetValue, double ); - itkGetMacro( LevelSetValue, double ); + itkGetConstMacro( LevelSetValue, double ); /** Set/Get the narrowbanding flag. By default, narrowbanding is switched * off. */ itkSetMacro( NarrowBanding, bool ); - itkGetMacro( NarrowBanding, bool ); + itkGetConstMacro( NarrowBanding, bool ); itkBooleanMacro( NarrowBanding ); /** Set/Get the input narrow bandwidth. The default value is 12. */ itkSetClampMacro( InputNarrowBandwidth, double, 0.0, NumericTraits<double>::max()); - itkGetMacro( InputNarrowBandwidth, double ); + itkGetConstMacro( InputNarrowBandwidth, double ); /** Set/Get the output narrow bandwidth. The default value is 12. */ itkSetClampMacro( OutputNarrowBandwidth, double, 0.0, NumericTraits<double>::max()); - itkGetMacro( OutputNarrowBandwidth, double ); + itkGetConstMacro( OutputNarrowBandwidth, double ); /** Set the bandwidth for both the input and output narrowband, * By default, both the input and output are set to 12. */ diff --git a/Utilities/ITK/Code/Algorithms/itkReinitializeLevelSetImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkReinitializeLevelSetImageFilter.txx index 68ac345b0b..78c1e890f1 100644 --- a/Utilities/ITK/Code/Algorithms/itkReinitializeLevelSetImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkReinitializeLevelSetImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkReinitializeLevelSetImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:57 $ - Version: $Revision: 1.20 $ + Date: $Date: 2009-03-31 19:41:49 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -150,7 +150,9 @@ ReinitializeLevelSetImageFilter<TLevelSet> // set the marcher output size m_Marcher->SetOutputSize( outputPtr->GetRequestedRegion().GetSize() ); - + this->m_Marcher->SetOutputOrigin(this->GetInput()->GetOrigin()); + this->m_Marcher->SetOutputSpacing(this->GetInput()->GetSpacing()); + this->m_Marcher->SetOutputDirection(this->GetInput()->GetDirection()); } diff --git a/Utilities/ITK/Code/Algorithms/itkSTAPLEImageFilter.h b/Utilities/ITK/Code/Algorithms/itkSTAPLEImageFilter.h index 6621a7d713..74bc11d9fd 100644 --- a/Utilities/ITK/Code/Algorithms/itkSTAPLEImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkSTAPLEImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSTAPLEImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:15 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -154,7 +154,7 @@ public: /** Set get the binary ON value of the input image. */ itkSetMacro(ForegroundValue, InputPixelType); - itkGetMacro(ForegroundValue, InputPixelType); + itkGetConstMacro(ForegroundValue, InputPixelType); /** After the filter is updated, this method returns a std::vector<double> of * all Specificity (true negative fraction, q) values for the expert @@ -198,7 +198,7 @@ public: * will be considered to have converged. In general this SHOULD NOT be set and * the algorithm should be allowed to converge on its own. */ itkSetMacro(MaximumIterations, unsigned int); - itkGetMacro(MaximumIterations, unsigned int); + itkGetConstMacro(MaximumIterations, unsigned int); /** Scales the estimated prior probability that a pixel will be inside the * targeted object of segmentation. The default prior probability g_t is @@ -208,10 +208,10 @@ public: * ConfidenceWeight. In general, ConfidenceWeight should be left to the * default of 1.0. */ itkSetMacro(ConfidenceWeight, double); - itkGetMacro(ConfidenceWeight, double); + itkGetConstMacro(ConfidenceWeight, double); /** Get the number of elapsed iterations of the iterative E-M algorithm. */ - itkGetMacro(ElapsedIterations, unsigned int); + itkGetConstMacro(ElapsedIterations, unsigned int); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Algorithms/itkScalarImageKmeansImageFilter.h b/Utilities/ITK/Code/Algorithms/itkScalarImageKmeansImageFilter.h index 11edd8b10d..abdd20926a 100644 --- a/Utilities/ITK/Code/Algorithms/itkScalarImageKmeansImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkScalarImageKmeansImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageKmeansImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:57 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,11 +25,18 @@ #include "itkKdTreeBasedKmeansEstimator.h" #include "itkWeightedCentroidKdTreeGenerator.h" +#ifdef ITK_USE_REVIEW_STATISTICS +#include "itkEuclideanDistanceMetric.h" +#include "itkSampleClassifierFilter.h" +#include "itkImageToListSampleAdaptor.h" +#include "itkMinimumDecisionRule2.h" +#else #include "itkMinimumDecisionRule.h" #include "itkEuclideanDistance.h" #include "itkSampleClassifier.h" - #include "itkScalarImageToListAdaptor.h" +#endif + #include "itkImageRegion.h" #include "itkRegionOfInterestImageFilter.h" @@ -93,12 +100,41 @@ public: typedef typename NumericTraits< InputPixelType >::RealType RealPixelType; /** Create a List from the scalar image */ +#ifdef ITK_USE_REVIEW_STATISTICS + typedef itk::Statistics::ImageToListSampleAdaptor< InputImageType > AdaptorType; +#else typedef itk::Statistics::ScalarImageToListAdaptor< InputImageType > AdaptorType; - +#endif + /** Define the Measurement vector type from the AdaptorType */ typedef typename AdaptorType::MeasurementVectorType MeasurementVectorType; +#ifdef ITK_USE_REVIEW_STATISTICS + typedef itk::Statistics::DistanceToCentroidMembershipFunction< MeasurementVectorType > MembershipFunctionType; + typedef itk::Statistics::SampleClassifierFilter< AdaptorType > ClassifierType; + typedef itk::Statistics::MinimumDecisionRule2 DecisionRuleType; +#else + typedef itk::Statistics::EuclideanDistance< MeasurementVectorType > MembershipFunctionType; + typedef itk::Statistics::SampleClassifier< AdaptorType > ClassifierType; + typedef itk::MinimumDecisionRule DecisionRuleType; +#endif + +#ifdef ITK_USE_REVIEW_STATISTICS + typedef typename ClassifierType::ClassLabelVectorType ClassLabelVectorType; +#else + typedef std::vector< unsigned int > ClassLabelVectorType; +#endif + +#ifdef ITK_USE_REVIEW_STATISTICS + typedef typename ClassifierType::MembershipFunctionVectorType MembershipFunctionVectorType; + typedef typename MembershipFunctionType::CentroidType MembershipFunctionOriginType; +#else + typedef typename MembershipFunctionType::OriginType MembershipFunctionOriginType; +#endif + + typedef typename MembershipFunctionType::Pointer MembershipFunctionPointer; + /** Create the K-d tree structure */ typedef itk::Statistics::WeightedCentroidKdTreeGenerator< AdaptorType > diff --git a/Utilities/ITK/Code/Algorithms/itkScalarImageKmeansImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkScalarImageKmeansImageFilter.txx index a9c1b41544..56fb2bbaf3 100644 --- a/Utilities/ITK/Code/Algorithms/itkScalarImageKmeansImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkScalarImageKmeansImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageKmeansImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-01-26 21:45:57 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -16,9 +16,14 @@ =========================================================================*/ #ifndef __itkScalarImageKmeansImageFilter_txx #define __itkScalarImageKmeansImageFilter_txx + #include "itkScalarImageKmeansImageFilter.h" #include "itkImageRegionExclusionIteratorWithIndex.h" +#ifdef ITK_USE_REVIEW_STATISTICS +#include "itkDistanceToCentroidMembershipFunction.h" +#endif + #include "itkProgressReporter.h" namespace itk @@ -97,21 +102,21 @@ ScalarImageKmeansImageFilter< TInputImage > // Now classify the samples // - typedef itk::Statistics::EuclideanDistance< MeasurementVectorType > - MembershipFunctionType; - typedef itk::MinimumDecisionRule DecisionRuleType; DecisionRuleType::Pointer decisionRule = DecisionRuleType::New(); - - typedef itk::Statistics::SampleClassifier< AdaptorType > ClassifierType; typename ClassifierType::Pointer classifier = ClassifierType::New(); classifier->SetDecisionRule( decisionRule.GetPointer() ); +#ifdef ITK_USE_REVIEW_STATISTICS + classifier->SetInput( adaptor ); +#else classifier->SetSample( adaptor ); +#endif classifier->SetNumberOfClasses( numberOfClasses ); - std::vector< unsigned int > classLabels; + + ClassLabelVectorType classLabels; classLabels.resize( numberOfClasses ); // Spread the labels over the intensity range @@ -123,8 +128,10 @@ ScalarImageKmeansImageFilter< TInputImage > unsigned int label = 0; - typedef typename MembershipFunctionType::Pointer MembershipFunctionPointer; - typedef typename MembershipFunctionType::OriginType MembershipFunctionOriginType; + +#ifdef ITK_USE_REVIEW_STATISTICS + MembershipFunctionVectorType membershipFunctions; +#endif for(unsigned int k=0; k<numberOfClasses; k++) { @@ -133,11 +140,29 @@ ScalarImageKmeansImageFilter< TInputImage > MembershipFunctionPointer membershipFunction = MembershipFunctionType::New(); MembershipFunctionOriginType origin( adaptor->GetMeasurementVectorSize() ); origin[0] = this->m_FinalMeans[k]; // A scalar image has a MeasurementVector of dimension 1 +#ifdef ITK_USE_REVIEW_STATISTICS + membershipFunction->SetCentroid( origin ); + const MembershipFunctionType *constMembershipFunction = membershipFunction; + membershipFunctions.push_back( constMembershipFunction ); +#else membershipFunction->SetOrigin( origin ); classifier->AddMembershipFunction( membershipFunction.GetPointer() ); +#endif } +#ifdef ITK_USE_REVIEW_STATISTICS + typename ClassifierType::MembershipFunctionVectorObjectPointer membershipFunctionsObject = + ClassifierType::MembershipFunctionVectorObjectType::New(); + membershipFunctionsObject->Set(membershipFunctions); + classifier->SetMembershipFunctions(membershipFunctionsObject); + + typedef typename ClassifierType::ClassLabelVectorObjectType ClassLabelVectorObjectType; + typename ClassLabelVectorObjectType::Pointer classLabelsObject = ClassLabelVectorObjectType::New(); + classLabelsObject->Set(classLabels); + classifier->SetClassLabels( classLabelsObject ); +#else classifier->SetMembershipFunctionClassLabels( classLabels ); +#endif // Execute the actual classification @@ -163,9 +188,13 @@ ScalarImageKmeansImageFilter< TInputImage > ImageIterator pixel( outputPtr, region ); pixel.GoToBegin(); +#ifdef ITK_USE_REVIEW_STATISTICS + typedef typename ClassifierType::MembershipSampleType ClassifierOutputType; +#else typedef typename ClassifierType::OutputType ClassifierOutputType; +#endif - ClassifierOutputType * membershipSample = classifier->GetOutput(); + const ClassifierOutputType * membershipSample = classifier->GetOutput(); typedef typename ClassifierOutputType::ConstIterator LabelIterator; diff --git a/Utilities/ITK/Code/Algorithms/itkSegmentationLevelSetImageFilter.h b/Utilities/ITK/Code/Algorithms/itkSegmentationLevelSetImageFilter.h index 8faa430cf0..9fe9f9ee03 100644 --- a/Utilities/ITK/Code/Algorithms/itkSegmentationLevelSetImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkSegmentationLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSegmentationLevelSetImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:15 $ - Version: $Revision: 1.35 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.36 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -289,7 +289,7 @@ public: * expansion/contraction as appropriate to a particular application or data * set. */ itkSetMacro(ReverseExpansionDirection, bool); - itkGetMacro(ReverseExpansionDirection, bool); + itkGetConstMacro(ReverseExpansionDirection, bool); itkBooleanMacro(ReverseExpansionDirection); /** Turn On/Off automatic generation of Speed and Advection terms when Update @@ -298,7 +298,7 @@ public: GenerateSpeedImage() and GenerateAdvectionImage() should be called prior to updating the filter. */ itkSetMacro(AutoGenerateSpeedAdvection, bool); - itkGetMacro(AutoGenerateSpeedAdvection, bool); + itkGetConstMacro(AutoGenerateSpeedAdvection, bool); itkBooleanMacro(AutoGenerateSpeedAdvection); /** Combined scaling of the propagation and advection speed diff --git a/Utilities/ITK/Code/Algorithms/itkShapePriorMAPCostFunction.h b/Utilities/ITK/Code/Algorithms/itkShapePriorMAPCostFunction.h index b14326b813..339c56d180 100644 --- a/Utilities/ITK/Code/Algorithms/itkShapePriorMAPCostFunction.h +++ b/Utilities/ITK/Code/Algorithms/itkShapePriorMAPCostFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShapePriorMAPCostFunction.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:15 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -94,11 +94,11 @@ public: /** Set/Get the array of shape parameters mean. */ itkSetMacro( ShapeParameterMeans, ArrayType ); - itkGetMacro( ShapeParameterMeans, ArrayType ); + itkGetConstMacro( ShapeParameterMeans, ArrayType ); /** Set/Get the array of shape parameters standard deviation. */ itkSetMacro( ShapeParameterStandardDeviations, ArrayType ); - itkGetMacro( ShapeParameterStandardDeviations, ArrayType ); + itkGetConstMacro( ShapeParameterStandardDeviations, ArrayType ); /** Set/Get the weights for each term. Default is a vector of all ones. * The weights are applied to terms in the following order: diff --git a/Utilities/ITK/Code/Algorithms/itkShapePriorSegmentationLevelSetImageFilter.h b/Utilities/ITK/Code/Algorithms/itkShapePriorSegmentationLevelSetImageFilter.h index be72d76e27..f8337bf7f3 100644 --- a/Utilities/ITK/Code/Algorithms/itkShapePriorSegmentationLevelSetImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkShapePriorSegmentationLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShapePriorSegmentationLevelSetImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:16 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -137,7 +137,7 @@ public: * the particular type of ShapeSignedDistanceFunction used to determine * the meaning of the parameters. */ itkSetMacro( InitialParameters, ParametersType ); - itkGetMacro( InitialParameters, ParametersType ); + itkGetConstMacro( InitialParameters, ParametersType ); /** Set/Get the scaling of the shape prior term. */ void SetShapePriorScaling( ValueType v ) diff --git a/Utilities/ITK/Code/Algorithms/itkSimplexMeshVolumeCalculator.h b/Utilities/ITK/Code/Algorithms/itkSimplexMeshVolumeCalculator.h index 6504dc5a9e..0533a00897 100755 --- a/Utilities/ITK/Code/Algorithms/itkSimplexMeshVolumeCalculator.h +++ b/Utilities/ITK/Code/Algorithms/itkSimplexMeshVolumeCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshVolumeCalculator.h,v $ Language: C++ -Date: $Date: 2007-04-10 15:45:19 $ -Version: $Revision: 1.4 $ +Date: $Date: 2009-04-23 03:53:37 $ +Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -170,10 +170,10 @@ public: void Compute(void); /** Return the computed volume. */ - itkGetMacro(Volume, double); + itkGetConstMacro(Volume, double); /** Return the computed area. */ - itkGetMacro(Area, double); + itkGetConstMacro(Area, double); protected: SimplexMeshVolumeCalculator(); diff --git a/Utilities/ITK/Code/Algorithms/itkSphereMeshSource.txx b/Utilities/ITK/Code/Algorithms/itkSphereMeshSource.txx index d26c1f3a67..9de13849a8 100644 --- a/Utilities/ITK/Code/Algorithms/itkSphereMeshSource.txx +++ b/Utilities/ITK/Code/Algorithms/itkSphereMeshSource.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSphereMeshSource.txx,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:16 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-06 16:49:23 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -89,7 +89,7 @@ SphereMeshSource<TOutputMesh> { for (v=vbeg, j=0; j < m_ResolutionY; v += vstep, j++) { - if (cos(u) > 0) + if (vcl_cos(u) > 0) { signu = 1; } @@ -97,7 +97,7 @@ SphereMeshSource<TOutputMesh> { signu = -1; } - if (cos(v) > 0) + if (vcl_cos(v) > 0) { signv = 1; } @@ -106,10 +106,10 @@ SphereMeshSource<TOutputMesh> signv = -1; } - p1[0] = m_Scale[0]*signu*(pow((float)(fabs(cos(u))), (float) m_Squareness1))*signv* - (pow((float)(fabs(cos(v))), (float) m_Squareness2)) + m_Center[0]; + p1[0] = m_Scale[0]*signu*(vcl_pow((float)(vcl_fabs(vcl_cos(u))), (float) m_Squareness1))*signv* + (vcl_pow((float)(vcl_fabs(vcl_cos(v))), (float) m_Squareness2)) + m_Center[0]; - if (sin(v) > 0) + if (vcl_sin(v) > 0) { signv = 1; } @@ -118,10 +118,10 @@ SphereMeshSource<TOutputMesh> signv = -1; } - p1[1] = m_Scale[1]*signu*(pow((float)(fabs(cos(u))), (float) m_Squareness1))*signv* - (pow((float)(fabs(sin(v))), (float) m_Squareness2)) + m_Center[1]; + p1[1] = m_Scale[1]*signu*(vcl_pow((float)(vcl_fabs(vcl_cos(u))), (float) m_Squareness1))*signv* + (vcl_pow((float)(vcl_fabs(vcl_sin(v))), (float) m_Squareness2)) + m_Center[1]; - if (sin(u) > 0) + if (vcl_sin(u) > 0) { signu = 1; } @@ -130,7 +130,7 @@ SphereMeshSource<TOutputMesh> signu = -1; } - p1[2] = m_Scale[2]*signu*(pow((float)(fabs(sin(u))), (float) m_Squareness1)) + + p1[2] = m_Scale[2]*signu*(vcl_pow((float)(vcl_fabs(vcl_sin(u))), (float) m_Squareness1)) + m_Center[2]; point.Value() = p1; @@ -139,21 +139,21 @@ SphereMeshSource<TOutputMesh> } // calculate the south pole node - p1[0] = (m_Scale[0]*(pow((float)(fabs(cos(-vnl_math::pi/2))),1.0f))* - (pow((float)(fabs(cos(0.0))),1.0f)) + m_Center[0]); - p1[1] = (m_Scale[1]*(pow((float)(fabs(cos(-vnl_math::pi/2))),1.0f))* - (pow((float)(fabs(sin(0.0))),1.0f)) + m_Center[1]); - p1[2] = (m_Scale[2]*-1*(pow((float)(fabs(sin(-vnl_math::pi/2))),1.0f)) + p1[0] = (m_Scale[0]*(vcl_pow((float)(vcl_fabs(vcl_cos(-vnl_math::pi/2))),1.0f))* + (vcl_pow((float)(vcl_fabs(vcl_cos(0.0))),1.0f)) + m_Center[0]); + p1[1] = (m_Scale[1]*(vcl_pow((float)(vcl_fabs(vcl_cos(-vnl_math::pi/2))),1.0f))* + (vcl_pow((float)(vcl_fabs(vcl_sin(0.0))),1.0f)) + m_Center[1]); + p1[2] = (m_Scale[2]*-1*(vcl_pow((float)(vcl_fabs(vcl_sin(-vnl_math::pi/2))),1.0f)) + m_Center[2]); point.Value() = p1; ++point; // calculate the north pole node - p1[0] = (m_Scale[0]*(pow((float)(fabs(cos(vnl_math::pi/2))),1.0f))* - (pow(fabs(cos(0.0)),1.0)) + m_Center[0]); - p1[1] = (m_Scale[1]*(pow((float)(fabs(cos(vnl_math::pi/2))),1.0f))* - (pow(fabs(sin(0.0)),1.0)) + m_Center[1]); - p1[2] = (m_Scale[2]*(pow((float)(fabs(sin(vnl_math::pi/2))),1.0f)) + p1[0] = (m_Scale[0]*(vcl_pow((float)(vcl_fabs(vcl_cos(vnl_math::pi/2))),1.0f))* + (vcl_pow(vcl_fabs(vcl_cos(0.0)),1.0)) + m_Center[0]); + p1[1] = (m_Scale[1]*(vcl_pow((float)(vcl_fabs(vcl_cos(vnl_math::pi/2))),1.0f))* + (vcl_pow(vcl_fabs(vcl_sin(0.0)),1.0)) + m_Center[1]); + p1[2] = (m_Scale[2]*(vcl_pow((float)(vcl_fabs(vcl_sin(vnl_math::pi/2))),1.0f)) + m_Center[2]); point.Value() = p1; ++point; diff --git a/Utilities/ITK/Code/Algorithms/itkStructHashFunction.h b/Utilities/ITK/Code/Algorithms/itkStructHashFunction.h index 397281c260..c247d40af1 100644 --- a/Utilities/ITK/Code/Algorithms/itkStructHashFunction.h +++ b/Utilities/ITK/Code/Algorithms/itkStructHashFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkStructHashFunction.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:16 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-05-12 17:26:21 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -33,7 +33,7 @@ namespace itk * general classes. */ template< class TInput > -class StructHashFunction +class ITK_EXPORT StructHashFunction { public: diff --git a/Utilities/ITK/Code/Algorithms/itkThresholdMaximumConnectedComponentsImageFilter.h b/Utilities/ITK/Code/Algorithms/itkThresholdMaximumConnectedComponentsImageFilter.h index c0007bbce6..93d82aaec7 100644 --- a/Utilities/ITK/Code/Algorithms/itkThresholdMaximumConnectedComponentsImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkThresholdMaximumConnectedComponentsImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkThresholdMaximumConnectedComponentsImageFilter.h,v $ Language: C++ - Date: $Date: 2007-04-27 19:05:39 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -103,7 +103,7 @@ public: * noise from being counted as an object. The default value is * zero. */ itkSetMacro( MinimumObjectSizeInPixels, unsigned int ); - itkGetMacro( MinimumObjectSizeInPixels, unsigned int ); + itkGetConstMacro( MinimumObjectSizeInPixels, unsigned int ); /** * The following Set/Get methods are for the binary threshold @@ -121,20 +121,20 @@ public: itkSetMacro( InsideValue, PixelType ); itkSetMacro( OutsideValue, PixelType ); itkSetMacro( UpperBoundary, PixelType ); - itkGetMacro( InsideValue, PixelType ); - itkGetMacro( OutsideValue, PixelType ); - itkGetMacro( UpperBoundary, PixelType ); + itkGetConstMacro( InsideValue, PixelType ); + itkGetConstMacro( OutsideValue, PixelType ); + itkGetConstMacro( UpperBoundary, PixelType ); /** * Returns the number of objects in the image. This information is * only valid after the filter has executed. Useful if your counting * something */ - itkGetMacro( NumberOfObjects, unsigned long ); + itkGetConstMacro( NumberOfObjects, unsigned long ); /** * Returns the automatic threshold setpoint. This information is * only valid after the filter has executed. */ - itkGetMacro( ThresholdValue, PixelType ); + itkGetConstMacro( ThresholdValue, PixelType ); /** Some additional typedefs. */ typedef TInputImage InputImageType; diff --git a/Utilities/ITK/Code/Algorithms/itkUnaryMedialNodeMetric.h b/Utilities/ITK/Code/Algorithms/itkUnaryMedialNodeMetric.h index 4dab411947..0b61b61b26 100644 --- a/Utilities/ITK/Code/Algorithms/itkUnaryMedialNodeMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkUnaryMedialNodeMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkUnaryMedialNodeMetric.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:16 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-05-12 17:26:21 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -45,7 +45,7 @@ namespace itk */ template<int VDimensions = 3> -class UnaryMedialNodeMetric : public LightObject +class ITK_EXPORT UnaryMedialNodeMetric : public LightObject { public: diff --git a/Utilities/ITK/Code/Algorithms/itkUnsharpMaskLevelSetImageFilter.h b/Utilities/ITK/Code/Algorithms/itkUnsharpMaskLevelSetImageFilter.h index fc8099e8ce..1011401a51 100644 --- a/Utilities/ITK/Code/Algorithms/itkUnsharpMaskLevelSetImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkUnsharpMaskLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkUnsharpMaskLevelSetImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:16 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -91,7 +91,7 @@ public: /** The radius type for the neighborhoods. */ typedef typename FunctionType::RadiusType RadiusType; - itkGetMacro(MaxFilterIteration,unsigned int); + itkGetConstMacro(MaxFilterIteration,unsigned int); itkSetMacro(MaxFilterIteration,unsigned int); protected: diff --git a/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2D.h b/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2D.h index 0ae8cb8028..98041d30b7 100644 --- a/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2D.h +++ b/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2D.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVoronoiDiagram2D.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:16 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -140,7 +140,7 @@ public: typedef typename std::vector<PointType>::iterator VertexIterator; /** Get the number of Voronoi seeds. */ - itkGetMacro(NumberOfSeeds,unsigned int); + itkGetConstMacro(NumberOfSeeds,unsigned int); /** Input the seeds information, will overwrite if seeds already * exists. */ diff --git a/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2DGenerator.h b/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2DGenerator.h index e8f5ef2bfb..c3ceec0375 100644 --- a/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2DGenerator.h +++ b/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2DGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVoronoiDiagram2DGenerator.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:16 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -77,7 +77,7 @@ public: typedef typename VDMesh::VoronoiEdge VoronoiEdge; /** Get the number of seed points. */ - itkGetMacro(NumberOfSeeds,unsigned int); + itkGetConstMacro(NumberOfSeeds,unsigned int); /** Input the seeds information, will overwrite if seeds already * exists. */ diff --git a/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2DGenerator.txx b/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2DGenerator.txx index 924f11e494..84cb27478c 100644 --- a/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2DGenerator.txx +++ b/Utilities/ITK/Code/Algorithms/itkVoronoiDiagram2DGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVoronoiDiagram2DGenerator.txx,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:17 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -591,7 +591,7 @@ dist(FortuneSite *s1,FortuneSite *s2) { double dx = (s1->m_Coord[0])-(s2->m_Coord[0]); double dy = (s1->m_Coord[1])-(s2->m_Coord[1]); - return(sqrt(dx*dx+dy*dy)); + return(vcl_sqrt(dx*dx+dy*dy)); } template <typename TCoordRepType> diff --git a/Utilities/ITK/Code/Algorithms/itkVoronoiPartitioningImageFilter.h b/Utilities/ITK/Code/Algorithms/itkVoronoiPartitioningImageFilter.h index 177d12b224..ba5303aadc 100644 --- a/Utilities/ITK/Code/Algorithms/itkVoronoiPartitioningImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkVoronoiPartitioningImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVoronoiPartitioningImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:17 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -75,7 +75,7 @@ public: * Voronoi region is below this threshold, then the region is * considered homogeneous. */ itkSetMacro(SigmaThreshold, double); - itkGetMacro(SigmaThreshold, double); + itkGetConstMacro(SigmaThreshold, double); /** ImageDimension enumeration */ itkStaticConstMacro(InputImageDimension, unsigned int, diff --git a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilter.h b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilter.h index 3abf28bbf7..e8f5fbe5e8 100644 --- a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVoronoiSegmentationImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:17 $ - Version: $Revision: 1.34 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.35 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -79,29 +79,29 @@ public: /** Set/Get the Estimation of the mean pixel value for the object. */ itkSetMacro(Mean, double); - itkGetMacro(Mean, double); + itkGetConstMacro(Mean, double); /** Set/Get the estimation of the STD of the pixel value for the * object. */ itkSetMacro(STD, double); - itkGetMacro(STD, double); + itkGetConstMacro(STD, double); /** Set/Get the Tolearance of Mean for classifying the regions. */ itkSetMacro(MeanTolerance, double); - itkGetMacro(MeanTolerance, double); + itkGetConstMacro(MeanTolerance, double); /** Set the Tolearance of STD for classifying the regions. */ itkSetMacro(STDTolerance, double); /** Get the Tolearance of Variance for classifying the regions. */ - itkGetMacro(STDTolerance, double); + itkGetConstMacro(STDTolerance, double); /** Set/Get the mean percent error. */ void SetMeanPercentError(double x); - itkGetMacro(MeanPercentError, double); + itkGetConstMacro(MeanPercentError, double); /** Set/Get the STD percent error. */ - itkGetMacro(STDPercentError, double); + itkGetConstMacro(STDPercentError, double); void SetSTDPercentError(double x); /** Take a prior from other segmentation node, should be an diff --git a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.h b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.h index c3ee31aaa7..cdddf9511d 100644 --- a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.h +++ b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVoronoiSegmentationImageFilterBase.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:17 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -112,44 +112,44 @@ public: /** Set/Get the initial number of seeds for VD. */ itkSetMacro(NumberOfSeeds, int); - itkGetMacro(NumberOfSeeds, int); + itkGetConstMacro(NumberOfSeeds, int); /** Set/Get the smallest region to be divided. */ itkSetMacro(MinRegion, int); - itkGetMacro(MinRegion, int); + itkGetConstMacro(MinRegion, int); /** Set/Get the number of iterations to run (if set to 0: the classification * run process runs until no more cells can be divided). */ itkSetMacro(Steps, int); - itkGetMacro(Steps, int); + itkGetConstMacro(Steps, int); /** Get the number of seeds before adding new ones. */ - itkGetMacro(LastStepSeeds, int); + itkGetConstMacro(LastStepSeeds, int); /** Get the number of seeds to add. */ - itkGetMacro(NumberOfSeedsToAdded, int); + itkGetConstMacro(NumberOfSeedsToAdded, int); /** */ itkSetMacro(UseBackgroundInAPrior, bool); - itkGetMacro(UseBackgroundInAPrior, bool); + itkGetConstMacro(UseBackgroundInAPrior, bool); /** Enable the generation of the output boundary. */ itkSetMacro(OutputBoundary, bool); - itkGetMacro(OutputBoundary, bool); + itkGetConstMacro(OutputBoundary, bool); /** Output the segmentation on every iteration. Useful for iteractive sessions. The setting of OutputBoundary determines the type of output. */ itkSetMacro(InteractiveSegmentation, bool); - itkGetMacro(InteractiveSegmentation, bool); + itkGetConstMacro(InteractiveSegmentation, bool); itkBooleanMacro(InteractiveSegmentation); /** Set/Get the mean deviation. */ itkSetMacro(MeanDeviation, double); - itkGetMacro(MeanDeviation, double); + itkGetConstMacro(MeanDeviation, double); /** Set/Get the region size. */ itkSetMacro(Size,SizeType); - itkGetMacro(Size,SizeType); + itkGetConstMacro(Size,SizeType); /** Take a prior from other segmentation node. This should be a * binary object. */ diff --git a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.txx b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.txx index 3f9ac595eb..63f6ac2ea8 100644 --- a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.txx +++ b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVoronoiSegmentationImageFilterBase.txx,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:17 $ - Version: $Revision: 1.34 $ + Date: $Date: 2009-04-06 13:46:34 $ + Version: $Revision: 1.35 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -190,7 +190,7 @@ VoronoiSegmentationImageFilterBase <TInputImage,TOutputImage,TBinaryPriorImage> { beginx=leftP[0]; } - for(i=static_cast<int>(ceil(beginx));i<=static_cast<int>(floor(endx));i++) + for(i=static_cast<int>(vcl_ceil(beginx));i<=static_cast<int>(vcl_floor(endx));i++) { idx[0]=i; (*PixelPool).push_back(idx); @@ -204,7 +204,7 @@ VoronoiSegmentationImageFilterBase <TInputImage,TOutputImage,TBinaryPriorImage> beginx += offset * leftDx; while(idx[1] <= intendy) { - for(i=static_cast<int>(ceil(beginx)); i <= static_cast<int>(floor(endx)); i++) + for(i=static_cast<int>(vcl_ceil(beginx)); i <= static_cast<int>(vcl_floor(endx)); i++) { idx[0] = i; (*PixelPool).push_back(idx); @@ -291,7 +291,7 @@ VoronoiSegmentationImageFilterBase <TInputImage,TOutputImage,TBinaryPriorImage> beginx += offset * leftDx; while(idx[1] <= intendy) { - for(i = static_cast<int>(ceil(beginx)); i <= static_cast<int>(floor(endx)); i++) + for(i = static_cast<int>(vcl_ceil(beginx)); i <= static_cast<int>(vcl_floor(endx)); i++) { idx[0] = i; (*PixelPool).push_back(idx); @@ -350,7 +350,7 @@ VoronoiSegmentationImageFilterBase <TInputImage,TOutputImage,TBinaryPriorImage> endx += offset * rightDx; while(idx[1] <= intendy) { - for(i = static_cast<int>(ceil(beginx)); i <= static_cast<int>(floor(endx)); i++) + for(i = static_cast<int>(vcl_ceil(beginx)); i <= static_cast<int>(vcl_floor(endx)); i++) { idx[0] = i; (*PixelPool).push_back(idx); @@ -751,7 +751,7 @@ VoronoiSegmentationImageFilterBase <TInputImage,TOutputImage,TBinaryPriorImage> { beginx=leftP[0]; } - for(i=static_cast<int>(ceil(beginx));i<=static_cast<int>(floor(endx));i++) + for(i=static_cast<int>(vcl_ceil(beginx));i<=static_cast<int>(vcl_floor(endx));i++) { idx[0]=i; this->GetOutput()->SetPixel(idx,color); @@ -765,7 +765,7 @@ VoronoiSegmentationImageFilterBase <TInputImage,TOutputImage,TBinaryPriorImage> beginx += offset * leftDx; while(idx[1] <= intendy) { - for(i = static_cast<int>(ceil(beginx)); i <= static_cast<int>(floor(endx)); i++) + for(i = static_cast<int>(vcl_ceil(beginx)); i <= static_cast<int>(vcl_floor(endx)); i++) { idx[0] = i; this->GetOutput()->SetPixel(idx,color); @@ -852,7 +852,7 @@ VoronoiSegmentationImageFilterBase <TInputImage,TOutputImage,TBinaryPriorImage> beginx += offset * leftDx; while(idx[1] <= intendy) { - for(i = static_cast<int>(ceil(beginx)); i <= static_cast<int>(floor(endx)); i++) + for(i = static_cast<int>(vcl_ceil(beginx)); i <= static_cast<int>(vcl_floor(endx)); i++) { idx[0] = i; this->GetOutput()->SetPixel(idx,color); @@ -911,7 +911,7 @@ VoronoiSegmentationImageFilterBase <TInputImage,TOutputImage,TBinaryPriorImage> endx += offset * rightDx; while(idx[1] <= intendy) { - for(i = static_cast<int>(ceil(beginx)); i <= static_cast<int>(floor(endx)); i++) + for(i = static_cast<int>(vcl_ceil(beginx)); i <= static_cast<int>(vcl_floor(endx)); i++) { idx[0] = i; this->GetOutput()->SetPixel(idx,color); diff --git a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationRGBImageFilter.h b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationRGBImageFilter.h index 92f8e966b0..3182c0362d 100644 --- a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationRGBImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationRGBImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVoronoiSegmentationRGBImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:17 $ - Version: $Revision: 1.35 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.36 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -98,7 +98,7 @@ public: * default as 8 bit per channel, if it is different, need to be * set before doing anything. */ itkSetMacro(MaxValueOfRGB,double); - itkGetMacro(MaxValueOfRGB,double); + itkGetConstMacro(MaxValueOfRGB,double); /** Set the three channels to test the mean and STD respectivley * 0:red, 1:green, 2:blue, 3:hue, 4:chroma, 5:value. */ diff --git a/Utilities/ITK/Code/Algorithms/itkWatershedBoundaryResolver.h b/Utilities/ITK/Code/Algorithms/itkWatershedBoundaryResolver.h index 17627ddb1d..fb45105eff 100644 --- a/Utilities/ITK/Code/Algorithms/itkWatershedBoundaryResolver.h +++ b/Utilities/ITK/Code/Algorithms/itkWatershedBoundaryResolver.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWatershedBoundaryResolver.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:17 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -99,7 +99,7 @@ public: /** Set/Get the face of the boundary object that we are going to * resolve. */ itkSetMacro(Face, unsigned short); - itkGetMacro(Face, unsigned short); + itkGetConstMacro(Face, unsigned short); /** This method sets/gets the equivalency table used to store equivalencies * among segments that are generated from the boundary resolution diff --git a/Utilities/ITK/Code/Algorithms/itkWatershedImageFilter.h b/Utilities/ITK/Code/Algorithms/itkWatershedImageFilter.h index 08a0cbc9f7..fbf853a220 100644 --- a/Utilities/ITK/Code/Algorithms/itkWatershedImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkWatershedImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWatershedImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:18 $ - Version: $Revision: 1.44 $ + Date: $Date: 2009-04-23 03:53:37 $ + Version: $Revision: 1.45 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -216,12 +216,12 @@ public: /** Set/Get the input thresholding parameter. Units are a percentage of * the maximum depth in the image. */ void SetThreshold(double); - itkGetMacro(Threshold, double); + itkGetConstMacro(Threshold, double); /** Set/Get the flood level for generating the merge tree from the initial * segmentation */ void SetLevel(double); - itkGetMacro(Level, double); + itkGetConstMacro(Level, double); /** Get the basic segmentation from the Segmenter member filter. */ typename watershed::Segmenter<InputImageType>::OutputImageType * diff --git a/Utilities/ITK/Code/Algorithms/itkWatershedMiniPipelineProgressCommand.cxx b/Utilities/ITK/Code/Algorithms/itkWatershedMiniPipelineProgressCommand.cxx index 8c787f2398..adddb85082 100644 --- a/Utilities/ITK/Code/Algorithms/itkWatershedMiniPipelineProgressCommand.cxx +++ b/Utilities/ITK/Code/Algorithms/itkWatershedMiniPipelineProgressCommand.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWatershedMiniPipelineProgressCommand.cxx,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:18 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-12 20:21:46 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,4 +47,11 @@ void WatershedMiniPipelineProgressCommand } } +void WatershedMiniPipelineProgressCommand +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "NumberOfFilters: " << m_NumberOfFilters << std::endl; + os << indent << "Count: " << m_Count << std::endl; +} } // end namespace itk diff --git a/Utilities/ITK/Code/Algorithms/itkWatershedMiniPipelineProgressCommand.h b/Utilities/ITK/Code/Algorithms/itkWatershedMiniPipelineProgressCommand.h index 07b9ab3ca0..1b9fda251a 100644 --- a/Utilities/ITK/Code/Algorithms/itkWatershedMiniPipelineProgressCommand.h +++ b/Utilities/ITK/Code/Algorithms/itkWatershedMiniPipelineProgressCommand.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWatershedMiniPipelineProgressCommand.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:18 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-12 20:21:46 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,7 +27,7 @@ namespace itk { * MiniPipeline. Follows the progress of a series of filters * and calls UpdateProgress on another filter (i.e. the filter * implementing the mini-pipeline). */ -class WatershedMiniPipelineProgressCommand : public Command +class ITK_EXPORT WatershedMiniPipelineProgressCommand : public Command { public: /** Smart pointer declaration methods */ @@ -51,17 +51,18 @@ public: /** Set/Get the base count for stepping through filter progress values */ itkSetMacro(Count, double); - itkGetMacro(Count, double); + itkGetConstMacro(Count, double); /** Set/Get the number of filters that this command will expect to be * observing */ itkSetMacro(NumberOfFilters, double); - itkGetMacro(NumberOfFilters, double); + itkGetConstMacro(NumberOfFilters, double); protected: WatershedMiniPipelineProgressCommand() : m_Count(0.0), m_Filter(0), m_NumberOfFilters(1) {} virtual ~WatershedMiniPipelineProgressCommand() {} + void PrintSelf(std::ostream& os, Indent indent) const; private: double m_Count; diff --git a/Utilities/ITK/Code/Algorithms/itkWatershedRelabeler.h b/Utilities/ITK/Code/Algorithms/itkWatershedRelabeler.h index b787c91978..334eaf079e 100644 --- a/Utilities/ITK/Code/Algorithms/itkWatershedRelabeler.h +++ b/Utilities/ITK/Code/Algorithms/itkWatershedRelabeler.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWatershedRelabeler.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:18 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-23 03:53:38 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -125,7 +125,7 @@ public: /** Set/Get the percentage of the maximum saliency level * to merge to. */ itkSetClampMacro(FloodLevel, double, 0.0, 1.0); - itkGetMacro(FloodLevel, double); + itkGetConstMacro(FloodLevel, double); /** Standard ProcessObject method used in implementing mini-pipelines */ void GraftOutput(ImageType *graft); diff --git a/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTree.h b/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTree.h index 9cd766e140..efccafecd5 100644 --- a/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTree.h +++ b/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTree.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWatershedSegmentTree.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:19 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-04-17 16:12:25 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,7 +27,7 @@ namespace itk { namespace watershed { -/* \class SegmentTree +/** \class SegmentTree * A data structure for storing segment merge information used in filters of * the watershed segmentation algorithm. See itk::WatershedImageFilter for an * overview. @@ -38,8 +38,11 @@ namespace watershed * component classes. It holds a list of merges among image segments at * various saliency levels. The list is actually a representation of a binary * tree, whose nodes are segments and edges are saliencies. + * * \ingroup WatershedSegmentation - * \sa itk::WatershedImageFilter */ + * \sa itk::WatershedImageFilter + * + */ template <class TScalarType> class ITK_EXPORT SegmentTree : public DataObject { @@ -73,6 +76,7 @@ public: struct merge_comp : public std::binary_function<bool, const merge_t&, const merge_t& > { + merge_comp() {} bool operator()(const merge_t &a, const merge_t &b) { return b.saliency < a.saliency; diff --git a/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTreeGenerator.h b/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTreeGenerator.h index a9cbc7540b..ade8cb0c01 100644 --- a/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTreeGenerator.h +++ b/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTreeGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWatershedSegmentTreeGenerator.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:19 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-23 03:53:38 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -144,7 +144,7 @@ public: useful for streaming applications and is turned off by default. (TRUE == merge, FALSE == do not merge). */ itkSetMacro(Merge, bool); - itkGetMacro(Merge, bool); + itkGetConstMacro(Merge, bool); /** Get/Set FloodLevel. FloodLevel is specified as a percentage (0.0 - 1.0) of the maximum possible saliency value in the initial image from which the @@ -152,13 +152,13 @@ public: 1.0 calculates all of the potential merges that can occur as the FloodLevel is increased to the maximum saliency value. */ void SetFloodLevel(double); - itkGetMacro(FloodLevel, double); + itkGetConstMacro(FloodLevel, double); /** Get/Set HighestCalculatedFloodLevel. HighestCalculatedFloodLevel keeps * track of the highest level this filter has computed. It is * used to prevent unneccessary re-execution of the filter. */ itkSetMacro(HighestCalculatedFloodLevel, double); - itkGetMacro(HighestCalculatedFloodLevel, double); + itkGetConstMacro(HighestCalculatedFloodLevel, double); /** Get/Set a flag that prevents the filter from copying its input * segment table before executing. This can be enabled to conserve @@ -166,7 +166,7 @@ public: * concern. If enabled, the input to this filter must always be * re-executed on updates. Default is false. */ itkSetMacro(ConsumeInput, bool); - itkGetMacro(ConsumeInput, bool); + itkGetConstMacro(ConsumeInput, bool); /** Performs a merge of two segments in a SegmentTable according * to criteria specific to this algorithm. */ diff --git a/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTreeGenerator.txx b/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTreeGenerator.txx index 889a9a0d42..b23dfb5baf 100644 --- a/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTreeGenerator.txx +++ b/Utilities/ITK/Code/Algorithms/itkWatershedSegmentTreeGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWatershedSegmentTreeGenerator.txx,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:19 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-17 15:57:33 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -181,8 +181,8 @@ void SegmentTreeGenerator<TScalarType> } // Heapsort the list - typename SegmentTreeType::merge_comp comp; - std::make_heap(mergeList->Begin(), mergeList->End(), comp); + typedef typename SegmentTreeType::merge_comp MergeComparison; + std::make_heap(mergeList->Begin(), mergeList->End(), MergeComparison() ); } template <class TScalarType> @@ -198,7 +198,7 @@ void SegmentTreeGenerator<TScalarType> ScalarType threshold = static_cast<ScalarType>(m_FloodLevel * segments->GetMaximumDepth()); unsigned counter; - typename SegmentTreeType::merge_comp comp; + typedef typename SegmentTreeType::merge_comp MergeComparison; typename SegmentTableType::DataType *toSeg; typename SegmentTreeType::ValueType tempMerge; unsigned long toSegLabel, fromSegLabel; @@ -229,7 +229,7 @@ void SegmentTreeGenerator<TScalarType> initHeapSize)); } - std::pop_heap(heap->Begin(), heap->End(), comp); + std::pop_heap(heap->Begin(), heap->End(), MergeComparison() ); heap->PopBack(); // Popping the heap moves the top element to the end // of the container structure, so we delete that here. @@ -274,7 +274,7 @@ void SegmentTreeGenerator<TScalarType> (toSeg->edge_list.front().height) - toSeg->min; heap->PushBack(tempMerge); - std::push_heap(heap->Begin(), heap->End(), comp); + std::push_heap(heap->Begin(), heap->End(), MergeComparison() ); } } if( ! heap->Empty() ) diff --git a/Utilities/ITK/Code/Algorithms/itkWatershedSegmenter.h b/Utilities/ITK/Code/Algorithms/itkWatershedSegmenter.h index 1fadde7f67..bca987fce0 100644 --- a/Utilities/ITK/Code/Algorithms/itkWatershedSegmenter.h +++ b/Utilities/ITK/Code/Algorithms/itkWatershedSegmenter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWatershedSegmenter.h,v $ Language: C++ - Date: $Date: 2009-01-27 19:30:19 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-23 03:53:38 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -199,7 +199,7 @@ public: /** Gets/Sets the initial label (unsigned long integer value) used * by the labeling algorithm. Only necessary for streaming applications. */ itkSetMacro(CurrentLabel, unsigned long); - itkGetMacro(CurrentLabel, unsigned long); + itkGetConstMacro(CurrentLabel, unsigned long); /** Gets/Sets the input threshold. Threshold is specified as a percentage * (0.0 - 1.0) of the maximum height of the image. This filter thresholds the @@ -212,19 +212,19 @@ public: * regions that this thresholding eliminates are generally not of * interest. */ itkSetClampMacro(Threshold, double, 0.0, 1.0); - itkGetMacro(Threshold, double); + itkGetConstMacro(Threshold, double); /** Turns on special labeling of the boundaries for streaming applications. * The default value is FALSE, meaning that boundary analysis is turned * off. */ itkSetMacro(DoBoundaryAnalysis, bool); - itkGetMacro(DoBoundaryAnalysis, bool); + itkGetConstMacro(DoBoundaryAnalysis, bool); /** Determines whether the algorithm will sort the adjacencies in its * SegmentTable before returning. Default is true. This is an option only * useful for streaming applications where the sorting only needs to be done * after all iterations have taken place. */ - itkGetMacro(SortEdgeLists, bool); + itkGetConstMacro(SortEdgeLists, bool); itkSetMacro(SortEdgeLists, bool); protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkAbsImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAbsImageFilter.h index 49f66be2a8..b27e05218b 100755 --- a/Utilities/ITK/Code/BasicFilters/itkAbsImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAbsImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAbsImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:09:10 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-01 14:36:03 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return (TOutput)( ( A > 0 ) ? A : -A ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkAbsoluteValueDifferenceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAbsoluteValueDifferenceImageFilter.h index 06b8eb78e1..f6a54c5313 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAbsoluteValueDifferenceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAbsoluteValueDifferenceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAbsoluteValueDifferenceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:09:10 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:05 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -63,7 +63,7 @@ public: return !(*this != other); } inline TOutput operator()( const TInput1 & A, - const TInput2 & B) + const TInput2 & B) const { const double dA = static_cast<double>( A ); const double dB = static_cast<double>( B ); diff --git a/Utilities/ITK/Code/BasicFilters/itkAccumulateImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAccumulateImageFilter.h index d4122cc22e..c7de9e1375 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAccumulateImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAccumulateImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAccumulateImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:09:10 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:27:00 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -97,7 +97,7 @@ public: /** Set the direction in which to accumulate the data. It must be * set before the update of the filter. Defaults to the last * dimension. */ - itkGetMacro( AccumulateDimension, unsigned int ); + itkGetConstMacro( AccumulateDimension, unsigned int ); itkSetMacro( AccumulateDimension, unsigned int ); /** Perform a division by the size of the accumulated dimension @@ -106,7 +106,7 @@ public: * sum of the pixels along the selected direction. The default * value is false. */ itkSetMacro( Average, bool ); - itkGetMacro( Average, bool ); + itkGetConstMacro( Average, bool ); itkBooleanMacro(Average); diff --git a/Utilities/ITK/Code/BasicFilters/itkAcosImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAcosImageFilter.h index d1ba2f5daf..faa30dd6bd 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAcosImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAcosImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAcosImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:09:10 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-04-01 14:36:05 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,7 +59,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( vcl_acos(static_cast<double>(A) ) ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkAdaptImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAdaptImageFilter.h index c54cc4e0fc..b3f26d644c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAdaptImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAdaptImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAdaptImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:09:10 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-01 14:36:06 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,7 +47,7 @@ public: /** operator(). This is the "call" method of the functor. */ typedef typename TAccessor::ExternalType OutputType; - inline OutputType operator()( const TInput & A ) + inline OutputType operator() ( const TInput & A ) const { return m_Accessor.Get( A ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkAdaptiveHistogramEqualizationImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAdaptiveHistogramEqualizationImageFilter.h index 6e643f3442..3fa2c2968a 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAdaptiveHistogramEqualizationImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAdaptiveHistogramEqualizationImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAdaptiveHistogramEqualizationImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:13:36 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-04-25 12:27:02 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -94,14 +94,14 @@ public: * histogram equalization (provided beta=0). Alpha=1 produces an * unsharp mask. Default is 0.3. */ itkSetMacro(Alpha, float); - itkGetMacro(Alpha, float); + itkGetConstMacro(Alpha, float); /** Set/Get the value of beta. If beta=1 (and alpha=1), * then the output image matches the input image. As beta * approaches 0, the filter behaves as an unsharp mask. Default is * 0.3. */ itkSetMacro(Beta, float); - itkGetMacro(Beta, float); + itkGetConstMacro(Beta, float); /** Set/Get the radius of the neighborhood used to compute local * statistics. Radius sizes of 10 and 20 are common. Default is a @@ -112,7 +112,7 @@ public: /** Set/Get whether an optimized lookup table for the intensity * mapping function is used. Default is off. */ itkSetMacro(UseLookupTable, bool); - itkGetMacro(UseLookupTable, bool); + itkGetConstMacro(UseLookupTable, bool); itkBooleanMacro(UseLookupTable); protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkAddImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAddImageFilter.h index 6538dad7d1..9b762e6fc9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAddImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAddImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAddImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 15:07:03 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-01 14:36:08 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,7 +73,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator() ( const TInput1 & A, const TInput2 & B) const { const AccumulatorType sum = A; return static_cast<TOutput>( sum + B ); diff --git a/Utilities/ITK/Code/BasicFilters/itkAndImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAndImageFilter.h index 8d7100f0a6..180ed0768c 100755 --- a/Utilities/ITK/Code/BasicFilters/itkAndImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAndImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAndImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:49:29 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:08 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,7 +59,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { return static_cast<TOutput>( A & B ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkAnisotropicDiffusionImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAnisotropicDiffusionImageFilter.h index 865ce56a86..7e01798baa 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAnisotropicDiffusionImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAnisotropicDiffusionImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnisotropicDiffusionImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:49:30 $ - Version: $Revision: 1.42 $ + Date: $Date: 2009-04-25 12:27:04 $ + Version: $Revision: 1.43 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,22 +100,22 @@ public: /** Set/Get the time step for each iteration */ itkSetMacro(TimeStep, TimeStepType); - itkGetMacro(TimeStep, TimeStepType); + itkGetConstMacro(TimeStep, TimeStepType); /** Set/Get the conductance parameter governing sensitivity of the conductance equation. */ itkSetMacro(ConductanceParameter, double); - itkGetMacro(ConductanceParameter, double); + itkGetConstMacro(ConductanceParameter, double); /** Set/Get the interval at which a new scaling for the conductance term is calculated. */ itkSetMacro(ConductanceScalingUpdateInterval, unsigned int); - itkGetMacro(ConductanceScalingUpdateInterval, unsigned int); + itkGetConstMacro(ConductanceScalingUpdateInterval, unsigned int); /** The following parameters are not used at this time. Setting them will have no effect on the output */ itkSetMacro(ConductanceScalingParameter, double); - itkGetMacro(ConductanceScalingParameter, double); + itkGetConstMacro(ConductanceScalingParameter, double); /** Supplies a fixed value for the average gradient magnitude of the image to the AnisotropicDiffusionFunction at each iteration. The average gradient @@ -130,7 +130,7 @@ public: this->Modified(); m_GradientMagnitudeIsFixed = true; } - itkGetMacro(FixedAverageGradientMagnitude, double); + itkGetConstMacro(FixedAverageGradientMagnitude, double); protected: AnisotropicDiffusionImageFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkApproximateSignedDistanceMapImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkApproximateSignedDistanceMapImageFilter.h index 1bbe4ad322..f72b1e57b5 100755 --- a/Utilities/ITK/Code/BasicFilters/itkApproximateSignedDistanceMapImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkApproximateSignedDistanceMapImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkApproximateSignedDistanceMapImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:49:30 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-25 12:27:05 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -106,11 +106,11 @@ public: /** Set/Get intensity value representing the interior of objects in the mask */ itkSetMacro(InsideValue, InputPixelType); - itkGetMacro(InsideValue, InputPixelType); + itkGetConstMacro(InsideValue, InputPixelType); /** Set/Get intensity value representing non-objects in the mask */ itkSetMacro(OutsideValue, InputPixelType); - itkGetMacro(OutsideValue, InputPixelType); + itkGetConstMacro(OutsideValue, InputPixelType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkAsinImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAsinImageFilter.h index b338c3137d..815ce11e93 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAsinImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAsinImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAsinImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:49:30 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-01 14:36:08 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -57,7 +57,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( vcl_asin( diff --git a/Utilities/ITK/Code/BasicFilters/itkAtan2ImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAtan2ImageFilter.h index d4243d9706..bdfbba8e45 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAtan2ImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAtan2ImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAtan2ImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:49:30 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-01 14:36:08 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,7 +52,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { return static_cast<TOutput>( vcl_atan2( diff --git a/Utilities/ITK/Code/BasicFilters/itkAtanImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkAtanImageFilter.h index 83dedeb4be..6d52432916 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAtanImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkAtanImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAtanImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 14:49:30 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-04-01 14:36:09 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,7 +59,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( vcl_atan(static_cast<double>(A) ) ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkBSplineDecompositionImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkBSplineDecompositionImageFilter.h index f254f5a71c..8a330387b5 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBSplineDecompositionImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkBSplineDecompositionImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineDecompositionImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-14 18:39:05 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:27:05 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -12,8 +12,8 @@ Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -34,7 +34,7 @@ namespace itk * \brief Calculates the B-Spline coefficients of an image. Spline order may be from 0 to 5. * * This class defines N-Dimension B-Spline transformation. - * It is based on: + * It is based on: * [1] M. Unser, * "Splines: A Perfect Fit for Signal and Image Processing," * IEEE Signal Processing Magazine, vol. 16, no. 6, pp. 22-38, @@ -48,7 +48,7 @@ namespace itk * IEEE Transactions on Signal Processing, vol. 41, no. 2, pp. 834-848, * February 1993. * And code obtained from bigwww.epfl.ch by Philippe Thevenaz - * + * * Limitations: Spline order must be between 0 and 5. * Spline order must be set before setting the image. * Uses mirror boundary conditions. @@ -60,10 +60,10 @@ namespace itk * ***TODO: Is this an ImageFilter? or does it belong to another group? * \ingroup ImageFilters * \ingroup SingleThreaded - * \ingroup CannotBeStreamed + * \ingroup CannotBeStreamed */ template <class TInputImage, class TOutputImage> -class ITK_EXPORT BSplineDecompositionImageFilter : +class ITK_EXPORT BSplineDecompositionImageFilter : public ImageToImageFilter<TInputImage,TOutputImage> { public: @@ -75,7 +75,7 @@ public: /** Run-time type information (and related methods). */ itkTypeMacro(BSplineDecompositionImageFilter, ImageToImageFilter); - + /** New macro for creation of through a Smart Pointer */ itkNewMacro( Self ); @@ -98,7 +98,7 @@ public: /** Get/Sets the Spline Order, supports 0th - 5th order splines. The default * is a 3rd order spline. */ void SetSplineOrder(unsigned int SplineOrder); - itkGetMacro(SplineOrder, int); + itkGetConstMacro(SplineOrder, int); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ @@ -128,7 +128,7 @@ protected: void GenerateInputRequestedRegion(); /** This filter must produce all of its output at once. */ - void EnlargeOutputRequestedRegion( DataObject *output ); + void EnlargeOutputRequestedRegion( DataObject *output ); /** These are needed by the smoothing spline routine. */ std::vector<CoeffType> m_Scratch; // temp storage for processing of Coefficients @@ -169,7 +169,7 @@ private: /** Copies a vector of data from m_Scratch to the Coefficients image. */ void CopyScratchToCoefficients( OutputLinearIterator & ); - + }; diff --git a/Utilities/ITK/Code/BasicFilters/itkBSplineDecompositionImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkBSplineDecompositionImageFilter.txx index 813bf5cd11..6ba262ff0d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBSplineDecompositionImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkBSplineDecompositionImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineDecompositionImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-09 20:43:42 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-05 23:09:19 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -12,8 +12,8 @@ Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -50,7 +50,7 @@ template <class TInputImage, class TOutputImage> void BSplineDecompositionImageFilter<TInputImage, TOutputImage> ::PrintSelf( - std::ostream& os, + std::ostream& os, Indent indent) const { Superclass::PrintSelf( os, indent ); @@ -63,13 +63,13 @@ template <class TInputImage, class TOutputImage> bool BSplineDecompositionImageFilter<TInputImage, TOutputImage> ::DataToCoefficients1D() -{ - - // See Unser, 1993, Part II, Equation 2.5, - // or Unser, 1999, Box 2. for an explaination. +{ - double c0 = 1.0; + // See Unser, 1993, Part II, Equation 2.5, + // or Unser, 1999, Box 2. for an explaination. + double c0 = 1.0; + if (m_DataLength[m_IteratorDirection] == 1) //Required by mirror boundaries { return false; @@ -78,30 +78,30 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> // Compute overall gain for (int k = 0; k < m_NumberOfPoles; k++) { - // Note for cubic splines lambda = 6 + // Note for cubic splines lambda = 6 c0 = c0 * (1.0 - m_SplinePoles[k]) * (1.0 - 1.0 / m_SplinePoles[k]); } - // apply the gain + // apply the gain for (unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++) { m_Scratch[n] *= c0; } - // loop over all poles - for (int k = 0; k < m_NumberOfPoles; k++) + // loop over all poles + for (int k = 0; k < m_NumberOfPoles; k++) { - // causal initialization + // causal initialization this->SetInitialCausalCoefficient(m_SplinePoles[k]); - // causal recursion + // causal recursion for (unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++) { m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1]; } - // anticausal initialization + // anticausal initialization this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]); - // anticausal recursion + // anticausal recursion for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n--) { m_Scratch[n] = m_SplinePoles[k] * (m_Scratch[n + 1] - m_Scratch[n]); @@ -134,7 +134,7 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> ::SetPoles() { /* See Unser, 1997. Part II, Table I for Pole values */ - // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac N. Bankman, + // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac N. Bankman, // 2000, pg. 416. switch (m_SplineOrder) { @@ -191,13 +191,13 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> zn = z; if (m_Tolerance > 0.0) { - horizon = (long)vcl_ceil(log(m_Tolerance) / vcl_log(fabs(z))); + horizon = (long)vcl_ceil(vcl_log(m_Tolerance) / vcl_log(vcl_fabs(z))); } if (horizon < m_DataLength[m_IteratorDirection]) { /* accelerated loop */ sum = m_Scratch[0]; // verify this - for (unsigned int n = 1; n < horizon; n++) + for (unsigned int n = 1; n < horizon; n++) { sum += zn * m_Scratch[n]; zn *= z; @@ -226,11 +226,11 @@ void BSplineDecompositionImageFilter<TInputImage, TOutputImage> ::SetInitialAntiCausalCoefficient(double z) { - // this initialization corresponds to mirror boundaries + // this initialization corresponds to mirror boundaries /* See Unser, 1999, Box 2 for explaination */ // Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html m_Scratch[m_DataLength[m_IteratorDirection] - 1] = - (z / (z * z - 1.0)) * + (z / (z * z - 1.0)) * (z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1]); } @@ -268,7 +268,7 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> // Perform 1D BSpline calculations this->DataToCoefficients1D(); - + // Copy scratch back to coefficients. // Brings us back to the end of the line we were working on. CIterator.GoToBeginOfLine(); @@ -305,7 +305,7 @@ BSplineDecompositionImageFilter<TInputImage, TOutputImage> ++inIt; ++outIt; } - + } diff --git a/Utilities/ITK/Code/BasicFilters/itkBSplineInterpolateImageFunction.h b/Utilities/ITK/Code/BasicFilters/itkBSplineInterpolateImageFunction.h index 0ef8bf204a..50bf884e01 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBSplineInterpolateImageFunction.h +++ b/Utilities/ITK/Code/BasicFilters/itkBSplineInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2009-01-28 17:52:26 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-25 12:27:05 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -178,7 +178,7 @@ public: * and OFF by default when ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE is * OFF). */ itkSetMacro( UseImageDirection, bool ); - itkGetMacro( UseImageDirection, bool ); + itkGetConstMacro( UseImageDirection, bool ); itkBooleanMacro( UseImageDirection ); diff --git a/Utilities/ITK/Code/BasicFilters/itkBSplineInterpolateImageFunction.txx b/Utilities/ITK/Code/BasicFilters/itkBSplineInterpolateImageFunction.txx index a98c76b20a..0fb05dfd0f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBSplineInterpolateImageFunction.txx +++ b/Utilities/ITK/Code/BasicFilters/itkBSplineInterpolateImageFunction.txx @@ -12,8 +12,8 @@ Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -69,19 +69,19 @@ template <class TImageType, class TCoordRep, class TCoefficientType> void BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> ::PrintSelf( - std::ostream& os, + std::ostream& os, Indent indent) const { Superclass::PrintSelf( os, indent ); os << indent << "Spline Order: " << m_SplineOrder << std::endl; - os << indent << "UseImageDirection = " + os << indent << "UseImageDirection = " << (this->m_UseImageDirection ? "On" : "Off") << std::endl; } template <class TImageType, class TCoordRep, class TCoefficientType> -void +void BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> ::SetInputImage(const TImageType * inputData) { @@ -91,7 +91,7 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> // the Coefficient Filter requires that the spline order and the input data be set. // TODO: We need to ensure that this is only run once and only after both input and - // spline order have been set. Should we force an update after the + // spline order have been set. Should we force an update after the // splineOrder has been set also? m_CoefficientFilter->Update(); @@ -111,7 +111,7 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> template <class TImageType, class TCoordRep, class TCoefficientType> -void +void BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> ::SetSplineOrder(unsigned int SplineOrder) { @@ -127,13 +127,13 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> for (unsigned int n=0; n < ImageDimension; n++) { m_MaxNumberInterpolationPoints *= ( m_SplineOrder + 1); - } + } this->GeneratePointsToIndex( ); } template <class TImageType, class TCoordRep, class TCoefficientType> -typename +typename BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> ::OutputType BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> @@ -141,8 +141,8 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> { vnl_matrix<long> EvaluateIndex(ImageDimension, ( m_SplineOrder + 1 )); - // compute the interpolation indexes - this->DetermineRegionOfSupport(EvaluateIndex, x, m_SplineOrder); + // compute the interpolation indexes + this->DetermineRegionOfSupport(EvaluateIndex, x, m_SplineOrder); // Determine weights vnl_matrix<double> weights(ImageDimension, ( m_SplineOrder + 1 )); @@ -150,8 +150,8 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> // Modify EvaluateIndex at the boundaries using mirror boundary conditions this->ApplyMirrorBoundaryConditions(EvaluateIndex, m_SplineOrder); - - // perform interpolation + + // perform interpolation double interpolated = 0.0; IndexType coefficientIndex; // Step through eachpoint in the N-dimensional interpolation cube. @@ -170,14 +170,14 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> // m_Coefficients cube. interpolated += w * (m_Coefficients->GetPixel(coefficientIndex)); } - + return(interpolated); - + } template <class TImageType, class TCoordRep, class TCoefficientType> -typename +typename BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> :: CovariantVectorType BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> @@ -185,7 +185,7 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> { vnl_matrix<long> EvaluateIndex(ImageDimension, ( m_SplineOrder + 1 )); - // compute the interpolation indexes + // compute the interpolation indexes // TODO: Do we need to revisit region of support for the derivatives? this->DetermineRegionOfSupport(EvaluateIndex, x, m_SplineOrder); @@ -198,7 +198,7 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> // Modify EvaluateIndex at the boundaries using mirror boundary conditions this->ApplyMirrorBoundaryConditions(EvaluateIndex, m_SplineOrder); - + const InputImageType * inputImage = this->GetInputImage(); const typename InputImageType::SpacingType & spacing = inputImage->GetSpacing(); @@ -211,7 +211,7 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> derivativeValue[n] = 0.0; for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) { - tempValue = 1.0; + tempValue = 1.0; for (unsigned int n1 = 0; n1 < ImageDimension; n1++) { //coefficientIndex[n1] = EvaluateIndex[n1][sp]; @@ -246,16 +246,16 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> template <class TImageType, class TCoordRep, class TCoefficientType> -void +void BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> -::SetInterpolationWeights( const ContinuousIndexType & x, const vnl_matrix<long> & EvaluateIndex, +::SetInterpolationWeights( const ContinuousIndexType & x, const vnl_matrix<long> & EvaluateIndex, vnl_matrix<double> & weights, unsigned int splineOrder ) const { // For speed improvements we could make each case a separate function and use // function pointers to reference the correct weight order. // Left as is for now for readability. double w, w2, w4, t, t0, t1; - + switch (splineOrder) { case 3: @@ -340,13 +340,13 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> throw err; break; } - + } template <class TImageType, class TCoordRep, class TCoefficientType> -void +void BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> -::SetDerivativeWeights( const ContinuousIndexType & x, const vnl_matrix<long> & EvaluateIndex, +::SetDerivativeWeights( const ContinuousIndexType & x, const vnl_matrix<long> & EvaluateIndex, vnl_matrix<double> & weights, unsigned int splineOrder ) const { // For speed improvements we could make each case a separate function and use @@ -356,10 +356,10 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> // Left as is for now for readability. double w, w1, w2, w3, w4, w5, t, t0, t1, t2; int derivativeSplineOrder = (int) splineOrder -1; - + switch (derivativeSplineOrder) { - + // Calculates B(splineOrder) ( (x + 1/2) - xi) - B(splineOrder -1) ( (x - 1/2) - xi) case -1: // Why would we want to do this? @@ -384,11 +384,11 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> weights[n][0] = 0.0 - w1; weights[n][1] = w1 - w; - weights[n][2] = w; + weights[n][2] = w; } break; case 2: - + for (unsigned int n = 0; n < ImageDimension; n++) { w = x[n] + .5 - (double)EvaluateIndex[n][2]; @@ -399,11 +399,11 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> weights[n][0] = 0.0 - w1; weights[n][1] = w1 - w2; weights[n][2] = w2 - w3; - weights[n][3] = w3; + weights[n][3] = w3; } break; case 3: - + for (unsigned int n = 0; n < ImageDimension; n++) { w = x[n] + 0.5 - (double)EvaluateIndex[n][2]; @@ -443,7 +443,7 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> weights[n][5] = w5; } break; - + default: // SplineOrder not implemented yet. ExceptionObject err(__FILE__, __LINE__); @@ -452,7 +452,7 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> throw err; break; } - + } @@ -485,13 +485,13 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> template <class TImageType, class TCoordRep, class TCoefficientType> void BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> -::DetermineRegionOfSupport( vnl_matrix<long> & evaluateIndex, - const ContinuousIndexType & x, +::DetermineRegionOfSupport( vnl_matrix<long> & evaluateIndex, + const ContinuousIndexType & x, unsigned int splineOrder ) const -{ +{ long indx; -// compute the interpolation indexes +// compute the interpolation indexes for (unsigned int n = 0; n< ImageDimension; n++) { if (splineOrder & 1) // Use this index calculation for odd splineOrder @@ -503,7 +503,7 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> } } else // Use this index calculation for even splineOrder - { + { indx = (long)vcl_floor((float)(x[n] + 0.5)) - splineOrder / 2; for (unsigned int k = 0; k <= splineOrder; k++) { @@ -516,14 +516,14 @@ BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> template <class TImageType, class TCoordRep, class TCoefficientType> void BSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> -::ApplyMirrorBoundaryConditions(vnl_matrix<long> & evaluateIndex, +::ApplyMirrorBoundaryConditions(vnl_matrix<long> & evaluateIndex, unsigned int splineOrder) const { for (unsigned int n = 0; n < ImageDimension; n++) { long dataLength2 = 2 * m_DataLength[n] - 2; - // apply the mirror boundary conditions + // apply the mirror boundary conditions // TODO: We could implement other boundary options beside mirror if (m_DataLength[n] == 1) { diff --git a/Utilities/ITK/Code/BasicFilters/itkBSplineResampleImageFilterBase.h b/Utilities/ITK/Code/BasicFilters/itkBSplineResampleImageFilterBase.h index d499bc1463..c42604690d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBSplineResampleImageFilterBase.h +++ b/Utilities/ITK/Code/BasicFilters/itkBSplineResampleImageFilterBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineResampleImageFilterBase.h,v $ Language: C++ - Date: $Date: 2008-10-09 20:43:43 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:27:07 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -122,7 +122,7 @@ public: void SetSplineOrder(int SplineOrder); /** Get the spline order */ - itkGetMacro(SplineOrder, int); + itkGetConstMacro(SplineOrder, int); protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkBSplineResampleImageFilterBase.txx b/Utilities/ITK/Code/BasicFilters/itkBSplineResampleImageFilterBase.txx index 47e19789a1..6e5ed45d3f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBSplineResampleImageFilterBase.txx +++ b/Utilities/ITK/Code/BasicFilters/itkBSplineResampleImageFilterBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineResampleImageFilterBase.txx,v $ Language: C++ - Date: $Date: 2008-10-15 23:41:11 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-05-11 21:42:52 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -348,7 +348,7 @@ void BSplineResampleImageFilterBase<TInputImage, TOutputImage> SizeType currentSize; // Does not support streaming typename Superclass::InputImagePointer inputPtr = const_cast< TInputImage * > ( this->GetInput() ); - startSize = inputPtr->GetLargestPossibleRegion().GetSize(); + startSize = inputPtr->GetBufferedRegion().GetSize(); // Initilize scratchImage space and allocate memory InitializeScratch(startSize); @@ -364,13 +364,13 @@ void BSplineResampleImageFilterBase<TInputImage, TOutputImage> // images? i.e. is the rounding handled correctly? currentSize[0] = currentSize[0]/2; scratchRegion.SetSize( currentSize ); - scratchImage->SetBufferedRegion( scratchRegion ); + scratchImage->SetRegions( scratchRegion ); scratchImage->Allocate(); currentSize = startSize; validRegion.SetSize( currentSize ); - validRegion.SetIndex ( inputPtr->GetLargestPossibleRegion().GetIndex() ); + validRegion.SetIndex ( inputPtr->GetBufferedRegion().GetIndex() ); /** The data is handled in this routine to minimize data copying. * Alternative methods could be used which may permit the use of @@ -385,16 +385,15 @@ void BSplineResampleImageFilterBase<TInputImage, TOutputImage> // The first time through the loop our input image is inputPtr typename TInputImage::ConstPointer workingImage; workingImage = inputPtr; -// ConstInputImageIterator inIterator1; -// ConstOutputImageIterator inIterator2; unsigned int count = scratchRegion.GetNumberOfPixels() * ImageDimension; ProgressReporter progress(this,0,count,10); for (unsigned int n=0; n < ImageDimension; n++) { // Setup iterators for input image. - ConstInputImageIterator inIterator1( workingImage, validRegion); - ConstOutputImageIterator inIterator2( scratchImage, validRegion); + ConstInputImageIterator inIterator1( workingImage, validRegion ); + ConstOutputImageIterator inIterator2( scratchImage, scratchRegion ); + if (n==0) { // First time through the loop we use the InputImage @@ -469,7 +468,7 @@ void BSplineResampleImageFilterBase<TInputImage, TOutputImage> // Does not support streaming typename Superclass::InputImagePointer inputPtr = const_cast< TInputImage * > ( this->GetInput() ); - startSize = inputPtr->GetLargestPossibleRegion().GetSize(); + startSize = inputPtr->GetBufferedRegion().GetSize(); // Initilize scratchImage space and allocate memory @@ -494,7 +493,7 @@ void BSplineResampleImageFilterBase<TInputImage, TOutputImage> currentSize = startSize; validRegion.SetSize( currentSize ); - validRegion.SetIndex ( inputPtr->GetLargestPossibleRegion().GetIndex() ); + validRegion.SetIndex ( inputPtr->GetBufferedRegion().GetIndex() ); /** The data is handled in this routine to minimize data copying. Alternative methods could be used which may permit the use of streaming. On the first @@ -510,12 +509,14 @@ void BSplineResampleImageFilterBase<TInputImage, TOutputImage> typename TInputImage::ConstPointer workingImage; workingImage = inputPtr; + RegionType workingRegion = validRegion; + unsigned int count = scratchRegion.GetNumberOfPixels() * ImageDimension; ProgressReporter progress(this,0,count,10); for (unsigned int n=0; n < ImageDimension; n++) { // Setup iterators for input image. - ConstInputImageIterator inIterator1( workingImage, validRegion); + ConstInputImageIterator inIterator1( workingImage, workingRegion); ConstOutputImageIterator inIterator2( scratchImage, validRegion); if (n==0) { @@ -556,7 +557,6 @@ void BSplineResampleImageFilterBase<TInputImage, TOutputImage> this->Expand1DImage( m_Scratch, outIterator, startSize[n], progress ); inIterator1.NextLine(); outIterator.NextLine(); - } } else @@ -581,7 +581,6 @@ template <class TInputImage, class TOutputImage> void BSplineResampleImageFilterBase<TInputImage, TOutputImage> ::InitializeScratch(SizeType DataLength) { -// typename TInputImage::SizeType DataLength = ptr->GetLargestPossibleRegion().GetSize(); unsigned int maxLength = 0; for ( unsigned int n = 0; n < ImageDimension; n++ ) { diff --git a/Utilities/ITK/Code/BasicFilters/itkBilateralImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkBilateralImageFilter.h index 6490be6768..e5fe3d0207 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBilateralImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkBilateralImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBilateralImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.20 $ + Date: $Date: 2009-04-25 12:27:11 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -125,10 +125,10 @@ public: * DomainSigma is specified in the same units as the Image spacing. * RangeSigma is specified in the units of intensity. */ itkSetMacro(DomainSigma, ArrayType); - itkGetMacro(DomainSigma, const ArrayType); + itkGetConstMacro(DomainSigma, const ArrayType); itkSetMacro(RangeSigma, double); - itkGetMacro(RangeSigma, double); - itkGetMacro(FilterDimensionality, unsigned int); + itkGetConstMacro(RangeSigma, double); + itkGetConstMacro(FilterDimensionality, unsigned int); itkSetMacro(FilterDimensionality, unsigned int); /** Convenience get/set methods for setting all domain parameters to the @@ -144,7 +144,7 @@ public: * specified by the user. * \sa SetRadius() */ itkBooleanMacro(AutomaticKernelSize); - itkGetMacro(AutomaticKernelSize, bool); + itkGetConstMacro(AutomaticKernelSize, bool); itkSetMacro(AutomaticKernelSize, bool); /** Set/Get the kernel radius, specified in pixels. This parameter @@ -158,7 +158,7 @@ public: * used for the range smoothing. Samples are only generated in the * range of [0, 4*m_RangeSigma]. Default is 100. */ itkSetMacro(NumberOfRangeGaussianSamples, unsigned long); - itkGetMacro(NumberOfRangeGaussianSamples, unsigned long); + itkGetConstMacro(NumberOfRangeGaussianSamples, unsigned long); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkBinaryDilateImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkBinaryDilateImageFilter.txx index d787de6779..db90024afa 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBinaryDilateImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkBinaryDilateImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryDilateImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-08-13 12:37:50 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-17 18:58:09 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -103,7 +103,7 @@ BinaryDilateImageFilter< TInputImage, TOutputImage, TKernel> InputPixelType value = inIt.Get(); // replace foreground pixels with the default background if (value == foregroundValue) - { outIt.Set( backgroundValue ); } + { outIt.Set( static_cast<OutputPixelType> ( backgroundValue ) ); } // keep all of the original background values intact else { outIt.Set( static_cast<OutputPixelType>( value ) ); } @@ -258,7 +258,7 @@ BinaryDilateImageFilter< TInputImage, TOutputImage, TKernel> { IndexType idx = tmpRegIndexIt.GetIndex() + *itIdx; if( outputRegion.IsInside( idx ) ) - { output->SetPixel( idx, foregroundValue ); } + { output->SetPixel( idx, static_cast<OutputPixelType> ( foregroundValue ) ); } } // add it to queue @@ -329,7 +329,7 @@ BinaryDilateImageFilter< TInputImage, TOutputImage, TKernel> { IndexType idx = neighbIndex + *itIndex; if( outputRegion.IsInside( idx ) ) - { output->SetPixel( idx, foregroundValue ); } + { output->SetPixel( idx, static_cast<OutputPixelType> ( foregroundValue ) ); } } } } @@ -387,7 +387,7 @@ BinaryDilateImageFilter< TInputImage, TOutputImage, TKernel> // Define boundaries conditions ConstantBoundaryCondition<TOutputImage> obc; - obc.SetConstant( backgroundValue ); + obc.SetConstant( static_cast<OutputPixelType> ( backgroundValue ) ); NeighborhoodIterator<OutputImageType> onit( kernel.GetRadius(), output, outputRegion ); @@ -442,7 +442,7 @@ BinaryDilateImageFilter< TInputImage, TOutputImage, TKernel> if( !inputRegionForThread.IsInside( translatedIndex ) || input->GetPixel( translatedIndex ) == foregroundValue ) { - ouRegIndexIt.Set( foregroundValue ); + ouRegIndexIt.Set( static_cast<OutputPixelType> ( foregroundValue ) ); break; // Do not need to examine other offsets because at least one // input pixel has been translated on current output pixel. } @@ -464,7 +464,7 @@ BinaryDilateImageFilter< TInputImage, TOutputImage, TKernel> if( inputRegionForThread.IsInside( translatedIndex ) && input->GetPixel( translatedIndex ) == foregroundValue ) { - ouRegIndexIt.Set( foregroundValue ); + ouRegIndexIt.Set( static_cast<OutputPixelType> ( foregroundValue ) ); break; } } diff --git a/Utilities/ITK/Code/BasicFilters/itkBinaryMagnitudeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkBinaryMagnitudeImageFilter.h index 5ec84c187a..5b38676f27 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBinaryMagnitudeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkBinaryMagnitudeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMagnitudeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-01 14:36:09 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -62,7 +62,7 @@ public: return !(*this != other); } inline TOutput operator()( const TInput1 & A, - const TInput2 & B) + const TInput2 & B) const { const double dA = static_cast<double>( A ); const double dB = static_cast<double>( B ); diff --git a/Utilities/ITK/Code/BasicFilters/itkBinaryMaskToNarrowBandPointSetFilter.h b/Utilities/ITK/Code/BasicFilters/itkBinaryMaskToNarrowBandPointSetFilter.h index 5b017e026d..89e3cab377 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBinaryMaskToNarrowBandPointSetFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkBinaryMaskToNarrowBandPointSetFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMaskToNarrowBandPointSetFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:27:15 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -134,7 +134,7 @@ public: the points in the narrow band. The full width of the full narrow band will be double of this value. */ itkSetMacro( BandWidth, float ); - itkGetMacro( BandWidth, float ); + itkGetConstMacro( BandWidth, float ); protected: BinaryMaskToNarrowBandPointSetFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkBinaryThresholdImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkBinaryThresholdImageFilter.h index 7a067da733..9034f0c097 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBinaryThresholdImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkBinaryThresholdImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryThresholdImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-24 08:14:12 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-01 14:36:09 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,7 +95,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { if ( m_LowerThreshold <= A && A <= m_UpperThreshold ) { diff --git a/Utilities/ITK/Code/BasicFilters/itkBinomialBlurImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkBinomialBlurImageFilter.h index d995866ba7..de230d9a4a 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBinomialBlurImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkBinomialBlurImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinomialBlurImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-09 15:31:37 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-25 12:27:15 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -76,7 +76,7 @@ public: /** Get and set the number of times to repeat the filter. */ itkSetMacro(Repetitions, unsigned int); - itkGetMacro(Repetitions, unsigned int); + itkGetConstMacro(Repetitions, unsigned int); /** This filter needs to request a larger input than its requested output. * If this filter runs "Repetitions" iterations, then it needs an input diff --git a/Utilities/ITK/Code/BasicFilters/itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx index 5af10b81e6..65c23d6a33 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-09 16:20:18 $ - Version: $Revision: 1.42 $ + Date: $Date: 2009-05-07 14:03:37 $ + Version: $Revision: 1.44 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,11 +26,6 @@ #include "itkCumulativeGaussianOptimizer.h" #include "itkCumulativeGaussianCostFunction.h" -typedef vnl_matrix<double> MatrixType; -typedef vnl_vector<double> VectorType; - -const double INV_SQRT_TWO_PI = 0.398942280401; // 1/vcl_sqrt(2*pi) -const double SQUARE_ROOT_OF_TWO = 1.41421356237; // vcl_sqrt(2) namespace itk { @@ -89,10 +84,10 @@ BloxBoundaryPointImageToBloxBoundaryProfileImageFilter< TSourceImage > { m_Accumulator[binNumber] += weight * sourcePixelValue; m_Normalizer[binNumber] += weight; - return(1); + return 1; } - else - return(0); + + return 0; } template< typename TSourceImage > @@ -109,7 +104,9 @@ BloxBoundaryPointImageToBloxBoundaryProfileImageFilter< TSourceImage > for(unsigned int j = 0; j < m_NumberOfBins; ++j) { if(temp >= maximum) + { maximum = temp; + } } } return maximum; @@ -128,7 +125,9 @@ BloxBoundaryPointImageToBloxBoundaryProfileImageFilter< TSourceImage > for(unsigned int j = 0; j < m_NumberOfBins; ++j) { if(temp <= minimum) + { minimum = temp; + } } } return minimum; @@ -231,8 +230,12 @@ BloxBoundaryPointImageToBloxBoundaryProfileImageFilter< TSourceImage > = dynamic_cast<SourceImageType*>(ProcessObject::GetInput(1)); OutputImagePointer outputPtr = this->GetOutput(0); + typedef typename TSourceImage::RegionType RegionType; + + const RegionType bufferedRegion = outputPtr->GetRequestedRegion(); + // Allocate the output - outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() ); + outputPtr->SetBufferedRegion( bufferedRegion ); outputPtr->Allocate(); // Create an iterator to walk the boundary point image @@ -243,10 +246,9 @@ BloxBoundaryPointImageToBloxBoundaryProfileImageFilter< TSourceImage > // Count number of iterated boundary points unsigned int bpCount = 0; -//////////////////////////////////////////////// -//////////OPTIMIZER INITIALIZATION////////////// -//////////////////////////////////////////////// - + //////////////////////////////////////////////// + //////////OPTIMIZER INITIALIZATION////////////// + //////////////////////////////////////////////// // Iterate through the bp image (all pixels) and look for boundary profiles for ( bpIt.GoToBegin(); !bpIt.IsAtEnd(); ++bpIt) @@ -351,10 +353,10 @@ BloxBoundaryPointImageToBloxBoundaryProfileImageFilter< TSourceImage > int binNumber = (int) (vectorRatio * m_NumberOfBins); double binJitter = (vectorRatio * m_NumberOfBins) - binNumber; - typename TSourceImage::PixelType sourcePixelValue; + typedef typename TSourceImage::PixelType SourcePixelType; // Get the value of the pixel - sourcePixelValue = sourcePtr->GetPixel(sfi.GetIndex()); + const SourcePixelType sourcePixelValue = sfi.Get(); // Gaussian Splat - Project Gaussian weighted pixel intensities along major axis of ellipsoid (sampling region) if(m_SplatMethod == 0) @@ -362,13 +364,13 @@ BloxBoundaryPointImageToBloxBoundaryProfileImageFilter< TSourceImage > double a = 2; double b = .6; // for weight .5 - this->AddSplatToAccumulatorAndNormalizer(binNumber-1, double(a*vcl_exp(-.5*(pow((binJitter+1)/b, 2)))), + this->AddSplatToAccumulatorAndNormalizer(binNumber-1, double(a*vcl_exp(-.5*(vcl_pow((binJitter+1)/b, 2)))), sourcePixelValue); - this->AddSplatToAccumulatorAndNormalizer(binNumber, double(a*vcl_exp(-.5*(pow((binJitter )/b, 2)))), + this->AddSplatToAccumulatorAndNormalizer(binNumber, double(a*vcl_exp(-.5*(vcl_pow((binJitter )/b, 2)))), sourcePixelValue); - this->AddSplatToAccumulatorAndNormalizer(binNumber+1, double(a*vcl_exp(-.5*(pow((binJitter-1)/b, 2)))), + this->AddSplatToAccumulatorAndNormalizer(binNumber+1, double(a*vcl_exp(-.5*(vcl_pow((binJitter-1)/b, 2)))), sourcePixelValue); - this->AddSplatToAccumulatorAndNormalizer(binNumber+2, double(a*vcl_exp(-.5*(pow((binJitter-2)/b, 2)))), + this->AddSplatToAccumulatorAndNormalizer(binNumber+2, double(a*vcl_exp(-.5*(vcl_pow((binJitter-2)/b, 2)))), sourcePixelValue); } @@ -416,7 +418,9 @@ BloxBoundaryPointImageToBloxBoundaryProfileImageFilter< TSourceImage > PositionType optimalBoundaryLocation; for(unsigned int i = 0; i < NDimensions; i++) + { optimalBoundaryLocation[i] = boundaryProfile->GetOptimalBoundaryLocation()[i]; + } // Figure out the data space coordinates of the optimal boundary location IndexType boundaryProfilePosition; @@ -424,10 +428,20 @@ BloxBoundaryPointImageToBloxBoundaryProfileImageFilter< TSourceImage > // Transform optimal boundary location to an index outputPtr->TransformPhysicalPointToIndex(optimalBoundaryLocation, boundaryProfilePosition); +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + if( bufferedRegion.IsInside( boundaryProfilePosition ) ) + { + // Store the new boundary profile in the correct spot in output image + outputPtr->GetPixel(boundaryProfilePosition).push_back(boundaryProfile); + m_NumBoundaryProfiles++; + } +#else // Store the new boundary profile in the correct spot in output image outputPtr->GetPixel(boundaryProfilePosition).push_back(boundaryProfile); m_NumBoundaryProfiles++; +#endif + } bpCount++; } diff --git a/Utilities/ITK/Code/BasicFilters/itkBoundedReciprocalImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkBoundedReciprocalImageFilter.h index 85babfeb87..c19631bcb9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBoundedReciprocalImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkBoundedReciprocalImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBoundedReciprocalImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-09 16:20:18 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,7 +49,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( 1.0 / ( 1.0 + static_cast<double>(A) ) ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.h index 3bd9a0dbb3..ba2a48e157 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCannyEdgeDetectionImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-17 14:49:46 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-25 12:27:15 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -129,6 +129,7 @@ public: /** Typedef to describe the output image region type. */ typedef typename TOutputImage::RegionType OutputImageRegionType; + typedef typename TInputImage::RegionType InputImageRegionType; /** Run-time type information (and related methods). */ itkTypeMacro(CannyEdgeDetectionImageFilter, ImageToImageFilter); @@ -144,9 +145,9 @@ public: /** Standard get/set macros for filter parameters. */ itkSetMacro(Variance, ArrayType); - itkGetMacro(Variance, const ArrayType); + itkGetConstMacro(Variance, const ArrayType); itkSetMacro(MaximumError, ArrayType); - itkGetMacro(MaximumError, const ArrayType); + itkGetConstMacro(MaximumError, const ArrayType); /** Set/Get the Variance parameter used by the Gaussian smoothing filter in this algorithm */ @@ -195,14 +196,14 @@ public: ///* Set the Threshold value for detected edges. */ itkSetMacro(UpperThreshold, OutputImagePixelType ); - itkGetMacro(UpperThreshold, OutputImagePixelType); + itkGetConstMacro(UpperThreshold, OutputImagePixelType); itkSetMacro(LowerThreshold, OutputImagePixelType ); - itkGetMacro(LowerThreshold, OutputImagePixelType); + itkGetConstMacro(LowerThreshold, OutputImagePixelType); /* Set the Thresholdvalue for detected edges. */ itkSetMacro(OutsideValue, OutputImagePixelType); - itkGetMacro(OutsideValue, OutputImagePixelType); + itkGetConstMacro(OutsideValue, OutputImagePixelType); OutputImageType * GetNonMaximumSuppressionImage() { @@ -263,9 +264,6 @@ private: /** Edge linking funciton */ void FollowEdge(IndexType index); - /** Check if the index is in bounds or not */ - bool InBounds(IndexType index); - /** Calculate the second derivative of the smoothed image, it writes the * result to m_UpdateBuffer using the ThreadedCompute2ndDerivative() method diff --git a/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.txx index 71a633bf30..700d86e5c4 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCannyEdgeDetectionImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:26 $ - Version: $Revision: 1.53 $ + Date: $Date: 2009-04-08 16:31:08 $ + Version: $Revision: 1.54 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -115,6 +115,7 @@ CannyEdgeDetectionImageFilter<TInputImage,TOutputImage> } //Set the kernel size. + // fix me this needs to be based on the variance of the gaussian filter unsigned long radius = 1; // get a copy of the input requested region (should equal the output @@ -376,7 +377,8 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > float value; ListNodeType *node; - + +// fix me ImageRegionIterator<TOutputImage> oit( input, input->GetRequestedRegion() ); oit.GoToBegin(); @@ -415,16 +417,18 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > // gradients of the image. HysteresisThresholding of this image should give // the Canny output. typename OutputImageType::Pointer input = m_MultiplyImageFilter->GetOutput(); + InputImageRegionType inputRegion = input->GetRequestedRegion(); IndexType nIndex; IndexType cIndex; ListNodeType * node; //assign iterator radius - Size<ImageDimension> radius; radius.Fill(1); + Size<ImageDimension> radius; + radius.Fill(1); ConstNeighborhoodIterator<TOutputImage> oit(radius, - input, input->GetRequestedRegion()); + input, input->GetRequestedRegion()); ImageRegionIteratorWithIndex<TOutputImage> uit( this->GetOutput(), this->GetOutput()->GetRequestedRegion()); @@ -453,7 +457,7 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > { nIndex = oit.GetIndex(i); uit.SetIndex(nIndex); - if(InBounds(nIndex)) + if(inputRegion.IsInside(nIndex)) { if(oit.GetPixel(i) > m_LowerThreshold && uit.Value() != 1 ) { @@ -469,26 +473,6 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > } } -template< class TInputImage, class TOutputImage > -bool -CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > -::InBounds(IndexType index) -{ - typename InputImageType::ConstPointer input = this->GetInput(); - typename InputImageType::SizeType sz; - sz = (input->GetRequestedRegion()).GetSize(); - - for(unsigned int i = 0; i < ImageDimension; i++) - { - if(index[i] < 0 || - index[i] >= static_cast<typename IndexType::IndexValueType>(sz[i])) - { - return false; - } - } - return true; - -} template< class TInputImage, class TOutputImage > void diff --git a/Utilities/ITK/Code/BasicFilters/itkCastImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkCastImageFilter.h index c1b1d817d6..870e0e7d95 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCastImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkCastImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCastImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-08 13:54:09 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,7 +58,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( A ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkChainCodeToFourierSeriesPathFilter.txx b/Utilities/ITK/Code/BasicFilters/itkChainCodeToFourierSeriesPathFilter.txx index 443f885352..b6ace2c9e5 100644 --- a/Utilities/ITK/Code/BasicFilters/itkChainCodeToFourierSeriesPathFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkChainCodeToFourierSeriesPathFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkChainCodeToFourierSeriesPathFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:26 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-06 00:05:53 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -89,8 +89,8 @@ ChainCodeToFourierSeriesPathFilter<TInputChainCodePath,TOutputFourierSeriesPath> for( int d=0; d<dimension; d++ ) indexVector[d] = index[d]; - cosCoefficient += indexVector * (cos(theta)/numSteps); - sinCoefficient += indexVector * (sin(theta)/numSteps); + cosCoefficient += indexVector * (vcl_cos(theta)/numSteps); + sinCoefficient += indexVector * (vcl_sin(theta)/numSteps); } outputPtr->AddHarmonic( cosCoefficient, sinCoefficient ); diff --git a/Utilities/ITK/Code/BasicFilters/itkChangeInformationImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkChangeInformationImageFilter.h index 456794ef7c..a30621cbc2 100644 --- a/Utilities/ITK/Code/BasicFilters/itkChangeInformationImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkChangeInformationImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkChangeInformationImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:26 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:27:17 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -106,7 +106,7 @@ public: itkSetMacro(UseReferenceImage, bool); itkBooleanMacro(UseReferenceImage); - itkGetMacro(UseReferenceImage, bool); + itkGetConstMacro(UseReferenceImage, bool); /** Specify a new data spacing explicitly. The default is to * use the spacing of the Input, or of the ReferenceImage @@ -164,7 +164,7 @@ public: itkSetMacro(ChangeSpacing, bool); itkBooleanMacro(ChangeSpacing); - itkGetMacro(ChangeSpacing, bool); + itkGetConstMacro(ChangeSpacing, bool); /** Change the Origin of the output image. If false, the output * image origin will be set to the input image origin. If true, the @@ -174,7 +174,7 @@ public: itkSetMacro(ChangeOrigin, bool); itkBooleanMacro(ChangeOrigin); - itkGetMacro(ChangeOrigin, bool); + itkGetConstMacro(ChangeOrigin, bool); /** Change the direction of the output image. If false, the output * image direction will be set to the input image direction. If true, the @@ -184,20 +184,20 @@ public: itkSetMacro(ChangeDirection, bool); itkBooleanMacro(ChangeDirection); - itkGetMacro(ChangeDirection, bool); + itkGetConstMacro(ChangeDirection, bool); /** Change the BufferedRegion of the output image. */ itkSetMacro(ChangeRegion, bool); itkBooleanMacro(ChangeRegion); - itkGetMacro(ChangeRegion, bool); + itkGetConstMacro(ChangeRegion, bool); /** Set the Origin of the output so that image coordinate (0,0,0) * lies at the Center of the Image. This will override * SetOutputOrigin. */ itkSetMacro(CenterImage, bool); itkBooleanMacro(CenterImage); - itkGetMacro(CenterImage, bool); + itkGetConstMacro(CenterImage, bool); /** Apply changes to the output image information. */ virtual void GenerateOutputInformation(); diff --git a/Utilities/ITK/Code/BasicFilters/itkChangeLabelImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkChangeLabelImageFilter.h index c2cb8cbadf..b6ce0f3f6c 100755 --- a/Utilities/ITK/Code/BasicFilters/itkChangeLabelImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkChangeLabelImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkChangeLabelImageFilter.h,v $ Language: C++ - Date: $Date: 2008-02-13 20:52:34 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-30 11:32:14 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -90,11 +90,12 @@ public: m_ChangeMap.clear(); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { - if ( m_ChangeMap.find(A) != m_ChangeMap.end() ) + const typename ChangeMapType::const_iterator it = m_ChangeMap.find(A); + if ( it != m_ChangeMap.end() ) { - return m_ChangeMap[A]; + return it->second; } return A; } diff --git a/Utilities/ITK/Code/BasicFilters/itkComplexToImaginaryImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkComplexToImaginaryImageFilter.h index 4387a236b2..87177f1766 100644 --- a/Utilities/ITK/Code/BasicFilters/itkComplexToImaginaryImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkComplexToImaginaryImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkComplexToImaginaryImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:27 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return (TOutput)( A.imag() ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkComplexToModulusImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkComplexToModulusImageFilter.h index c3737be928..94a3e1ad45 100644 --- a/Utilities/ITK/Code/BasicFilters/itkComplexToModulusImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkComplexToModulusImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkComplexToModulusImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:27 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return (TOutput)( vcl_sqrt(A.real() * A.real() + A.imag() * A.imag() ) ); diff --git a/Utilities/ITK/Code/BasicFilters/itkComplexToPhaseImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkComplexToPhaseImageFilter.h index b19801b4c1..ad8134d155 100644 --- a/Utilities/ITK/Code/BasicFilters/itkComplexToPhaseImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkComplexToPhaseImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkComplexToPhaseImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:27 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return (TOutput)( vcl_atan2(A.imag(), A.real() ) ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkComplexToRealImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkComplexToRealImageFilter.h index 7c22aed608..d09669836e 100644 --- a/Utilities/ITK/Code/BasicFilters/itkComplexToRealImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkComplexToRealImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkComplexToRealImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:27 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return (TOutput)( A.real() ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkCompose2DCovariantVectorImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkCompose2DCovariantVectorImageFilter.h index f43d5a65bf..ebb6fa6a98 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCompose2DCovariantVectorImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkCompose2DCovariantVectorImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCompose2DCovariantVectorImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-14 18:39:05 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,7 +41,7 @@ public: return !(*this != other); } inline OutputType operator()( const TInput & s1, - const TInput & s2 ) + const TInput & s2 ) const { OutputType v; v[0] = s1; diff --git a/Utilities/ITK/Code/BasicFilters/itkCompose2DVectorImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkCompose2DVectorImageFilter.h index 237da58808..c46efa22be 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCompose2DVectorImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkCompose2DVectorImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCompose2DVectorImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-14 18:39:05 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,7 +41,7 @@ public: return !(*this != other); } inline OutputType operator()( const TInput & s1, - const TInput & s2 ) + const TInput & s2 ) const { OutputType v; v[0] = s1; diff --git a/Utilities/ITK/Code/BasicFilters/itkCompose3DCovariantVectorImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkCompose3DCovariantVectorImageFilter.h index 2d407041b7..4e5d9c4007 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCompose3DCovariantVectorImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkCompose3DCovariantVectorImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCompose3DCovariantVectorImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-14 18:39:05 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,7 +42,7 @@ public: } inline OutputType operator()( const TInput & s1, const TInput & s2, - const TInput & s3) + const TInput & s3) const { OutputType v; v[0] = s1; diff --git a/Utilities/ITK/Code/BasicFilters/itkCompose3DVectorImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkCompose3DVectorImageFilter.h index 4572513f9d..9c801f3f4d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCompose3DVectorImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkCompose3DVectorImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCompose3DVectorImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-14 18:39:05 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,7 +42,7 @@ public: } inline OutputType operator()( const TInput & s1, const TInput & s2, - const TInput & s3) + const TInput & s3) const { OutputType v; v[0] = s1; diff --git a/Utilities/ITK/Code/BasicFilters/itkComposeRGBImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkComposeRGBImageFilter.h index c17cc792af..e690ff4e0e 100644 --- a/Utilities/ITK/Code/BasicFilters/itkComposeRGBImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkComposeRGBImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkComposeRGBImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-14 18:39:05 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,7 +42,7 @@ public: } inline OutputType operator()( const TInput & R, const TInput & G, - const TInput & B) + const TInput & B) const { OutputType rgbPixel; rgbPixel.Set( R, G, B); diff --git a/Utilities/ITK/Code/BasicFilters/itkConfidenceConnectedImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkConfidenceConnectedImageFilter.h index 320e920463..15b2987299 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConfidenceConnectedImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkConfidenceConnectedImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConfidenceConnectedImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:27 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-25 12:27:19 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -92,37 +92,26 @@ public: void PrintSelf ( std::ostream& os, Indent indent ) const; /** Set seed point. This method is deprecated, please use AddSeed() */ - void SetSeed(const IndexType & seed) - { - m_Seeds.clear(); - this->AddSeed( seed ); - } + void SetSeed(const IndexType & seed); /** Clear all the seeds. */ - void ClearSeeds() - { - m_Seeds.clear(); - } + void ClearSeeds(); /** Add seed point. */ - void AddSeed(const IndexType & seed) - { - m_Seeds.push_back( seed ); - this->Modified(); - } + void AddSeed(const IndexType & seed); /** Set/Get the multiplier to define the confidence interval. Multiplier * can be anything greater than zero. A typical value is 2.5 */ itkSetMacro(Multiplier, double); - itkGetMacro(Multiplier, double); + itkGetConstMacro(Multiplier, double); /** Set/Get the number of iterations */ itkSetMacro(NumberOfIterations, unsigned int); - itkGetMacro(NumberOfIterations, unsigned int); + itkGetConstMacro(NumberOfIterations, unsigned int); /** Set/Get value to replace thresholded pixels */ itkSetMacro(ReplaceValue, OutputImagePixelType); - itkGetMacro(ReplaceValue, OutputImagePixelType); + itkGetConstMacro(ReplaceValue, OutputImagePixelType); /** Get/Set the radius of the neighborhood over which the statistics are evaluated */ diff --git a/Utilities/ITK/Code/BasicFilters/itkConfidenceConnectedImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkConfidenceConnectedImageFilter.txx index dcdc6933a5..7b7588bff3 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConfidenceConnectedImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkConfidenceConnectedImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConfidenceConnectedImageFilter.txx,v $ Language: C++ -Date: $Date: 2008-10-13 18:54:27 $ -Version: $Revision: 1.36 $ +Date: $Date: 2009-04-21 12:29:35 $ +Version: $Revision: 1.37 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,6 +47,36 @@ ConfidenceConnectedImageFilter<TInputImage, TOutputImage> m_Variance = NumericTraits< InputRealType >::Zero; } +template <class TInputImage, class TOutputImage> +void +ConfidenceConnectedImageFilter<TInputImage, TOutputImage> +::SetSeed(const IndexType & seed) +{ + this->m_Seeds.clear(); + this->AddSeed( seed ); +} + +template <class TInputImage, class TOutputImage> +void +ConfidenceConnectedImageFilter<TInputImage, TOutputImage> +::ClearSeeds() +{ + if( this->m_Seeds.size() > 0 ) + { + this->m_Seeds.clear(); + this->Modified(); + } +} + +template <class TInputImage, class TOutputImage> +void +ConfidenceConnectedImageFilter<TInputImage, TOutputImage> +::AddSeed(const IndexType & seed) +{ + this->m_Seeds.push_back( seed ); + this->Modified(); +} + /** * Standard PrintSelf method. */ diff --git a/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.h index 8e58fcdb94..6afa9ff67b 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConnectedComponentImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-01 15:16:46 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-27 22:58:48 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -126,8 +126,12 @@ public: itkGetConstReferenceMacro(FullyConnected, bool); itkBooleanMacro(FullyConnected); + + /** Type used as identifier of the different component labels. */ + typedef unsigned long int LabelType; + // only set after completion - itkGetConstReferenceMacro(ObjectCount, unsigned long); + itkGetConstReferenceMacro(ObjectCount, LabelType); // Concept checking -- input and output dimensions must be the same itkConceptMacro(SameDimension, @@ -148,7 +152,7 @@ public: /** */ itkSetMacro(BackgroundValue, OutputImagePixelType); - itkGetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); protected: ConnectedComponentImageFilter() @@ -182,7 +186,7 @@ protected: bool m_FullyConnected; private: - unsigned long m_ObjectCount; + LabelType m_ObjectCount; OutputImagePixelType m_BackgroundValue; // some additional types @@ -193,9 +197,9 @@ private: { public: // run length information - may be a more type safe way of doing this - long int length; - typename InputImageType::IndexType where; // Index of the start of the run - unsigned long int label; // the initial label of the run + long int length; + typename InputImageType::IndexType where; // Index of the start of the run + LabelType label; // the initial label of the run }; typedef std::vector<runLength> lineEncoding; @@ -206,17 +210,18 @@ private: typedef std::vector<long> OffsetVec; // the types to support union-find operations - typedef std::vector<unsigned long int> UnionFindType; + typedef std::vector<LabelType> UnionFindType; UnionFindType m_UnionFind; UnionFindType m_Consecutive; + // functions to support union-find operations void InitUnion(const unsigned long int size) { m_UnionFind = UnionFindType(size + 1); } void InsertSet(const unsigned long int label); - unsigned long int LookupSet(const unsigned long int label); - void LinkLabels(const unsigned long int lab1, const unsigned long int lab2); + unsigned long int LookupSet(const LabelType label); + void LinkLabels(const LabelType lab1, const LabelType lab2); unsigned long int CreateConsecutive(); ////////////////// bool CheckNeighbors(const OutputIndexType &A, diff --git a/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.txx index 61d1d64227..c719d8332f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConnectedComponentImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-01-14 14:25:11 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-05-08 22:33:59 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -335,18 +335,28 @@ ConnectedComponentImageFilter< TInputImage, TOutputImage, TMaskImage> if( threadId == 0 ) { - unsigned long int totalLabs = CreateConsecutive(); - m_ObjectCount = totalLabs; - // check for overflow exception here - if( totalLabs > static_cast<unsigned long int>( + m_ObjectCount = CreateConsecutive(); + } + + this->Wait(); + + + // check for overflow exception here + if( m_ObjectCount > static_cast<unsigned long int>( NumericTraits<OutputPixelType>::max() ) ) + { + if( threadId == 0 ) { + // main thread throw the exception itkExceptionMacro( << "Number of objects greater than maximum of output pixel type " ); } + else + { + // other threads just return + return; + } } - this->Wait(); - // create the output // A more complex version that is intended to minimize the number of @@ -597,7 +607,11 @@ ConnectedComponentImageFilter< TInputImage, TOutputImage, TMaskImage> ::CreateConsecutive() { m_Consecutive = UnionFindType(m_UnionFind.size()); - m_Consecutive[m_BackgroundValue] = m_BackgroundValue; + + const LabelType background = static_cast<LabelType>( this->m_BackgroundValue ); + + m_Consecutive[background] = background; + unsigned long int CLab = 0; unsigned long int count = 0; for (unsigned long int I = 1; I < m_UnionFind.size(); I++) @@ -620,7 +634,7 @@ ConnectedComponentImageFilter< TInputImage, TOutputImage, TMaskImage> template< class TInputImage, class TOutputImage, class TMaskImage > unsigned long int ConnectedComponentImageFilter< TInputImage, TOutputImage, TMaskImage> -::LookupSet(const unsigned long int label) +::LookupSet(const LabelType label) { // recursively set the equivalence if necessary if (label != m_UnionFind[label]) @@ -633,7 +647,7 @@ ConnectedComponentImageFilter< TInputImage, TOutputImage, TMaskImage> template< class TInputImage, class TOutputImage, class TMaskImage > void ConnectedComponentImageFilter< TInputImage, TOutputImage, TMaskImage> -::LinkLabels(const unsigned long int lab1, const unsigned long int lab2) +::LinkLabels(const LabelType lab1, const LabelType lab2) { unsigned long E1 = this->LookupSet(lab1); unsigned long E2 = this->LookupSet(lab2); diff --git a/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.h index 4750a4e6ae..e4b5eef860 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConnectedThresholdImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-16 21:17:18 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-25 12:27:20 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -67,33 +67,17 @@ public: /** Set seed point. */ - void SetSeed ( const IndexType & seed ) - { - this->ClearSeeds(); - this->AddSeed ( seed ); - } - void AddSeed(const IndexType & seed) - { - m_SeedList.push_back ( seed ); - this->Modified(); - } + void SetSeed ( const IndexType & seed ); + void AddSeed(const IndexType & seed); /** Clear the seed list. */ - void ClearSeeds () - { - if (m_SeedList.size() > 0) - { - m_SeedList.clear(); - this->Modified(); - } - } - + void ClearSeeds (); /** Set/Get value to replace thresholded pixels. Pixels that lie * * within Lower and Upper (inclusive) will be replaced with this * value. The default is 1. */ itkSetMacro(ReplaceValue, OutputImagePixelType); - itkGetMacro(ReplaceValue, OutputImagePixelType); + itkGetConstMacro(ReplaceValue, OutputImagePixelType); /** Type of DataObjects to use for scalar inputs */ typedef SimpleDataObjectDecorator<InputImagePixelType> InputPixelObjectType; @@ -146,7 +130,7 @@ public: /** Type of connectivity to use (fully connected OR 4(2D), 6(3D), * 2*N(ND) connectivity) */ itkSetMacro( Connectivity, ConnectivityEnumType ); - itkGetMacro( Connectivity, ConnectivityEnumType ); + itkGetConstMacro( Connectivity, ConnectivityEnumType ); #endif protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.txx index 5299701c6b..88b735583c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConnectedThresholdImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-17 11:02:28 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-04-21 12:29:36 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -50,6 +50,36 @@ ConnectedThresholdImageFilter<TInputImage, TOutputImage> this->ProcessObject::SetNthInput( 2, upper ); } +template <class TInputImage, class TOutputImage> +void +ConnectedThresholdImageFilter<TInputImage, TOutputImage> +::SetSeed ( const IndexType & seed ) +{ + this->ClearSeeds(); + this->AddSeed ( seed ); +} + +template <class TInputImage, class TOutputImage> +void +ConnectedThresholdImageFilter<TInputImage, TOutputImage> +::AddSeed(const IndexType & seed) +{ + this->m_SeedList.push_back ( seed ); + this->Modified(); +} + +template <class TInputImage, class TOutputImage> +void +ConnectedThresholdImageFilter<TInputImage, TOutputImage> +::ClearSeeds () +{ + if( m_SeedList.size() > 0 ) + { + this->m_SeedList.clear(); + this->Modified(); + } +} + /** * Standard PrintSelf method. */ diff --git a/Utilities/ITK/Code/BasicFilters/itkConstantPadImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkConstantPadImageFilter.h index 66de370d35..578f6f7ce0 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConstantPadImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkConstantPadImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConstantPadImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:27 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-25 12:27:20 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -74,7 +74,7 @@ public: /** Set/Get the pad value. Default is Zero. */ itkSetMacro(Constant, OutputImagePixelType); - itkGetMacro(Constant, OutputImagePixelType); + itkGetConstMacro(Constant, OutputImagePixelType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkConstrainedValueAdditionImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkConstrainedValueAdditionImageFilter.h index e4756321a2..4c79f5c9a0 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConstrainedValueAdditionImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkConstrainedValueAdditionImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConstrainedValueAdditionImageFilter.h,v $ Language: C++ - Date: $Date: 2007-09-27 11:36:40 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:10 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -68,7 +68,7 @@ public: return !(*this != other); } inline TOutput operator()( const TInput1 & A, - const TInput2 & B) + const TInput2 & B) const { const double dA = static_cast<double>( A ); const double dB = static_cast<double>( B ); diff --git a/Utilities/ITK/Code/BasicFilters/itkConstrainedValueDifferenceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkConstrainedValueDifferenceImageFilter.h index ebe8795e82..de65f3abf7 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConstrainedValueDifferenceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkConstrainedValueDifferenceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConstrainedValueDifferenceImageFilter.h,v $ Language: C++ - Date: $Date: 2007-09-27 11:36:40 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:11 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -68,7 +68,7 @@ public: return !(*this != other); } inline TOutput operator()( const TInput1 & A, - const TInput2 & B) + const TInput2 & B) const { const double dA = static_cast<double>( A ); const double dB = static_cast<double>( B ); diff --git a/Utilities/ITK/Code/BasicFilters/itkContourDirectedMeanDistanceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkContourDirectedMeanDistanceImageFilter.h index ee1b319d6c..15fa7d3c92 100755 --- a/Utilities/ITK/Code/BasicFilters/itkContourDirectedMeanDistanceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkContourDirectedMeanDistanceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkContourDirectedMeanDistanceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-24 08:14:12 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:27:20 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -118,7 +118,7 @@ public: const InputImage2Type * GetInput2(void); /** Return the computed directed Mean distance. */ - itkGetMacro(ContourDirectedMeanDistance,RealType); + itkGetConstMacro(ContourDirectedMeanDistance,RealType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkContourMeanDistanceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkContourMeanDistanceImageFilter.h index 4661b09672..9f01692f06 100755 --- a/Utilities/ITK/Code/BasicFilters/itkContourMeanDistanceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkContourMeanDistanceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkContourMeanDistanceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:27 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-25 12:27:20 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -118,7 +118,7 @@ public: const InputImage2Type * GetInput2(void); /** Return the computed Mean distance. */ - itkGetMacro(MeanDistance,RealType); + itkGetConstMacro(MeanDistance,RealType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkCosImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkCosImageFilter.h index b01a60c3b8..db6ddea5a1 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCosImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkCosImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCosImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:27 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-06 00:05:54 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -57,9 +57,9 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { - return static_cast<TOutput>(cos( static_cast<double>(A)) ); + return static_cast<TOutput>(vcl_cos( static_cast<double>(A)) ); } }; diff --git a/Utilities/ITK/Code/BasicFilters/itkCropImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkCropImageFilter.h index ff60d13b5a..08f36c8880 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCropImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkCropImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCropImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:28 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:27:20 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -74,9 +74,9 @@ public: /** Set/Get the cropping sizes for the upper and lower boundaries. */ itkSetMacro(UpperBoundaryCropSize, SizeType); - itkGetMacro(UpperBoundaryCropSize, SizeType); + itkGetConstMacro(UpperBoundaryCropSize, SizeType); itkSetMacro(LowerBoundaryCropSize, SizeType); - itkGetMacro(LowerBoundaryCropSize, SizeType); + itkGetConstMacro(LowerBoundaryCropSize, SizeType); void SetBoundaryCropSize(const SizeType & s) { diff --git a/Utilities/ITK/Code/BasicFilters/itkCurvatureNDAnisotropicDiffusionFunction.txx b/Utilities/ITK/Code/BasicFilters/itkCurvatureNDAnisotropicDiffusionFunction.txx index e94098b83e..f9e32de542 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCurvatureNDAnisotropicDiffusionFunction.txx +++ b/Utilities/ITK/Code/BasicFilters/itkCurvatureNDAnisotropicDiffusionFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCurvatureNDAnisotropicDiffusionFunction.txx,v $ Language: C++ - Date: $Date: 2008-10-13 18:54:28 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-06 11:15:07 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -121,8 +121,8 @@ CurvatureNDAnisotropicDiffusionFunction<TImage> grad_mag_sq_d += 0.25f * (dx[j]+dx_dim) * (dx[j]+dx_dim); } } - grad_mag = ::sqrt(m_MIN_NORM + grad_mag_sq); - grad_mag_d = ::sqrt(m_MIN_NORM + grad_mag_sq_d); + grad_mag = vcl_sqrt(m_MIN_NORM + grad_mag_sq); + grad_mag_d = vcl_sqrt(m_MIN_NORM + grad_mag_sq_d); // Conductance Terms if (m_K == 0.0) @@ -132,8 +132,8 @@ CurvatureNDAnisotropicDiffusionFunction<TImage> } else { - Cx = ::exp( grad_mag_sq / m_K ); - Cxd = ::exp( grad_mag_sq_d / m_K ); + Cx = vcl_exp( grad_mag_sq / m_K ); + Cxd = vcl_exp( grad_mag_sq_d / m_K ); } // First order normalized finite-difference conductance products dx_forward_Cn = (dx_forward[i] / grad_mag) * Cx; @@ -162,7 +162,7 @@ CurvatureNDAnisotropicDiffusionFunction<TImage> + vnl_math_sqr( vnl_math_min(dx_forward[i], 0.0) ); } } - return static_cast<PixelType>( ::sqrt(propagation_gradient) * speed ); + return static_cast<PixelType>( vcl_sqrt(propagation_gradient) * speed ); } } // end namespace itk diff --git a/Utilities/ITK/Code/BasicFilters/itkDanielssonDistanceMapImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkDanielssonDistanceMapImageFilter.txx index 5337930e5e..5745946d5b 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDanielssonDistanceMapImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkDanielssonDistanceMapImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDanielssonDistanceMapImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:32 $ - Version: $Revision: 1.38 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.39 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -279,7 +279,7 @@ DanielssonDistanceMapImageFilter<TInputImage,TOutputImage> } else { - dt.Set( static_cast<typename OutputImageType::PixelType>(sqrt( distance )) ); + dt.Set( static_cast<typename OutputImageType::PixelType>(vcl_sqrt( distance )) ); } ++ot; ++ct; diff --git a/Utilities/ITK/Code/BasicFilters/itkDeformationFieldJacobianDeterminantFilter.h b/Utilities/ITK/Code/BasicFilters/itkDeformationFieldJacobianDeterminantFilter.h index ce0a3b9b71..8f8f6f6e86 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDeformationFieldJacobianDeterminantFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDeformationFieldJacobianDeterminantFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformationFieldJacobianDeterminantFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:32 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-05-20 16:21:47 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -136,6 +136,8 @@ protected: virtual ~DeformationFieldJacobianDeterminantFilter() {} private: + DeformationFieldJacobianDeterminantFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented }; } // end namespace itk diff --git a/Utilities/ITK/Code/BasicFilters/itkDerivativeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkDerivativeImageFilter.h index a069148a65..a4f55fa95b 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDerivativeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDerivativeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDerivativeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-25 12:27:20 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -83,9 +83,9 @@ public: /** Standard get/set macros for filter parameters. */ itkSetMacro(Order, unsigned int); - itkGetMacro(Order, unsigned int); + itkGetConstMacro(Order, unsigned int); itkSetMacro(Direction, unsigned int); - itkGetMacro(Direction, unsigned int); + itkGetConstMacro(Direction, unsigned int); /** Use the image spacing information in calculations. Use this option if you * want derivatives in physical space. Default is UseImageSpacingOn. */ @@ -100,7 +100,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input image in its calculations */ itkSetMacro(UseImageSpacing, bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); /** DerivativeImageFilter needs a larger input requested region than * the output requested region (larger in the direction of the diff --git a/Utilities/ITK/Code/BasicFilters/itkDifferenceOfGaussiansGradientImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkDifferenceOfGaussiansGradientImageFilter.h index 96bbe23349..60ec99cb8e 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDifferenceOfGaussiansGradientImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDifferenceOfGaussiansGradientImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDifferenceOfGaussiansGradientImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-25 12:27:21 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,7 +73,7 @@ public: typedef typename TInputImage::RegionType OutputImageRegionType; /** Set/Get the member variables. */ - itkGetMacro(Width, unsigned int); + itkGetConstMacro(Width, unsigned int); itkSetMacro(Width, unsigned int); #ifdef ITK_USE_CONCEPT_CHECKING diff --git a/Utilities/ITK/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilter.h index d8a6626d71..c737c5d9ee 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiffusionTensor3DReconstructionImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-04-25 12:27:21 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -223,7 +223,7 @@ public: * tensor for pixels in the reference image that have a value less than this * threshold. */ itkSetMacro( Threshold, ReferencePixelType ); - itkGetMacro( Threshold, ReferencePixelType ); + itkGetConstMacro( Threshold, ReferencePixelType ); /** diff --git a/Utilities/ITK/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilter.txx index 3dfa78ac42..d9e4c607e7 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkDiffusionTensor3DReconstructionImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiffusionTensor3DReconstructionImageFilter.txx,v $ Language: C++ - Date: $Date: 2006-07-19 15:11:41 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-06 11:51:06 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -158,7 +158,7 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, } else { - B[i] = -log( static_cast<double>(b) / static_cast<double>(b0) )/this->m_BValue; + B[i] = - vcl_log( static_cast<double>(b) / static_cast<double>(b0) )/this->m_BValue; } ++(*gradientItContainer[i]); @@ -258,7 +258,7 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, } else { - B[i] = -log( static_cast<double>(b[gradientind[i]]) / static_cast<double>(b0) ) / this->m_BValue; + B[i] = - vcl_log( static_cast<double>(b[gradientind[i]]) / static_cast<double>(b0) ) / this->m_BValue; } } diff --git a/Utilities/ITK/Code/BasicFilters/itkDilateObjectMorphologyImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkDilateObjectMorphologyImageFilter.h index 1a056a8e67..6fc20d84e1 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDilateObjectMorphologyImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDilateObjectMorphologyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDilateObjectMorphologyImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-28 14:36:18 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,10 +73,13 @@ public: typedef typename Superclass::DefaultBoundaryConditionType DefaultBoundaryConditionType; + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkDilateObjectMorphologyImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkDilateObjectMorphologyImageFilter.txx index 54d1e144db..cbd6b7f5c6 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDilateObjectMorphologyImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkDilateObjectMorphologyImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDilateObjectMorphologyImageFilter.txx,v $ Language: C++ - Date: $Date: 2005-01-16 15:10:52 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-28 14:36:19 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,9 +42,9 @@ DilateObjectMorphologyImageFilter<TInputImage, TOutputImage, TKernel> const KernelIteratorType kernelEnd = kernel.End(); bool valid = true; - for (i=0, kernel_it=kernel.Begin(); kernel_it<kernelEnd; ++kernel_it, ++i) + for( i=0, kernel_it=kernel.Begin(); kernel_it<kernelEnd; ++kernel_it, ++i ) { - if(*kernel_it>0) + if( *kernel_it > NumericTraits< KernelPixelType >::Zero ) { nit.SetPixel(i, this->GetObjectValue(), valid); } diff --git a/Utilities/ITK/Code/BasicFilters/itkDirectedHausdorffDistanceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkDirectedHausdorffDistanceImageFilter.h index c1f5f528f0..d0f003497c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDirectedHausdorffDistanceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDirectedHausdorffDistanceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDirectedHausdorffDistanceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:27:21 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -112,8 +112,8 @@ public: const InputImage2Type * GetInput2(void); /** Return the computed directed Hausdorff distance. */ - itkGetMacro(DirectedHausdorffDistance,RealType); - itkGetMacro(AverageHausdorffDistance,RealType); + itkGetConstMacro(DirectedHausdorffDistance,RealType); + itkGetConstMacro(AverageHausdorffDistance,RealType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkDiscreteGaussianImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkDiscreteGaussianImageFilter.h index 4282fba1fe..507d6880df 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDiscreteGaussianImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDiscreteGaussianImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiscreteGaussianImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.40 $ + Date: $Date: 2009-04-25 12:27:21 $ + Version: $Revision: 1.41 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,17 +95,17 @@ public: * of your image. If UseImageSpacing is false then the units are * pixels. */ itkSetMacro(Variance, ArrayType); - itkGetMacro(Variance, const ArrayType); + itkGetConstMacro(Variance, const ArrayType); /** The algorithm will size the discrete kernel so that the error * resulting from truncation of the kernel is no greater than * MaximumError. The default is 0.01 in each dimension. */ itkSetMacro(MaximumError, ArrayType); - itkGetMacro(MaximumError, const ArrayType); + itkGetConstMacro(MaximumError, const ArrayType); /** Set the kernel to be no wider than MaximumKernelWidth pixels, * even if MaximumError demands it. The default is 32 pixels. */ - itkGetMacro(MaximumKernelWidth, int); + itkGetConstMacro(MaximumKernelWidth, int); itkSetMacro(MaximumKernelWidth, int); /** Set the number of dimensions to smooth. Defaults to the image @@ -113,7 +113,7 @@ public: * the dimensions less than FilterDimensionality. For instance, to * smooth the slices of a volume without smoothing in Z, set the * FilterDimensionality to 2. */ - itkGetMacro(FilterDimensionality, unsigned int); + itkGetConstMacro(FilterDimensionality, unsigned int); itkSetMacro(FilterDimensionality, unsigned int); /** Convenience Set methods for setting all dimensional parameters @@ -182,7 +182,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input image in its calculations */ itkSetMacro(UseImageSpacing, bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); /** DiscreteGaussianImageFilter needs a larger input requested region * than the output requested region (larger by the size of the diff --git a/Utilities/ITK/Code/BasicFilters/itkDisplacementFieldJacobianDeterminantFilter.h b/Utilities/ITK/Code/BasicFilters/itkDisplacementFieldJacobianDeterminantFilter.h index 1840bc96bc..a894ecac5c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDisplacementFieldJacobianDeterminantFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDisplacementFieldJacobianDeterminantFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDisplacementFieldJacobianDeterminantFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-25 12:27:21 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -189,7 +189,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input image in its calculations */ void SetUseImageSpacing(bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); /** Directly Set/Get the array of weights used in the gradient calculations. Note that calling UseImageSpacingOn will clobber these values. */ diff --git a/Utilities/ITK/Code/BasicFilters/itkDivideImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkDivideImageFilter.h index d89e0eb5cd..0c4306eb7c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDivideImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDivideImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDivideImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-01 14:36:15 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -50,7 +50,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { if(B != (TInput2) 0) { diff --git a/Utilities/ITK/Code/BasicFilters/itkDoubleThresholdImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkDoubleThresholdImageFilter.h index 523fb3c8d4..f24e245bef 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDoubleThresholdImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkDoubleThresholdImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDoubleThresholdImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-25 12:27:21 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -80,14 +80,14 @@ public: itkSetMacro(OutsideValue,OutputPixelType); /** Get the "outside" pixel value. */ - itkGetMacro(OutsideValue,OutputPixelType); + itkGetConstMacro(OutsideValue,OutputPixelType); /** Set the "inside" pixel value. The default value * NumericTraits<OutputPixelType>::max() */ itkSetMacro(InsideValue,OutputPixelType); /** Get the "inside" pixel value. */ - itkGetMacro(InsideValue,OutputPixelType); + itkGetConstMacro(InsideValue,OutputPixelType); /** Set the thresholds. Four thresholds should be specified. The * two lower thresholds default to @@ -100,10 +100,10 @@ public: itkSetMacro( Threshold4, InputPixelType ); /** Get the threshold values. */ - itkGetMacro( Threshold1, InputPixelType ); - itkGetMacro( Threshold2, InputPixelType ); - itkGetMacro( Threshold3, InputPixelType ); - itkGetMacro( Threshold4, InputPixelType ); + itkGetConstMacro( Threshold1, InputPixelType ); + itkGetConstMacro( Threshold2, InputPixelType ); + itkGetConstMacro( Threshold3, InputPixelType ); + itkGetConstMacro( Threshold4, InputPixelType ); /** \deprecated * Get the number of iterations used by the geodesic dilation to diff --git a/Utilities/ITK/Code/BasicFilters/itkEdgePotentialImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkEdgePotentialImageFilter.h index 303ec0926a..d28b984fe2 100644 --- a/Utilities/ITK/Code/BasicFilters/itkEdgePotentialImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkEdgePotentialImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEdgePotentialImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-01 14:36:17 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,7 +49,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( vcl_exp(-1.0 * A.GetNorm() ) ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkErodeObjectMorphologyImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkErodeObjectMorphologyImageFilter.h index e79746cf83..819a263292 100644 --- a/Utilities/ITK/Code/BasicFilters/itkErodeObjectMorphologyImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkErodeObjectMorphologyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkErodeObjectMorphologyImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-28 14:36:20 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -90,12 +90,15 @@ public: itkSetMacro(BackgroundValue, PixelType); /** Get the value to be assigned to eroded pixels */ - itkGetMacro(BackgroundValue, PixelType); + itkGetConstMacro(BackgroundValue, PixelType); + + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkExpImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkExpImageFilter.h index 29577b3794..f4f71ca5a4 100644 --- a/Utilities/ITK/Code/BasicFilters/itkExpImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkExpImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExpImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-04-01 14:36:18 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -53,7 +53,7 @@ public: #if defined(_MSC_VER) && (_MSC_VER == 1300) #pragma optimize("g",off) #endif - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return (TOutput)vcl_exp((double)A); } diff --git a/Utilities/ITK/Code/BasicFilters/itkExpNegativeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkExpNegativeImageFilter.h index 25352f83ae..569143d01d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkExpNegativeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkExpNegativeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExpNegativeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-01 14:36:19 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -54,7 +54,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( vcl_exp(- m_Factor * static_cast<double>(A) ) ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkExpandImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkExpandImageFilter.h index c0bfd26239..b2eaac952d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkExpandImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkExpandImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExpandImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:33 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-05-19 18:31:17 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,10 +40,17 @@ namespace itk * SetInterpolator(). Note that the input interpolator must derive * from base class InterpolateImageFunction. * - * When the LargestPossibleRegion is requested, the output image will - * contain padding at the upper edge of each dimension. The width - * of padding in the i'th dimension is (ExpandFactors[i] - 1). Users can - * specify the padding value used by setting the EdgePaddingValue. + * \warning: The following is valid only when the flag + * ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY is OFF. + * When the LargestPossibleRegion is requested, the output image will contain + * padding at the upper edge of each dimension. The width of padding in the + * i'th dimension is (ExpandFactors[i] - 1). Users can specify the padding + * value used by setting the EdgePaddingValue. + * + * \warning: The following is valid only when the flag + * ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY is ON + * The output image will not contain any padding, and therefore the + * EdgePaddingValue will not be used. * * This filter will produce an output with different pixel spacing * that its input image such that: @@ -126,7 +133,7 @@ public: itkSetMacro( EdgePaddingValue, OutputPixelType ); /** Get the edge padding value */ - itkGetMacro( EdgePaddingValue, OutputPixelType ); + itkGetConstMacro( EdgePaddingValue, OutputPixelType ); /** ExpandImageFilter produces an image which is a different resolution and * with a different pixel spacing than its input image. As such, diff --git a/Utilities/ITK/Code/BasicFilters/itkExpandImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkExpandImageFilter.txx index 34e8f5a2f2..3609a5ed0c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkExpandImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkExpandImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExpandImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:34 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-05-19 18:31:17 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -198,8 +198,11 @@ ExpandImageFilter<TInputImage,TOutputImage> // clamped to be minimum for 1. for( unsigned int j = 0; j < ImageDimension; j++ ) { - inputIndex[j] = (double) outputIndex[j] / - (double) m_ExpandFactors[j]; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + inputIndex[j] = ( (double) outputIndex[j] + 0.5 ) / (double) m_ExpandFactors[j] - 0.5; +#else + inputIndex[j] = (double) outputIndex[j] / (double) m_ExpandFactors[j]; +#endif } // interpolate value and write to output @@ -308,19 +311,39 @@ ExpandImageFilter<TInputImage,TOutputImage> = inputPtr->GetLargestPossibleRegion().GetSize(); const typename TInputImage::IndexType& inputStartIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); + const typename TInputImage::PointType& + inputOrigin = inputPtr->GetOrigin(); typename TOutputImage::SpacingType outputSpacing; typename TOutputImage::SizeType outputSize; typename TOutputImage::IndexType outputStartIndex; + typename TOutputImage::PointType outputOrigin; + + typename TInputImage::SpacingType inputOriginShift; for (unsigned int i = 0; i < TOutputImage::ImageDimension; i++) { outputSpacing[i] = inputSpacing[i] / (float) m_ExpandFactors[i]; outputSize[i] = inputSize[i] * (unsigned long) m_ExpandFactors[i]; outputStartIndex[i] = inputStartIndex[i] * (long) m_ExpandFactors[i]; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + const double fraction = (double)(m_ExpandFactors[i] - 1) / (double)m_ExpandFactors[i]; + inputOriginShift[i] = - ( inputSpacing[i] / 2.0 ) * fraction; +#endif } +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + const typename TInputImage::DirectionType inputDirection = inputPtr->GetDirection(); + const typename TOutputImage::SpacingType outputOriginShift = inputDirection * inputOriginShift; + + outputOrigin = inputOrigin + outputOriginShift; +#else + outputOrigin = inputOrigin; +#endif + + outputPtr->SetSpacing( outputSpacing ); + outputPtr->SetOrigin( outputOrigin ); typename TOutputImage::RegionType outputLargestPossibleRegion; outputLargestPossibleRegion.SetSize( outputSize ); diff --git a/Utilities/ITK/Code/BasicFilters/itkExtractImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkExtractImageFilter.h index e4171e0c67..d074431dbe 100644 --- a/Utilities/ITK/Code/BasicFilters/itkExtractImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkExtractImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExtractImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:20:34 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-25 12:27:21 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -110,7 +110,7 @@ public: * 'c' dimensions less than the input image, where c = # of * ExtractionRegion.Size = 0. */ void SetExtractionRegion(InputImageRegionType extractRegion); - itkGetMacro(ExtractionRegion, InputImageRegionType); + itkGetConstMacro(ExtractionRegion, InputImageRegionType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkFlipImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkFlipImageFilter.h index bb2a0a2bfa..4922575321 100644 --- a/Utilities/ITK/Code/BasicFilters/itkFlipImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkFlipImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFlipImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-25 12:27:21 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,14 +81,14 @@ public: /** Set/Get the axis to be flipped. The image is flipped along axes * for which array[i] is true. */ itkSetMacro( FlipAxes, FlipAxesArrayType ); - itkGetMacro( FlipAxes, FlipAxesArrayType ); + itkGetConstMacro( FlipAxes, FlipAxesArrayType ); /** Controls how the output origin is computed. If FlipAboutOrigin is * "on", the flip will occur about the origin of the axis, otherwise, * the flip will occur about the center of the axis. */ itkBooleanMacro(FlipAboutOrigin); - itkGetMacro(FlipAboutOrigin, bool); + itkGetConstMacro(FlipAboutOrigin, bool); itkSetMacro(FlipAboutOrigin, bool); /** FlipImageFilter produces an image with different origin and diff --git a/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.h b/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.h index 99d11696ef..fe316a1259 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.h +++ b/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianImageSource.h,v $ Language: C++ - Date: $Date: 2008-12-17 18:56:53 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-05-12 17:22:43 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -113,13 +113,13 @@ public: /** Gets and sets for gaussian parameters */ itkSetMacro(Scale, double); - itkGetMacro(Scale, double); + itkGetConstReferenceMacro(Scale, double); itkSetMacro(Normalized, bool); - itkGetMacro(Normalized, bool); + itkGetConstReferenceMacro(Normalized, bool); itkSetMacro(Sigma, ArrayType); - itkGetMacro(Sigma, ArrayType); + itkGetConstReferenceMacro(Sigma, ArrayType); itkSetMacro(Mean, ArrayType); - itkGetMacro(Mean, ArrayType); + itkGetConstReferenceMacro(Mean, ArrayType); protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkGetAverageSliceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGetAverageSliceImageFilter.h index 552451fddb..5d8e3f43e9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGetAverageSliceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGetAverageSliceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGetAverageSliceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:07 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-25 12:27:22 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -60,7 +60,7 @@ public: itkTypeMacro(GetAverageSliceImageFilter, AccumulateImageFilter); /** Set the direction in which to reflect the data. */ - itkGetMacro( AveragedOutDimension, unsigned int ); + itkGetConstMacro( AveragedOutDimension, unsigned int ); itkSetMacro( AveragedOutDimension, unsigned int ); protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGradientImageFilter.h index 1852e27359..0134bae812 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGradientImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:13:36 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-25 12:27:22 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -109,7 +109,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input image in its calculations */ itkSetMacro(UseImageSpacing, bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ @@ -133,7 +133,7 @@ public: * and OFF by default when ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE is * OFF). */ itkSetMacro( UseImageDirection, bool ); - itkGetMacro( UseImageDirection, bool ); + itkGetConstMacro( UseImageDirection, bool ); itkBooleanMacro( UseImageDirection ); protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientImageToBloxBoundaryPointImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGradientImageToBloxBoundaryPointImageFilter.h index e044f5344d..5b0f5696c7 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientImageToBloxBoundaryPointImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGradientImageToBloxBoundaryPointImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientImageToBloxBoundaryPointImageFilter.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:28:48 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:27:22 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -78,7 +78,7 @@ public: /** Get and set the number of times to repeat the filter. */ itkSetMacro(Threshold, double); - itkGetMacro(Threshold, double); + itkGetConstMacro(Threshold, double); /** Get and set the resolution of the blox * This is the number of input pixels "contained" within diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientImageToBloxBoundaryPointImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkGradientImageToBloxBoundaryPointImageFilter.txx index 7f7040b8b8..8107d5f80c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientImageToBloxBoundaryPointImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkGradientImageToBloxBoundaryPointImageFilter.txx @@ -3,14 +3,14 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientImageToBloxBoundaryPointImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-01-19 19:50:01 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-05-08 12:48:09 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -55,7 +55,7 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > for( j = 0; j < Superclass::ImageDimension; j++ ) { m_BloxResolution[j] = bloxResolution[j]; - if( m_BloxResolution[j] < 1 ) + if( m_BloxResolution[j] < 1 ) { m_BloxResolution[j] = 1; } @@ -80,7 +80,7 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > for( j = 0; j < NDimensions; j++ ) { m_BloxResolution[j] = bloxResolution; - if( m_BloxResolution[j] < 1 ) + if( m_BloxResolution[j] < 1 ) { m_BloxResolution[j] = 1; } @@ -94,32 +94,32 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > ::GenerateInputRequestedRegion() { itkDebugMacro(<< "GradientImageToBloxBoundaryPointImageFilter::GenerateInputRequestedRegion() called"); - + // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); - + // get pointers to the input and output - InputImagePointer inputPtr = + InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput()); OutputImagePointer outputPtr = this->GetOutput(); - + if ( !inputPtr || !outputPtr ) { return; } - + // we need to compute the input requested region (size and start index) const typename TOutputImage::SizeType& outputRequestedRegionSize = outputPtr->GetRequestedRegion().GetSize(); const typename TOutputImage::IndexType& outputRequestedRegionStartIndex = outputPtr->GetRequestedRegion().GetIndex(); - + typedef typename SizeType::SizeValueType SizeValueType; typedef typename IndexType::IndexValueType IndexValueType; SizeType inputRequestedRegionSize; IndexType inputRequestedRegionStartIndex; - + for (unsigned int i = 0; i < TInputImage::ImageDimension; i++) { inputRequestedRegionSize[i] = static_cast<SizeValueType>( @@ -127,11 +127,11 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > inputRequestedRegionStartIndex[i] = static_cast<IndexValueType>( outputRequestedRegionStartIndex[i] * m_BloxResolution[i] ); } - + typename TInputImage::RegionType inputRequestedRegion; inputRequestedRegion.SetSize( inputRequestedRegionSize ); inputRequestedRegion.SetIndex( inputRequestedRegionStartIndex ); - + inputPtr->SetRequestedRegion( inputRequestedRegion ); } @@ -142,7 +142,7 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > { // call the superclass' implementation of this method Superclass::GenerateOutputInformation(); - + // get pointers to the input and output InputImageConstPointer inputPtr = this->GetInput(); OutputImagePointer outputPtr = this->GetOutput(); @@ -151,15 +151,12 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > { return; } - + // we need to compute the output spacing, the output image size, and the // output image start index - const typename TInputImage::SpacingType& - inputSpacing = inputPtr->GetSpacing(); - const typename TInputImage::SizeType& inputSize - = inputPtr->GetLargestPossibleRegion().GetSize(); - const typename TInputImage::IndexType& inputStartIndex - = inputPtr->GetLargestPossibleRegion().GetIndex(); + const typename TInputImage::SpacingType& inputSpacing = inputPtr->GetSpacing(); + const typename TInputImage::SizeType& inputSize = inputPtr->GetLargestPossibleRegion().GetSize(); + const typename TInputImage::IndexType& inputStartIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); typename TOutputImage::SpacingType outputSpacing; typedef typename SizeType::SizeValueType SizeValueType; @@ -167,29 +164,50 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > SizeType outputSize; IndexType outputStartIndex; - + for (unsigned int i = 0; i < TOutputImage::ImageDimension; i++) { - outputSpacing[i] = inputSpacing[i] * m_BloxResolution[i]; outputSize[i] = static_cast<SizeValueType>( vcl_floor(static_cast<float>( inputSize[i] )/ m_BloxResolution[i])); + if( outputSize[i] < 1 ) { outputSize[i] = 1; } - + outputStartIndex[i] = static_cast<IndexValueType>( vcl_ceil(static_cast<float>( inputStartIndex[i] ) / m_BloxResolution[i] )); } - + outputPtr->SetSpacing( outputSpacing ); - + +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + // compute origin offset + // The physical center's of the input and output should be the same + ContinuousIndex<double, TOutputImage::ImageDimension> inputCenterIndex; + ContinuousIndex<double, TOutputImage::ImageDimension> outputCenterIndex; + for( unsigned int j = 0; j < TOutputImage::ImageDimension; j++ ) + { + inputCenterIndex[j] = inputStartIndex[j] + (inputSize[j] - 1) / 2.0; + outputCenterIndex[j] = outputStartIndex[j] + (outputSize[j] - 1) / 2.0; + } + + typename TOutputImage::PointType inputCenterPoint; + typename TOutputImage::PointType outputCenterPoint; + inputPtr->TransformContinuousIndexToPhysicalPoint(inputCenterIndex, inputCenterPoint); + outputPtr->TransformContinuousIndexToPhysicalPoint(outputCenterIndex, outputCenterPoint); + + typename TOutputImage::PointType outputOrigin = outputPtr->GetOrigin(); + outputOrigin = outputOrigin + (inputCenterPoint - outputCenterPoint); + outputPtr->SetOrigin(outputOrigin); +#endif + typename TOutputImage::RegionType outputLargestPossibleRegion; outputLargestPossibleRegion.SetSize( outputSize ); outputLargestPossibleRegion.SetIndex( outputStartIndex ); - + outputPtr->SetLargestPossibleRegion( outputLargestPossibleRegion ); } @@ -205,11 +223,14 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > OutputImagePointer outputPtr = this->GetOutput(0); // Allocate the output - outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() ); + typename TOutputImage::RegionType outputRequestedRegion = outputPtr->GetRequestedRegion(); + outputPtr->SetBufferedRegion( outputRequestedRegion ); outputPtr->Allocate(); + typename TInputImage::RegionType inputRequestedRegion = inputPtr->GetRequestedRegion(); + // Create a progress reporter - ProgressReporter progress(this, 0, inputPtr->GetRequestedRegion().GetNumberOfPixels()); + ProgressReporter progress(this, 0, inputRequestedRegion.GetNumberOfPixels()); // Position to figure out pixel location TPositionType inputPosition; @@ -217,17 +238,15 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > // Create an iterator to walk the input image typedef ImageRegionConstIterator<TInputImage> TInputIterator; - TInputIterator inputIt = TInputIterator(inputPtr, - inputPtr->GetRequestedRegion() ); + TInputIterator inputIt = TInputIterator(inputPtr, inputRequestedRegion ); // Keep track of how many boundary points we found (for debugging) unsigned long int numBP = 0; unsigned long int numBPadded = 0; // Get the index of the pixel - typename TInputImage::IndexType inputIndex; IndexType bloxIndex; - + for ( inputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt) { // Figure out the magnitude of the gradient @@ -235,7 +254,8 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > for(unsigned int i = 0; i < NDimensions; i++) { - mag += inputIt.Get()[i] * inputIt.Get()[i]; + const double component = inputIt.Get()[i]; + mag += component * component; } mag = vcl_sqrt(mag); @@ -245,22 +265,33 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > { numBP++; - // Get the index of the boundary pixel - inputIndex = inputIt.GetIndex(); - // Convert the index of the input pixel to the physical location of the // boundary point in the input image - inputPtr->TransformIndexToPhysicalPoint(inputIndex, inputPosition); + inputPtr->TransformIndexToPhysicalPoint( inputIt.GetIndex(), inputPosition ); // Transform the physical location to a blox index - outputPtr->TransformPhysicalPointToIndex(inputPosition, bloxIndex); + outputPtr->TransformPhysicalPointToIndex( inputPosition, bloxIndex ); + +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + // check if it is inside of the output image. + if( outputRequestedRegion.IsInside( bloxIndex ) ) + { + // Create a new boundary point item and set its parameters + BloxBoundaryPointItem<NDimensions>* pItem = new BloxBoundaryPointItem<NDimensions>; + pItem->SetPhysicalPosition(inputPosition); + pItem->SetGradient( inputIt.Get() ); + outputPtr->GetPixel(bloxIndex).push_back(pItem); + } +#else // Create a new boundary point item and set its parameters BloxBoundaryPointItem<NDimensions>* pItem = new BloxBoundaryPointItem<NDimensions>; pItem->SetPhysicalPosition(inputPosition); pItem->SetGradient( inputIt.Get() ); outputPtr->GetPixel(bloxIndex).push_back(pItem); +#endif + numBPadded++; } @@ -268,7 +299,7 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > } outputPtr->SetNumBoundaryPoints(numBP); - + itkDebugMacro(<< "Finished looking for boundary points\n" << "I found " << numBP << " points\n" << "I added " << numBPadded << " points\n"); @@ -280,7 +311,7 @@ GradientImageToBloxBoundaryPointImageFilter< TInputImage > ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); - + os << indent << "Threshold level: " << m_Threshold << std::endl; } diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeImageFilter.h index 552e4a5db2..1ae9dacaef 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientMagnitudeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-04-25 12:27:23 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -93,7 +93,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input image in its calculations */ itkSetMacro(UseImageSpacing, bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeImageFilter.txx index 3c7c10495b..e5131ea9ec 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientMagnitudeImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.34 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.35 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -188,7 +188,7 @@ GradientMagnitudeImageFilter< TInputImage, TOutputImage > const RealType g = SIP(x_slice[i], bit, op[i]); a += g * g; } - it.Value() = static_cast<OutputPixelType>(::sqrt(a)); + it.Value() = static_cast<OutputPixelType>(vcl_sqrt(a)); ++bit; ++it; progress.CompletedPixel(); diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeRecursiveGaussianImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeRecursiveGaussianImageFilter.h index 92a266a661..a74ed6e581 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeRecursiveGaussianImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientMagnitudeRecursiveGaussianImageFilter.h,v $ Language: C++ - Date: $Date: 2008-07-31 09:14:57 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-25 12:27:23 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -125,7 +125,7 @@ public: /** Define which normalization factor will be used for the Gaussian */ void SetNormalizeAcrossScale( bool normalizeInScaleSpace ); - itkGetMacro( NormalizeAcrossScale, bool ); + itkGetConstMacro( NormalizeAcrossScale, bool ); void SetNumberOfThreads( int nb ); diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeRecursiveGaussianImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeRecursiveGaussianImageFilter.txx index 4244ea0a3e..e560b82682 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeRecursiveGaussianImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkGradientMagnitudeRecursiveGaussianImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientMagnitudeRecursiveGaussianImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-05 05:36:44 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-03-24 21:55:11 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -246,7 +246,11 @@ GradientMagnitudeRecursiveGaussianImageFilter<TInputImage,TOutputImage > m_SqrSpacingFilter->SetInput( cumulativeImage ); // run the mini pipeline for that dimension - m_SqrSpacingFilter->Update(); + // Note: we must take care to update the requested region. Without that, a second run of the + // filter with a smaller input than in the first run trigger an exception, because the filter + // ask for a larger region than available. TODO: there should be a way to do that only once + // per GenerateData() call. + m_SqrSpacingFilter->UpdateLargestPossibleRegion(); // and user the result as the cumulative image cumulativeImage = m_SqrSpacingFilter->GetOutput(); diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientNDAnisotropicDiffusionFunction.txx b/Utilities/ITK/Code/BasicFilters/itkGradientNDAnisotropicDiffusionFunction.txx index 024304d19e..1f289ce846 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientNDAnisotropicDiffusionFunction.txx +++ b/Utilities/ITK/Code/BasicFilters/itkGradientNDAnisotropicDiffusionFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientNDAnisotropicDiffusionFunction.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-24 19:48:58 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -98,6 +98,7 @@ GradientNDAnisotropicDiffusionFunction<TImage> for (i = 0; i < ImageDimension; i++) { dx[i] = (it.GetPixel(m_Center + m_Stride[i])-it.GetPixel(m_Center - m_Stride[i]))/2.0f; + dx[i] *= this->m_ScaleCoefficients[i]; } for (i = 0; i < ImageDimension; i++) @@ -105,8 +106,10 @@ GradientNDAnisotropicDiffusionFunction<TImage> // ``Half'' directional derivatives dx_forward = it.GetPixel(m_Center + m_Stride[i]) - it.GetPixel(m_Center); + dx_forward *= this->m_ScaleCoefficients[i]; dx_backward = it.GetPixel(m_Center) - it.GetPixel(m_Center - m_Stride[i]); + dx_backward *= this->m_ScaleCoefficients[i]; // Calculate the conductance terms. Conductance varies with each // dimension because the gradient magnitude approximation is different @@ -119,8 +122,10 @@ GradientNDAnisotropicDiffusionFunction<TImage> { dx_aug = (it.GetPixel(m_Center + m_Stride[i] + m_Stride[j]) - it.GetPixel(m_Center + m_Stride[i] - m_Stride[j]) ) / 2.0f; + dx_aug *= this->m_ScaleCoefficients[j]; dx_dim = (it.GetPixel(m_Center - m_Stride[i] + m_Stride[j]) - it.GetPixel(m_Center - m_Stride[i] - m_Stride[j]) ) /2.0f; + dx_dim *= this->m_ScaleCoefficients[j]; accum += 0.25f * vnl_math_sqr( dx[j] + dx_aug ); accum_d += 0.25f * vnl_math_sqr( dx[j] + dx_dim ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientRecursiveGaussianImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGradientRecursiveGaussianImageFilter.h index a509527882..0d78527577 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGradientRecursiveGaussianImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientRecursiveGaussianImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:13:36 $ - Version: $Revision: 1.41 $ + Date: $Date: 2009-04-25 12:27:24 $ + Version: $Revision: 1.42 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -126,7 +126,7 @@ public: /** Define which normalization factor will be used for the Gaussian */ void SetNormalizeAcrossScale( bool normalizeInScaleSpace ); - itkGetMacro( NormalizeAcrossScale, bool ); + itkGetConstMacro( NormalizeAcrossScale, bool ); /** GradientRecursiveGaussianImageFilter needs all of the input to produce an * output. Therefore, GradientRecursiveGaussianImageFilter needs to provide @@ -148,7 +148,7 @@ public: * and OFF by default when ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE is * OFF). */ itkSetMacro( UseImageDirection, bool ); - itkGetMacro( UseImageDirection, bool ); + itkGetConstMacro( UseImageDirection, bool ); itkBooleanMacro( UseImageDirection ); #ifdef ITK_USE_CONCEPT_CHECKING diff --git a/Utilities/ITK/Code/BasicFilters/itkGradientToMagnitudeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGradientToMagnitudeImageFilter.h index 5edb6a8846..021d2a1c2e 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGradientToMagnitudeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGradientToMagnitudeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientToMagnitudeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-04-01 14:36:19 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -53,7 +53,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( A.GetNorm() ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleConnectedClosingImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleConnectedClosingImageFilter.h index 26c4c2016d..9de326a471 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleConnectedClosingImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleConnectedClosingImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleConnectedClosingImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:27:25 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -79,7 +79,7 @@ public: /** Set/Get the seed pixel for the segmentation */ itkSetMacro(Seed, InputImageIndexType); - itkGetMacro(Seed, InputImageIndexType); + itkGetConstMacro(Seed, InputImageIndexType); /** \deprecated * Get the number of iterations used to produce the current diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleConnectedOpeningImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleConnectedOpeningImageFilter.h index db5397392f..b6550a8e51 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleConnectedOpeningImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleConnectedOpeningImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleConnectedOpeningImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:27:25 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -80,7 +80,7 @@ public: /** Set/Get the seed pixel for the segmentation */ itkSetMacro(Seed, InputImageIndexType); - itkGetMacro(Seed, InputImageIndexType); + itkGetConstMacro(Seed, InputImageIndexType); /** \deprecated * Get the number of iterations used to produce the current diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleDilateImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleDilateImageFilter.h index 3c6022728e..8fadc54044 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleDilateImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleDilateImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleDilateImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-28 14:36:20 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -94,6 +94,9 @@ public: itkStaticConstMacro(KernelDimension, unsigned int, TKernel::NeighborhoodDimension); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(InputConvertibleToOutputCheck, @@ -104,8 +107,8 @@ public: (Concept::SameDimension<InputImageDimension, KernelDimension>)); itkConceptMacro(InputGreaterThanComparableCheck, (Concept::GreaterThanComparable<PixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleDilateImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkGrayscaleDilateImageFilter.txx index 6dd975ddf3..8840ec4a19 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleDilateImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleDilateImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleDilateImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-28 14:36:20 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,17 +52,17 @@ GrayscaleDilateImageFilter<TInputImage, TOutputImage, TKernel> KernelIteratorType kernel_it; - for (i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i) + for( i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i ) { // if structuring element is positive, use the pixel under that element // in the image - if (*kernel_it > 0) + if( *kernel_it > NumericTraits<KernelPixelType>::Zero ) { // note we use GetPixel() on the SmartNeighborhoodIterator to // respect boundary conditions temp = nit.GetPixel(i); - if (temp > max) + if( temp > max ) { max = temp; } diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleErodeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleErodeImageFilter.h index 518a4f93c2..21f59cc946 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleErodeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleErodeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleErodeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-28 14:36:20 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -92,6 +92,9 @@ public: itkStaticConstMacro(KernelDimension, unsigned int, TKernel::NeighborhoodDimension); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(InputConvertibleToOutputCheck, @@ -102,8 +105,8 @@ public: (Concept::SameDimension<InputImageDimension, KernelDimension>)); itkConceptMacro(InputLessThanComparableCheck, (Concept::LessThanComparable<PixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleErodeImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkGrayscaleErodeImageFilter.txx index 8b1cce33d6..edf13d88f8 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleErodeImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleErodeImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleErodeImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:08 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-28 14:36:20 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,17 +52,17 @@ GrayscaleErodeImageFilter<TInputImage, TOutputImage, TKernel> KernelIteratorType kernel_it; - for (i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i) + for( i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i ) { // if structuring element is positive, use the pixel under that element // in the image - if (*kernel_it > 0) + if( *kernel_it > NumericTraits<KernelPixelType>::Zero ) { // note we use GetPixel() on the NeighborhoodIterator in order // to respect boundary conditions. temp = nit.GetPixel(i); - if (temp < min) + if( temp < min ) { min = temp; } diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionDilateImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionDilateImageFilter.h index 1532aeb670..ba58a0fe56 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionDilateImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionDilateImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleFunctionDilateImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-28 14:36:21 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -86,6 +86,9 @@ public: itkStaticConstMacro(KernelDimension, unsigned int, TKernel::NeighborhoodDimension); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(SameDimensionCheck1, @@ -95,13 +98,13 @@ public: itkConceptMacro(InputConvertibleToOutputCheck, (Concept::Convertible<PixelType, typename TOutputImage::PixelType>)); itkConceptMacro(KernelConvertibleToInputCheck, - (Concept::Convertible<typename TKernel::PixelType, PixelType>)); + (Concept::Convertible<KernelPixelType, PixelType>)); itkConceptMacro(InputAdditiveOperatorsCheck, (Concept::AdditiveOperators<PixelType>)); itkConceptMacro(InputGreaterThanComparableCheck, (Concept::GreaterThanComparable<PixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionDilateImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionDilateImageFilter.txx index fed9e0ab17..2534a79370 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionDilateImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionDilateImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleFunctionDilateImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-28 14:36:23 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,18 +42,18 @@ GrayscaleFunctionDilateImageFilter<TInputImage, TOutputImage, TKernel> KernelIteratorType kernel_it; - for (i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i) + for( i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i ) { // if structuring element is positive, use the pixel under that element // in the image plus the structuring element value - if (*kernel_it > 0) + if( *kernel_it > NumericTraits< KernelPixelType >::Zero ) { // add the structuring element value to the pixel value, note we use // GetPixel() on SmartNeighborhoodIterator to respect boundary // conditions temp = nit.GetPixel(i) + (PixelType) *kernel_it; - if (temp > max) + if( temp > max ) { max = temp; } diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionErodeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionErodeImageFilter.h index a60c1d375a..be5a082f7a 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionErodeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionErodeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleFunctionErodeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-28 14:36:25 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -86,6 +86,9 @@ public: itkStaticConstMacro(KernelDimension, unsigned int, TKernel::NeighborhoodDimension); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(SameDimensionCheck1, @@ -95,13 +98,13 @@ public: itkConceptMacro(InputConvertibleToOutputCheck, (Concept::Convertible<PixelType, typename TOutputImage::PixelType>)); itkConceptMacro(KernelConvertibleToInputCheck, - (Concept::Convertible<typename TKernel::PixelType, PixelType>)); + (Concept::Convertible<KernelPixelType, PixelType>)); itkConceptMacro(InputAdditiveOperatorsCheck, (Concept::AdditiveOperators<PixelType>)); itkConceptMacro(InputLessThanComparableCheck, (Concept::LessThanComparable<PixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionErodeImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionErodeImageFilter.txx index 624edd74d6..e7b0cfbe9f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionErodeImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleFunctionErodeImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleFunctionErodeImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-28 14:36:27 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,18 +42,18 @@ GrayscaleFunctionErodeImageFilter<TInputImage, TOutputImage, TKernel> KernelIteratorType kernel_it; - for (i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i) + for( i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i ) { // if structuring element is positive, use the pixel under that element // in the image minus the structuring element value - if (*kernel_it > 0) + if( *kernel_it > NumericTraits< KernelPixelType >::Zero ) { // subtract the structuring element value to the pixel value, // note we use GetPixel() on SmartNeighborhoodIterator to respect // boundary condition temp = nit.GetPixel(i) - (PixelType) *kernel_it; - if (temp < min) + if( temp < min ) { min = temp; } diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleGeodesicDilateImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleGeodesicDilateImageFilter.h index 127535a326..d12e7f09fc 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleGeodesicDilateImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleGeodesicDilateImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleGeodesicDilateImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -118,12 +118,12 @@ public: * convergence. When run to convergence, this filter is equivalent * to "reconstruction by dilation". Default is off. */ itkSetMacro(RunOneIteration, bool); - itkGetMacro(RunOneIteration, bool); + itkGetConstMacro(RunOneIteration, bool); itkBooleanMacro(RunOneIteration); /** Get the number of iterations used to produce the current * output. */ - itkGetMacro(NumberOfIterationsUsed, unsigned long); + itkGetConstMacro(NumberOfIterationsUsed, unsigned long); /** * Set/Get whether the connected components are defined strictly by diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleGeodesicErodeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleGeodesicErodeImageFilter.h index b8348c23aa..9e03e10f4a 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleGeodesicErodeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleGeodesicErodeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleGeodesicErodeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -119,12 +119,12 @@ public: * convergence. When run to convergence, this filter is equivalent * to "reconstruction by erosion". Default is off. */ itkSetMacro(RunOneIteration, bool); - itkGetMacro(RunOneIteration, bool); + itkGetConstMacro(RunOneIteration, bool); itkBooleanMacro(RunOneIteration); /** Get the number of iterations used to produce the current * output. */ - itkGetMacro(NumberOfIterationsUsed, unsigned long); + itkGetConstMacro(NumberOfIterationsUsed, unsigned long); /** * Set/Get whether the connected components are defined strictly by diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleMorphologicalClosingImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleMorphologicalClosingImageFilter.h index 4fc1c9f0e6..39ffffbdec 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleMorphologicalClosingImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleMorphologicalClosingImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleMorphologicalClosingImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-08 16:03:55 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-28 14:36:29 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -101,6 +101,9 @@ public: itkGetConstReferenceMacro(SafeBorder, bool); itkBooleanMacro(SafeBorder); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(SameTypeCheck, @@ -113,8 +116,8 @@ public: (Concept::LessThanComparable<PixelType>)); itkConceptMacro(InputGreaterThanComparableCheck, (Concept::GreaterThanComparable<PixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkGrayscaleMorphologicalOpeningImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkGrayscaleMorphologicalOpeningImageFilter.h index 38083f5b81..872fe777e2 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGrayscaleMorphologicalOpeningImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkGrayscaleMorphologicalOpeningImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGrayscaleMorphologicalOpeningImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-08 16:03:55 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-28 14:36:30 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -102,6 +102,9 @@ public: itkGetConstReferenceMacro(SafeBorder, bool); itkBooleanMacro(SafeBorder); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(SameTypeCheck, @@ -114,8 +117,8 @@ public: (Concept::LessThanComparable<PixelType>)); itkConceptMacro(InputGreaterThanComparableCheck, (Concept::GreaterThanComparable<PixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkHConcaveImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkHConcaveImageFilter.h index 6d8d5cc58f..8624607bd2 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHConcaveImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkHConcaveImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHConcaveImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,7 +81,7 @@ public: * processing. Local maxima below this value are replaced with an * estimate of the local background. */ itkSetMacro(Height, InputImagePixelType); - itkGetMacro(Height, InputImagePixelType); + itkGetConstMacro(Height, InputImagePixelType); /** \deprecated * Get the number of iterations used to produce the current diff --git a/Utilities/ITK/Code/BasicFilters/itkHConvexImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkHConvexImageFilter.h index 6fdcfded70..ef2602d412 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHConvexImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkHConvexImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHConvexImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,7 +81,7 @@ public: * processing. Local maxima below this value are replaced with an * estimate of the local background. */ itkSetMacro(Height, InputImagePixelType); - itkGetMacro(Height, InputImagePixelType); + itkGetConstMacro(Height, InputImagePixelType); /** \deprecated * Get the number of iterations used to produce the current diff --git a/Utilities/ITK/Code/BasicFilters/itkHMaximaImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkHMaximaImageFilter.h index d0070f5882..9f922d65fa 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHMaximaImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkHMaximaImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHMaximaImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -93,7 +93,7 @@ public: * processing. Local maxima below this value are replaced with an * estimate of the local background. */ itkSetMacro(Height, InputImagePixelType); - itkGetMacro(Height, InputImagePixelType); + itkGetConstMacro(Height, InputImagePixelType); /** \deprecated * Get the number of iterations used to produce the current diff --git a/Utilities/ITK/Code/BasicFilters/itkHMinimaImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkHMinimaImageFilter.h index fd7dcee0ce..28f9a1c887 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHMinimaImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkHMinimaImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHMinimaImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -91,7 +91,7 @@ public: * processing. Local maxima below this value are replaced with an * estimate of the local background. */ itkSetMacro(Height, InputImagePixelType); - itkGetMacro(Height, InputImagePixelType); + itkGetConstMacro(Height, InputImagePixelType); /** \deprecated * Get the number of iterations used to produce the current diff --git a/Utilities/ITK/Code/BasicFilters/itkHausdorffDistanceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkHausdorffDistanceImageFilter.h index 44ce4325c3..ab3ab8b7e6 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHausdorffDistanceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkHausdorffDistanceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHausdorffDistanceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -110,8 +110,8 @@ public: const InputImage2Type * GetInput2(void); /** Return the computed Hausdorff distance. */ - itkGetMacro(HausdorffDistance,RealType); - itkGetMacro(AverageHausdorffDistance,RealType); + itkGetConstMacro(HausdorffDistance,RealType); + itkGetConstMacro(AverageHausdorffDistance,RealType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkHessian3DToVesselnessMeasureImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkHessian3DToVesselnessMeasureImageFilter.h index f9579b480c..13114d35a8 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHessian3DToVesselnessMeasureImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkHessian3DToVesselnessMeasureImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHessian3DToVesselnessMeasureImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:10 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -110,12 +110,12 @@ public: /** Set/Get macros for alpha_1. Please refer to * http://www.spl.harvard.edu/pages/spl-pre2007/pages/papers/yoshi */ itkSetMacro(Alpha1, double); - itkGetMacro(Alpha1, double); + itkGetConstMacro(Alpha1, double); /** Set/Get macros for alpha_2. Please refer to * http://www.spl.harvard.edu/pages/spl-pre2007/pages/papers/yoshi */ itkSetMacro(Alpha2, double); - itkGetMacro(Alpha2, double); + itkGetConstMacro(Alpha2, double); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkHessianRecursiveGaussianImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkHessianRecursiveGaussianImageFilter.h index 11f21632d2..da5046d817 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHessianRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkHessianRecursiveGaussianImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHessianRecursiveGaussianImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:10 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -133,7 +133,7 @@ public: /** Define which normalization factor will be used for the Gaussian */ void SetNormalizeAcrossScale( bool normalizeInScaleSpace ); - itkGetMacro( NormalizeAcrossScale, bool ); + itkGetConstMacro( NormalizeAcrossScale, bool ); /** HessianRecursiveGaussianImageFilter needs all of the input to produce an * output. Therefore, HessianRecursiveGaussianImageFilter needs to provide diff --git a/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DCirclesImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DCirclesImageFilter.h index 4c7f4a891d..66622fd47e 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DCirclesImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DCirclesImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHoughTransform2DCirclesImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:10 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -114,7 +114,7 @@ public: itkSetMacro(Threshold,double); /** Get the threshold value */ - itkGetMacro(Threshold,double); + itkGetConstMacro(Threshold,double); /** Get the radius image */ itkGetObjectMacro(RadiusImage,OutputImageType); @@ -123,27 +123,27 @@ public: itkSetMacro(SigmaGradient,double); /** Get the scale value */ - itkGetMacro(SigmaGradient,double); + itkGetConstMacro(SigmaGradient,double); /** Get the list of circles. This recomputes the circles */ CirclesListType & GetCircles(unsigned int n=0); /** Set/Get the number of circles to extract */ itkSetMacro(NumberOfCircles,unsigned int); - itkGetMacro(NumberOfCircles,unsigned int); + itkGetConstMacro(NumberOfCircles,unsigned int); /** Set/Get the radius of the disc to remove from the accumulator * for each circle found */ itkSetMacro(DiscRadiusRatio,float); - itkGetMacro(DiscRadiusRatio,float); + itkGetConstMacro(DiscRadiusRatio,float); /** Set the variance of the gaussian bluring for the accumulator */ itkSetMacro(Variance,float); - itkGetMacro(Variance,float); + itkGetConstMacro(Variance,float); /** Set the sweep angle */ itkSetMacro(SweepAngle,float); - itkGetMacro(SweepAngle,float); + itkGetConstMacro(SweepAngle,float); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DCirclesImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DCirclesImageFilter.txx index bdbce29168..d30f9d05f7 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DCirclesImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DCirclesImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHoughTransform2DCirclesImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-11-07 19:39:44 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-05 23:09:19 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -122,7 +122,7 @@ HoughTransform2DCirclesImageFilter< TInputPixelType, TOutputPixelType> double Vx = grad[0]; double Vy = grad[1]; - if( (fabs(Vx)>1) || (fabs(Vy)>1) ) // if the gradient is not flat + if( (vcl_fabs(Vx)>1) || (vcl_fabs(Vy)>1) ) // if the gradient is not flat { double norm = vcl_sqrt(Vx*Vx+Vy*Vy); Vx /= norm; diff --git a/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DLinesImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DLinesImageFilter.h index f45dcacdff..062a2fa9b2 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DLinesImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DLinesImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHoughTransform2DLinesImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:10 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:27:26 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -111,7 +111,7 @@ public: itkSetMacro(Threshold,float); /** Get the threshold value */ - itkGetMacro(Threshold,float); + itkGetConstMacro(Threshold,float); /** Set the resolution angle: The hough space descibes (in the angle direction) [-PI,PI[ @@ -119,7 +119,7 @@ public: itkSetMacro(AngleResolution,float); /** Get the resolution angle */ - itkGetMacro(AngleResolution,float); + itkGetConstMacro(AngleResolution,float); /** Simplify the accumulator */ void Simplify(void); @@ -132,16 +132,16 @@ public: /** Set/Get the number of lines to extract */ itkSetMacro(NumberOfLines,unsigned int); - itkGetMacro(NumberOfLines,unsigned int); + itkGetConstMacro(NumberOfLines,unsigned int); /** Set/Get the radius of the disc to remove from the accumulator * for each line found */ itkSetMacro(DiscRadius,float); - itkGetMacro(DiscRadius,float); + itkGetConstMacro(DiscRadius,float); /** Set the variance of the gaussian bluring for the accumulator */ itkSetMacro(Variance,float); - itkGetMacro(Variance,float); + itkGetConstMacro(Variance,float); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DLinesImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DLinesImageFilter.txx index 0429ca7558..61cc5a9f7a 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DLinesImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkHoughTransform2DLinesImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHoughTransform2DLinesImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-11-07 19:39:44 $ - Version: $Revision: 1.20 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -75,7 +75,7 @@ HoughTransform2DLinesImageFilter<TInputPixelType,TOutputPixelType> // Compute the size of the output image typename InputImageType::RegionType region; Size<2> size; - size[0]= (long unsigned int)(sqrt(m_AngleResolution*m_AngleResolution+input->GetLargestPossibleRegion().GetSize()[0]*input->GetLargestPossibleRegion().GetSize()[0])); + size[0]= (long unsigned int)(vcl_sqrt(m_AngleResolution*m_AngleResolution+input->GetLargestPossibleRegion().GetSize()[0]*input->GetLargestPossibleRegion().GetSize()[0])); size[1]= (long unsigned int)m_AngleResolution; region.SetSize(size); region.SetIndex(input->GetLargestPossibleRegion().GetIndex()); diff --git a/Utilities/ITK/Code/BasicFilters/itkImageToVectorImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkImageToVectorImageFilter.h index 750c157950..c24a890622 100644 --- a/Utilities/ITK/Code/BasicFilters/itkImageToVectorImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkImageToVectorImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageToVectorImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-13 18:32:19 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-20 16:21:47 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -84,6 +84,10 @@ protected: { Superclass::SetNthInput(num, input); } +private: + ImageToVectorImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkImplicitManifoldNormalVectorFilter.h b/Utilities/ITK/Code/BasicFilters/itkImplicitManifoldNormalVectorFilter.h index 09da24fcb9..3e2840635f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkImplicitManifoldNormalVectorFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkImplicitManifoldNormalVectorFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImplicitManifoldNormalVectorFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:10 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-12 17:22:49 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -68,7 +68,7 @@ namespace itk { * the NodeType has the following additional members: m_Flux. */ template <class TInputImage, class TSparseOutputImage> -class ImplicitManifoldNormalVectorFilter +class ITK_EXPORT ImplicitManifoldNormalVectorFilter : public FiniteDifferenceSparseImageFilter <TInputImage, TSparseOutputImage> { public: @@ -116,17 +116,17 @@ public: void SetNormalFunction( NormalFunctionType *nf ); itkSetMacro(MaxIteration, unsigned int); - itkGetMacro(MaxIteration, unsigned int); + itkGetConstMacro(MaxIteration, unsigned int); itkSetMacro(IsoLevelLow, NodeValueType); - itkGetMacro(IsoLevelLow, NodeValueType); + itkGetConstMacro(IsoLevelLow, NodeValueType); itkSetMacro(IsoLevelHigh, NodeValueType); - itkGetMacro(IsoLevelHigh, NodeValueType); + itkGetConstMacro(IsoLevelHigh, NodeValueType); itkSetMacro(MinVectorNorm, NodeValueType); - itkGetMacro(MinVectorNorm, NodeValueType); + itkGetConstMacro(MinVectorNorm, NodeValueType); itkSetMacro(UnsharpMaskingFlag, bool); - itkGetMacro(UnsharpMaskingFlag, bool); + itkGetConstMacro(UnsharpMaskingFlag, bool); itkSetMacro(UnsharpMaskingWeight, NodeValueType); - itkGetMacro(UnsharpMaskingWeight, NodeValueType); + itkGetConstMacro(UnsharpMaskingWeight, NodeValueType); protected: ImplicitManifoldNormalVectorFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkIntensityWindowingImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkIntensityWindowingImageFilter.h index cd4e53bf30..955be6c019 100755 --- a/Utilities/ITK/Code/BasicFilters/itkIntensityWindowingImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkIntensityWindowingImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIntensityWindowingImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:10 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-01 14:36:21 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,7 +58,7 @@ public: void SetOutputMaximum( TOutput max ) { m_OutputMaximum = max; } void SetWindowMinimum( TInput min ) { m_WindowMinimum = min; } void SetWindowMaximum( TInput max ) { m_WindowMaximum = max; } - inline TOutput operator()( const TInput & x ) + inline TOutput operator()( const TInput & x ) const { if( x < m_WindowMinimum ) { diff --git a/Utilities/ITK/Code/BasicFilters/itkInterpolateImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkInterpolateImageFilter.h index 5c24524a3f..b887bdc398 100644 --- a/Utilities/ITK/Code/BasicFilters/itkInterpolateImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkInterpolateImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkInterpolateImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:11 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:27:27 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -89,7 +89,7 @@ public: /** Set/Get the distance from the first image from which to generate * interpolated image. The default value is 0.5 */ itkSetClampMacro( Distance, double, 0.0, 1.0 ); - itkGetMacro( Distance, double ); + itkGetConstMacro( Distance, double ); /** Set the interpolator function */ itkSetObjectMacro( Interpolator, InterpolatorType ) diff --git a/Utilities/ITK/Code/BasicFilters/itkInterpolateImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkInterpolateImageFilter.txx index 6274bc0ba8..0abacfefd4 100644 --- a/Utilities/ITK/Code/BasicFilters/itkInterpolateImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkInterpolateImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkInterpolateImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:11 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-05-11 21:18:31 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -156,7 +156,7 @@ InterpolateImageFilter<TInputImage,TOutputImage> intermediateRegion.SetIndex( ImageDimension, 1 ); - intermediateRegion.SetSize( ImageDimension, 2 ); + intermediateRegion.SetSize( ImageDimension, 1 ); inIter = ImageRegionConstIteratorWithIndex<TInputImage>( this->GetInput2(), outputRegion ); outIter = ImageRegionIteratorWithIndex<IntermediateImageType>( m_IntermediateImage, diff --git a/Utilities/ITK/Code/BasicFilters/itkInterpolateImagePointsFilter.h b/Utilities/ITK/Code/BasicFilters/itkInterpolateImagePointsFilter.h index 1d6d6f84d1..3ba09ebf76 100644 --- a/Utilities/ITK/Code/BasicFilters/itkInterpolateImagePointsFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkInterpolateImagePointsFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkInterpolateImagePointsFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:11 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-25 12:27:27 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -128,7 +128,7 @@ public: itkSetMacro(DefaultPixelValue,PixelType); /** Get the pixel value when a transformed pixel is outside of the image */ - itkGetMacro(DefaultPixelValue,PixelType); + itkGetConstMacro(DefaultPixelValue,PixelType); /** Returns a pointer to the interpolator. */ InterpolatorPointer GetInterpolator() diff --git a/Utilities/ITK/Code/BasicFilters/itkInverseDeformationFieldImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkInverseDeformationFieldImageFilter.h index 4688261b73..6ec3ba3489 100755 --- a/Utilities/ITK/Code/BasicFilters/itkInverseDeformationFieldImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkInverseDeformationFieldImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkInverseDeformationFieldImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:11 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-25 12:27:27 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -147,7 +147,7 @@ public: * precise computation of the inverse field at the price of large memory * consumption and long computational time. */ itkSetMacro( SubsamplingFactor, unsigned int ); - itkGetMacro( SubsamplingFactor, unsigned int ); + itkGetConstMacro( SubsamplingFactor, unsigned int ); /** InverseDeformationFieldImageFilter produces an image which is a different size * than its input. As such, it needs to provide an implementation diff --git a/Utilities/ITK/Code/BasicFilters/itkInvertIntensityImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkInvertIntensityImageFilter.h index ca6aed6bcf..a24a34caeb 100644 --- a/Utilities/ITK/Code/BasicFilters/itkInvertIntensityImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkInvertIntensityImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkInvertIntensityImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-01 14:36:25 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,7 +48,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & x ) + inline TOutput operator()( const TInput & x ) const { TOutput result = static_cast<TOutput>( m_Maximum - x ); return result; diff --git a/Utilities/ITK/Code/BasicFilters/itkIsolatedConnectedImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkIsolatedConnectedImageFilter.h index c347a87882..6355a84a6d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkIsolatedConnectedImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkIsolatedConnectedImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIsolatedConnectedImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:11 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-21 12:29:36 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -108,47 +108,23 @@ public: /** Set seed point 1. This seed will be isolated from Seed2 (if possible). * All pixels connected to this seed will be replaced with ReplaceValue. * This method is deprecated, please use AddSeed() */ - void SetSeed1(const IndexType & seed) - { - this->ClearSeeds1(); - this->AddSeed1( seed ); - } - + void SetSeed1(const IndexType & seed); /** Clear all the seeds1. */ - void ClearSeeds1() - { - m_Seeds1.clear(); - } - + void ClearSeeds1(); /** Add seed point 1. */ - void AddSeed1(const IndexType & seed) - { - m_Seeds1.push_back( seed ); - this->Modified(); - } + void AddSeed1(const IndexType & seed); /** Set seed point 2. This seed will be isolated from Seed1 (if possible). * This method is deprecated, please use AddSeed() */ - void SetSeed2(const IndexType & seed) - { - this->ClearSeeds2(); - this->AddSeed2( seed ); - } - + void SetSeed2(const IndexType & seed); + /** Clear all the seeds2. */ - void ClearSeeds2() - { - m_Seeds2.clear(); - } + void ClearSeeds2(); /** Add seed point 2. */ - void AddSeed2(const IndexType & seed) - { - m_Seeds2.push_back( seed ); - this->Modified(); - } + void AddSeed2(const IndexType & seed); /** Set/Get the limit on the lower threshold value. The default is * the NonpositiveMin() for the InputPixelType. */ diff --git a/Utilities/ITK/Code/BasicFilters/itkIsolatedConnectedImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkIsolatedConnectedImageFilter.txx index 7bf92daf51..ddaab2876f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkIsolatedConnectedImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkIsolatedConnectedImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIsolatedConnectedImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:11 $ - Version: $Revision: 1.28 $ + Date: $Date: 2009-04-21 12:29:37 $ + Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -99,6 +99,72 @@ IsolatedConnectedImageFilter<TInputImage,TOutputImage> output->SetRequestedRegionToLargestPossibleRegion(); } +template <class TInputImage, class TOutputImage> +void +IsolatedConnectedImageFilter<TInputImage,TOutputImage> +::SetSeed1(const IndexType & seed) +{ + this->ClearSeeds1(); + this->AddSeed1( seed ); +} + +/** Clear all the seeds1. */ +template <class TInputImage, class TOutputImage> +void +IsolatedConnectedImageFilter<TInputImage,TOutputImage> +::ClearSeeds1() +{ + if( this->m_Seeds1.size() > 0 ) + { + this->m_Seeds1.clear(); + this->Modified(); + } +} + +/** Add seed point 1. */ +template <class TInputImage, class TOutputImage> +void +IsolatedConnectedImageFilter<TInputImage,TOutputImage> +::AddSeed1(const IndexType & seed) +{ + this->m_Seeds1.push_back( seed ); + this->Modified(); +} + +/** Set seed point 2. This seed will be isolated from Seed1 (if possible). + * This method is deprecated, please use AddSeed() */ +template <class TInputImage, class TOutputImage> +void +IsolatedConnectedImageFilter<TInputImage,TOutputImage> +::SetSeed2(const IndexType & seed) +{ + this->ClearSeeds2(); + this->AddSeed2( seed ); +} + +/** Clear all the seeds2. */ +template <class TInputImage, class TOutputImage> +void +IsolatedConnectedImageFilter<TInputImage,TOutputImage> +::ClearSeeds2() +{ + if( this->m_Seeds2.size() > 0 ) + { + this->m_Seeds2.clear(); + this->Modified(); + } +} + +/** Add seed point 2. */ +template <class TInputImage, class TOutputImage> +void +IsolatedConnectedImageFilter<TInputImage,TOutputImage> +::AddSeed2(const IndexType & seed) +{ + this->m_Seeds2.push_back( seed ); + this->Modified(); +} + template <class TInputImage, class TOutputImage> void IsolatedConnectedImageFilter<TInputImage,TOutputImage> diff --git a/Utilities/ITK/Code/BasicFilters/itkIterativeInverseDeformationFieldImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkIterativeInverseDeformationFieldImageFilter.h index e663dbf490..1c21911ccf 100755 --- a/Utilities/ITK/Code/BasicFilters/itkIterativeInverseDeformationFieldImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkIterativeInverseDeformationFieldImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIterativeInverseDeformationFieldImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:11 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-25 12:27:27 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,13 +95,13 @@ public: typedef typename FieldInterpolatorType::OutputType FieldInterpolatorOutputType; itkSetMacro(NumberOfIterations, unsigned int); - itkGetMacro(NumberOfIterations, unsigned int); + itkGetConstMacro(NumberOfIterations, unsigned int); // If the error (in mm) between forward and backward mapping is smaller than the StopValue, // the algorithm stops. // This value can be used to speed up the calculation. itkSetMacro(StopValue, double); - itkGetMacro(StopValue, double); + itkGetConstMacro(StopValue, double); char* GetReport() {return this->m_Report;} diff --git a/Utilities/ITK/Code/BasicFilters/itkJoinImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkJoinImageFilter.h index fe63ffc78c..52259da156 100644 --- a/Utilities/ITK/Code/BasicFilters/itkJoinImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkJoinImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkJoinImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-09 16:20:18 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-01 14:36:26 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -78,7 +78,7 @@ public: } /** operator(). This is the "call" method of the functor. */ - inline JoinType operator()( const TPixel1 & A, const TPixel2 & B) + inline JoinType operator() ( const TPixel1 & A, const TPixel2 & B) const { JoinType out; @@ -112,14 +112,14 @@ private: * overloaded on the last parameter type or pixel type) to avoid * "already declared/defined" errors for the case where TPixel1 * and TPixel2 are the same types. */ - void FirstCopier(JoinType& out, unsigned int idx, const TPixel1& A) + void FirstCopier(JoinType& out, unsigned int idx, const TPixel1& A) const { FirstCopier(CopierDispatch<Dimension1>(), out, idx, A); } /** Copier function specific to a vector type first pixel. */ void FirstCopier(CopierDispatchBase, - JoinType& out, unsigned int idx, const TPixel1& A) + JoinType& out, unsigned int idx, const TPixel1& A) const { for (unsigned int i=0; i < Dimension1; i++, idx++) { @@ -129,7 +129,7 @@ private: /** Copier function specific to a scalar first pixel. */ void FirstCopier(CopierDispatch<1>, - JoinType& out, unsigned int idx, const TPixel1& A) + JoinType& out, unsigned int idx, const TPixel1& A) const { out[idx] = static_cast<JoinValueType>(A); } /** Copier function to copy the second pixel to the output pixel casting @@ -137,14 +137,14 @@ private: * output pixel at position idx. This method simply delegates to * one of two overloaded implementations based on the dimension * (or number of components) of the second pixel. */ - void SecondCopier(JoinType& out, unsigned int idx, const TPixel2& B) + void SecondCopier(JoinType& out, unsigned int idx, const TPixel2& B) const { SecondCopier(CopierDispatch<Dimension2>(), out, idx, B); } /** Copier function specific to a vector type second pixel. */ void SecondCopier(CopierDispatchBase, - JoinType& out, unsigned int idx, const TPixel2& B) + JoinType& out, unsigned int idx, const TPixel2& B) const { for (unsigned int i=0; i < Dimension2; i++, idx++) { @@ -154,7 +154,7 @@ private: /** Copier function specific to a scalar second pixel. */ void SecondCopier(CopierDispatch<1>, - JoinType& out, unsigned int idx, const TPixel2& B) + JoinType& out, unsigned int idx, const TPixel2& B) const { out[idx] = static_cast<JoinValueType>(B); } diff --git a/Utilities/ITK/Code/BasicFilters/itkJoinSeriesImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkJoinSeriesImageFilter.h index 5b16589788..d07d9c9303 100644 --- a/Utilities/ITK/Code/BasicFilters/itkJoinSeriesImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkJoinSeriesImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkJoinSeriesImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-09 16:20:18 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-25 12:27:28 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -78,11 +78,11 @@ public: /** Set/Get spacing of the new dimension */ itkSetMacro(Spacing, double); - itkGetMacro(Spacing, double); + itkGetConstMacro(Spacing, double); /** Set/Get origin of the new dimension */ itkSetMacro(Origin, double); - itkGetMacro(Origin, double); + itkGetConstMacro(Origin, double); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkLabelStatisticsImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkLabelStatisticsImageFilter.h index 9a1d1d1e0f..35d037b08f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkLabelStatisticsImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkLabelStatisticsImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelStatisticsImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 17:40:08 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-05-05 18:16:17 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,7 +100,12 @@ public: typedef std::vector<typename IndexType::IndexValueType> BoundingBoxType; /** Histogram-related typedefs */ +#ifdef ITK_USE_REVIEW_STATISTICS + typedef itk::Statistics::Histogram<RealType> HistogramType; +#else typedef itk::Statistics::Histogram<RealType,1> HistogramType; +#endif + typedef typename HistogramType::Pointer HistogramPointer; /** \class LabelStatistics @@ -163,13 +168,19 @@ public: m_BoundingBox[i+1] = NumericTraits<ITK_TYPENAME IndexType::IndexValueType>::NonpositiveMin(); } - // Histogram + // Histogram m_Histogram = HistogramType::New(); - typename HistogramType::SizeType hsize; - hsize[0] = size; + typename HistogramType::SizeType hsize; typename HistogramType::MeasurementVectorType lb; - lb[0] = lowerBound; typename HistogramType::MeasurementVectorType ub; +#ifdef ITK_USE_REVIEW_STATISTICS + hsize.SetSize(1); + lb.SetSize(1); + ub.SetSize(1); + m_Histogram->SetMeasurementVectorSize(1); +#endif + hsize[0] = size; + lb[0] = lowerBound; ub[0] = upperBound; m_Histogram->Initialize(hsize, lb, ub); } @@ -223,7 +234,7 @@ public: // macros for Histogram enables itkSetMacro(UseHistograms, bool); - itkGetMacro(UseHistograms, bool); + itkGetConstMacro(UseHistograms, bool); itkBooleanMacro(UseHistograms); /** Set the label image */ diff --git a/Utilities/ITK/Code/BasicFilters/itkLabelStatisticsImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkLabelStatisticsImageFilter.txx index d8ef8e2b56..99a0012158 100644 --- a/Utilities/ITK/Code/BasicFilters/itkLabelStatisticsImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkLabelStatisticsImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelStatisticsImageFilter.txx,v $ Language: C++ -Date: $Date: 2008-10-17 01:43:11 $ -Version: $Revision: 1.21 $ +Date: $Date: 2009-05-08 16:17:51 $ +Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,6 +40,9 @@ LabelStatisticsImageFilter<TInputImage, TLabelImage> { this->SetNumberOfRequiredInputs(2); m_UseHistograms = false; +#ifdef ITK_USE_REVIEW_STATISTICS + m_NumBins.SetSize(1); +#endif m_NumBins[0] = 20; m_LowerBound = static_cast<RealType>( NumericTraits<PixelType>::NonpositiveMin() ); m_UpperBound = static_cast<RealType>( NumericTraits<PixelType>::max() ); @@ -192,6 +195,9 @@ LabelStatisticsImageFilter<TInputImage, TLabelImage> if (m_UseHistograms) { typename HistogramType::IndexType index; +#ifdef ITK_USE_REVIEW_STATISTICS + index.SetSize(1); +#endif for (unsigned int bin=0; bin<m_NumBins[0]; bin++) { index[0] = bin; @@ -308,8 +314,15 @@ LabelStatisticsImageFilter<TInputImage, TLabelImage> if (m_UseHistograms) { typename HistogramType::MeasurementVectorType meas; +#ifdef ITK_USE_REVIEW_STATISTICS + meas.SetSize(1); +#endif meas[0] = value; +#ifdef ITK_USE_REVIEW_STATISTICS + (*mapIt).second.m_Histogram->IncreaseFrequency(meas, 1); +#else (*mapIt).second.m_Histogram->IncreaseFrequency(meas, 1.0F); +#endif } ++it; @@ -514,8 +527,17 @@ LabelStatisticsImageFilter<TInputImage, TLabelImage> } else { + +#ifdef ITK_USE_REVIEW_STATISTICS + typename HistogramType::SizeValueType bin = 0; +#else typename HistogramType::SizeType::SizeValueType bin = 0; +#endif + typename HistogramType::IndexType index; +#ifdef ITK_USE_REVIEW_STATISTICS + index.SetSize(1); +#endif RealType total = 0; // count bins until just over half the distribution is counted diff --git a/Utilities/ITK/Code/BasicFilters/itkLaplacianImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkLaplacianImageFilter.h index b103613822..ff87d86667 100644 --- a/Utilities/ITK/Code/BasicFilters/itkLaplacianImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkLaplacianImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLaplacianImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 17:40:08 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-25 12:27:28 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -112,7 +112,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input image in its calculations */ itkSetMacro(UseImageSpacing, bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkLaplacianRecursiveGaussianImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkLaplacianRecursiveGaussianImageFilter.h index a00d8efad7..0dba3a3182 100644 --- a/Utilities/ITK/Code/BasicFilters/itkLaplacianRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkLaplacianRecursiveGaussianImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLaplacianRecursiveGaussianImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 17:40:08 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-25 12:27:29 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -117,7 +117,7 @@ public: /** Define which normalization factor will be used for the Gaussian */ void SetNormalizeAcrossScale( bool normalizeInScaleSpace ); - itkGetMacro( NormalizeAcrossScale, bool ); + itkGetConstMacro( NormalizeAcrossScale, bool ); /** LaplacianRecursiveGaussianImageFilter needs all of the input to produce an * output. Therefore, LaplacianRecursiveGaussianImageFilter needs to provide diff --git a/Utilities/ITK/Code/BasicFilters/itkLaplacianSharpeningImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkLaplacianSharpeningImageFilter.h index 8240628fa9..c1c0f11090 100644 --- a/Utilities/ITK/Code/BasicFilters/itkLaplacianSharpeningImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkLaplacianSharpeningImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLaplacianSharpeningImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 17:40:09 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-25 12:27:29 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -101,7 +101,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input image in its calculations */ itkSetMacro(UseImageSpacing, bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkLog10ImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkLog10ImageFilter.h index 4a1f43180f..40e1090ef2 100644 --- a/Utilities/ITK/Code/BasicFilters/itkLog10ImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkLog10ImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLog10ImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 17:40:09 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-01 14:36:26 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -43,7 +43,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( vcl_log10( static_cast<double>( A ) ) ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkLogImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkLogImageFilter.h index d56d70c275..2f1774e8de 100644 --- a/Utilities/ITK/Code/BasicFilters/itkLogImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkLogImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLogImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 17:40:09 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-01 14:36:27 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( vcl_log( static_cast<double>( A ) ) ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkMaskImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMaskImageFilter.h index 73d949bd30..9f6f1f16b0 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMaskImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMaskImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-15 17:01:18 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-01 14:36:27 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -69,7 +69,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & A, const TMask & B) + inline TOutput operator()( const TInput & A, const TMask & B) const { if (B != NumericTraits< TMask >::ZeroValue() ) { diff --git a/Utilities/ITK/Code/BasicFilters/itkMaskNegatedImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMaskNegatedImageFilter.h index 3ab2df55a6..a82fc85902 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMaskNegatedImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMaskNegatedImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskNegatedImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-15 17:22:45 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-01 14:36:30 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -69,7 +69,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & A, const TMask & B) + inline TOutput operator()( const TInput & A, const TMask & B) const { if (B != NumericTraits< TMask >::ZeroValue() ) { diff --git a/Utilities/ITK/Code/BasicFilters/itkMaskNeighborhoodOperatorImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMaskNeighborhoodOperatorImageFilter.h index 816651d785..baae5693e9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMaskNeighborhoodOperatorImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMaskNeighborhoodOperatorImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskNeighborhoodOperatorImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 18:05:25 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:27:30 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -112,7 +112,7 @@ public: /** Get the output value for the pixels that are not under the * mask. */ - itkGetMacro( DefaultValue, OutputPixelType ); + itkGetConstMacro( DefaultValue, OutputPixelType ); /** Set the UseDefaultValue flag. If true, the pixels outside the * mask will e set to m_DefaultValue. Otherwise, they will be set diff --git a/Utilities/ITK/Code/BasicFilters/itkMatrixIndexSelectionImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMatrixIndexSelectionImageFilter.h index fba1f9cbc5..3081790198 100755 --- a/Utilities/ITK/Code/BasicFilters/itkMatrixIndexSelectionImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMatrixIndexSelectionImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMatrixIndexSelectionImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 18:05:25 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-01 14:36:30 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,7 +48,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( A[m_I][m_J] ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkMaximumImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMaximumImageFilter.h index 1f5176f325..21146a95d4 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMaximumImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMaximumImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaximumImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 18:05:25 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-01 14:36:30 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -50,7 +50,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { if(A > B) { diff --git a/Utilities/ITK/Code/BasicFilters/itkMinimumImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMinimumImageFilter.h index 511eb0ea20..5e3afed1ed 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMinimumImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMinimumImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMinimumImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:41 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-01 14:36:30 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -50,7 +50,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { return static_cast<TOutput>( (A < B)? A : B ); } }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkMinimumMaximumImageCalculator.h b/Utilities/ITK/Code/BasicFilters/itkMinimumMaximumImageCalculator.h index 36a6cc0443..e9f020a677 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMinimumMaximumImageCalculator.h +++ b/Utilities/ITK/Code/BasicFilters/itkMinimumMaximumImageCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMinimumMaximumImageCalculator.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:41 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-25 12:27:32 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -78,10 +78,10 @@ public: void Compute(void); /** Return the minimum intensity value. */ - itkGetMacro(Minimum,PixelType); + itkGetConstMacro(Minimum,PixelType); /** Return the maximum intensity value. */ - itkGetMacro(Maximum,PixelType); + itkGetConstMacro(Maximum,PixelType); /** Return the index of the minimum intensity value. */ itkGetConstReferenceMacro(IndexOfMinimum,IndexType); diff --git a/Utilities/ITK/Code/BasicFilters/itkMinimumProjectionImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMinimumProjectionImageFilter.h index 5cac1872a0..8d77975eda 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMinimumProjectionImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMinimumProjectionImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMinimumProjectionImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -56,7 +56,7 @@ public: m_Minimum = NumericTraits< TInputPixel >::max(); } - inline void operator()( const TInputPixel &input ) + inline void operator()( const TInputPixel &input ) { m_Minimum = vnl_math_min( m_Minimum, input ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkModulusImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkModulusImageFilter.h index 3719eded9a..fbcfdbe09f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkModulusImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkModulusImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkModulusImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,7 +46,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & x ) + inline TOutput operator()( const TInput & x ) const { TOutput result = static_cast<TOutput>( x % m_Dividend ); return result; diff --git a/Utilities/ITK/Code/BasicFilters/itkMorphologicalGradientImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMorphologicalGradientImageFilter.h index 53c1fafbbb..bdf3286a05 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMorphologicalGradientImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMorphologicalGradientImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMorphologicalGradientImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-28 14:36:31 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -102,6 +102,9 @@ public: /** Get the kernel (structuring element). */ itkGetConstReferenceMacro(Kernel, KernelType); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(SameDimensionCheck1, @@ -116,8 +119,8 @@ public: (Concept::AdditiveOperators<InputImagePixelType>)); itkConceptMacro(InputConvertibleToOutputCheck, (Concept::Convertible<InputImagePixelType, OutputImagePixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkMorphologyImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMorphologyImageFilter.h index 4b196cc95b..3d188d2c85 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMorphologyImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMorphologyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMorphologyImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 23:24:23 $ - Version: $Revision: 1.20 $ + Date: $Date: 2009-04-25 12:27:36 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -149,7 +149,7 @@ public: { m_BoundaryCondition = &m_DefaultBoundaryCondition; } /** Get the current boundary condition. */ - itkGetMacro(BoundaryCondition, ImageBoundaryConditionPointerType); + itkGetConstMacro(BoundaryCondition, ImageBoundaryConditionPointerType); protected: MorphologyImageFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkMultiplyImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkMultiplyImageFilter.h index a1c7b95eca..6acf742856 100644 --- a/Utilities/ITK/Code/BasicFilters/itkMultiplyImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkMultiplyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiplyImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:41 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,7 +47,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { return (TOutput)(A * B); } }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkNarrowBand.txx b/Utilities/ITK/Code/BasicFilters/itkNarrowBand.txx index fd124bbf0d..c3d4390ef5 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNarrowBand.txx +++ b/Utilities/ITK/Code/BasicFilters/itkNarrowBand.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNarrowBand.txx,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:42 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-06 13:59:00 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,6 +21,7 @@ #define __itkNarrowBand_txx #include "itkNarrowBand.h" #include "math.h" +#include "vcl_cmath.h" namespace itk { @@ -45,7 +46,7 @@ NarrowBand<NodeType> { n = static_cast<unsigned int>( m_NodeContainer.size() ); } - unsigned int regionsize = static_cast<unsigned int> (floor(static_cast<float>(m_NodeContainer.size())/static_cast<float>( n ))); + unsigned int regionsize = static_cast<unsigned int> (vcl_floor(static_cast<float>(m_NodeContainer.size())/static_cast<float>( n ))); if (regionsize == 0) { regionsize = 1; diff --git a/Utilities/ITK/Code/BasicFilters/itkNarrowBandImageFilterBase.h b/Utilities/ITK/Code/BasicFilters/itkNarrowBandImageFilterBase.h index 119f74d495..bcb21bb5a4 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNarrowBandImageFilterBase.h +++ b/Utilities/ITK/Code/BasicFilters/itkNarrowBandImageFilterBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNarrowBandImageFilterBase.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:44 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:27:38 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -109,10 +109,10 @@ public: /** Set/Get IsoSurfaceValue to use in the input image */ itkSetMacro( IsoSurfaceValue, ValueType); - itkGetMacro( IsoSurfaceValue, ValueType); + itkGetConstMacro( IsoSurfaceValue, ValueType); /** Root Mean Square Change between successive iterations */ - // itkGetMacro( RMSChange, ValueType); + // itkGetConstMacro( RMSChange, ValueType); /** This function is used to insert a pixel index into the narrow band The * entire narrow band can be constructed using this method. Usually, diff --git a/Utilities/ITK/Code/BasicFilters/itkNarrowBandImageFilterBase.txx b/Utilities/ITK/Code/BasicFilters/itkNarrowBandImageFilterBase.txx index a5edde99c9..afa702f775 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNarrowBandImageFilterBase.txx +++ b/Utilities/ITK/Code/BasicFilters/itkNarrowBandImageFilterBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNarrowBandImageFilterBase.txx,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:44 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-05-12 17:22:53 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -401,6 +401,9 @@ NarrowBandImageFilterBase<TInputImage, TOutputImage> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); + os << indent << "IsoSurfaceValue: " + << static_cast<typename NumericTraits<ValueType>::PrintType>(m_IsoSurfaceValue) + << std::endl; } }// end namespace itk diff --git a/Utilities/ITK/Code/BasicFilters/itkNaryAddImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkNaryAddImageFilter.h index a0136642b4..77f9f700ca 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNaryAddImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkNaryAddImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNaryAddImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:44 $ - Version: $Revision: 1.35 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.36 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -61,7 +61,7 @@ public: typedef typename NumericTraits< TInput >::AccumulateType AccumulatorType; Add1() {} ~Add1() {} - inline TOutput operator()( const std::vector< TInput > & B) + inline TOutput operator()( const std::vector< TInput > & B) const { AccumulatorType sum = NumericTraits< TOutput >::Zero; for( unsigned int i=0; i< B.size(); i++ ) diff --git a/Utilities/ITK/Code/BasicFilters/itkNaryFunctorImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkNaryFunctorImageFilter.txx index 7c5d932f67..71a46faf15 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNaryFunctorImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkNaryFunctorImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNaryFunctorImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:44 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-03-05 09:46:31 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,26 +51,12 @@ NaryFunctorImageFilter<TInputImage, TOutputImage, TFunction> const unsigned int numberOfInputImages = static_cast< unsigned int >( this->GetNumberOfInputs() ); - OutputImagePointer outputPtr = this->GetOutput(0); - ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); - - - // Clear the content of the output - outputIt.GoToBegin(); - while( !outputIt.IsAtEnd() ) - { - outputIt.Set( itk::NumericTraits< OutputImagePixelType >::Zero ); - ++outputIt; - } - typedef ImageRegionConstIterator<TInputImage> ImageRegionConstIteratorType; std::vector< ImageRegionConstIteratorType * > inputItrVector; - inputItrVector.resize(numberOfInputImages); - //Array< ImageRegionConstIteratorType > inputItrVector(numberOfInputImages); + inputItrVector.reserve( numberOfInputImages ); // support progress methods/callbacks. // count the number of inputs that are non-null - unsigned int lastValidImage = 0; for (unsigned int i=0; i < numberOfInputImages; ++i) { InputImagePointer inputPtr = @@ -78,49 +64,53 @@ NaryFunctorImageFilter<TInputImage, TOutputImage, TFunction> if (inputPtr) { - ImageRegionConstIteratorType *inputIt = new ImageRegionConstIteratorType(inputPtr,outputRegionForThread); - lastValidImage = i; - inputItrVector[i] = reinterpret_cast< ImageRegionConstIteratorType * >( inputIt ); - inputItrVector[i]->GoToBegin(); - } - else - { - inputItrVector[i] = reinterpret_cast< ImageRegionConstIteratorType * >(NULL); + inputItrVector.push_back( new ImageRegionConstIteratorType(inputPtr,outputRegionForThread) ); } } ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - if( !inputItrVector[lastValidImage] ) + const unsigned int numberOfValidInputImages = inputItrVector.size(); + + if( numberOfValidInputImages==0 ) { //No valid regions in the thread + //(and no region iterators to delete) return; } - NaryArrayType naryInputArray; - naryInputArray.resize( numberOfInputImages ); - - outputIt.GoToBegin(); + NaryArrayType naryInputArray( numberOfValidInputImages ); + + OutputImagePointer outputPtr = this->GetOutput(0); + ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); + + typename std::vector< ImageRegionConstIteratorType * >::iterator regionIterators; + const typename std::vector< ImageRegionConstIteratorType * >::const_iterator regionItEnd + = inputItrVector.end(); + + typename NaryArrayType::iterator arrayIt; - while( !inputItrVector[lastValidImage]->IsAtEnd()) + while( !outputIt.IsAtEnd() ) { - for (unsigned int inputNumber=0; inputNumber < numberOfInputImages; inputNumber++) + arrayIt = naryInputArray.begin(); + regionIterators = inputItrVector.begin(); + while ( regionIterators != regionItEnd ) { - naryInputArray[ inputNumber ] = inputItrVector[inputNumber]->Get(); - ++(*inputItrVector[inputNumber]); + *arrayIt++ = (*regionIterators)->Get(); + ++(*(*regionIterators)); + ++regionIterators; } outputIt.Set( m_Functor( naryInputArray ) ); ++outputIt; progress.CompletedPixel(); } - - for (unsigned int i=0; i < numberOfInputImages; ++i) + + // Free memory + regionIterators = inputItrVector.begin(); + while ( regionIterators != regionItEnd ) { - if (inputItrVector[i]) - { - delete inputItrVector[i]; - } + delete (*regionIterators++); } } diff --git a/Utilities/ITK/Code/BasicFilters/itkNaryMaximumImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkNaryMaximumImageFilter.h index fb8e338898..6a1a07a682 100755 --- a/Utilities/ITK/Code/BasicFilters/itkNaryMaximumImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkNaryMaximumImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNaryMaximumImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:44 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -68,7 +68,7 @@ public: Maximum1() {} ~Maximum1() {} - inline TOutput operator()( const std::vector< TInput > & B) + inline TOutput operator()( const std::vector< TInput > & B) const { OutputValueType A = NumericTraits< TOutput >::NonpositiveMin(); for( unsigned int i=0; i< B.size(); i++ ) diff --git a/Utilities/ITK/Code/BasicFilters/itkNeighborhoodConnectedImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkNeighborhoodConnectedImageFilter.h index 6c764b7cd0..e0cf2b3cfb 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNeighborhoodConnectedImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkNeighborhoodConnectedImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNeighborhoodConnectedImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:44 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-25 12:27:41 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -64,38 +64,28 @@ public: void PrintSelf ( std::ostream& os, Indent indent ) const; /** Clear the seeds */ - void ClearSeeds() - { - m_Seeds.clear(); - this->Modified(); - } + void ClearSeeds(); + /** Set seed point. */ - void SetSeed(const IndexType & seed) - { - this->ClearSeeds(); - this->AddSeed ( seed ); - } + void SetSeed(const IndexType & seed); + /** Add a seed point */ - void AddSeed ( const IndexType & seed ) - { - m_Seeds.push_back ( seed ); - this->Modified(); - } + void AddSeed ( const IndexType & seed ); /** Set/Get the lower threshold. The default is 0. */ itkSetMacro(Lower, InputImagePixelType); - itkGetMacro(Lower, InputImagePixelType); + itkGetConstMacro(Lower, InputImagePixelType); /** Set/Get the upper threshold. The default is the largest possible * value for the InputPixelType. */ itkSetMacro(Upper, InputImagePixelType); - itkGetMacro(Upper, InputImagePixelType); + itkGetConstMacro(Upper, InputImagePixelType); /** Set/Get value to replace thresholded pixels. Pixels that lie * * within Lower and Upper (inclusive) will be replaced with this * value. The default is 1. */ itkSetMacro(ReplaceValue, OutputImagePixelType); - itkGetMacro(ReplaceValue, OutputImagePixelType); + itkGetConstMacro(ReplaceValue, OutputImagePixelType); /** Set the radius of the neighborhood used for a mask. */ itkSetMacro(Radius, InputImageSizeType); diff --git a/Utilities/ITK/Code/BasicFilters/itkNeighborhoodConnectedImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkNeighborhoodConnectedImageFilter.txx index a9b5996983..cd3aee46de 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNeighborhoodConnectedImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkNeighborhoodConnectedImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNeighborhoodConnectedImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:45 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-21 12:29:40 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,6 +38,36 @@ NeighborhoodConnectedImageFilter<TInputImage, TOutputImage> m_Radius.Fill(1); } +template <class TInputImage, class TOutputImage> +void +NeighborhoodConnectedImageFilter<TInputImage, TOutputImage> +::ClearSeeds() +{ + if( this->m_Seeds.size() > 0 ) + { + this->m_Seeds.clear(); + this->Modified(); + } +} + +template <class TInputImage, class TOutputImage> +void +NeighborhoodConnectedImageFilter<TInputImage, TOutputImage> +::SetSeed(const IndexType & seed) +{ + this->ClearSeeds(); + this->AddSeed ( seed ); +} + +template <class TInputImage, class TOutputImage> +void +NeighborhoodConnectedImageFilter<TInputImage, TOutputImage> +::AddSeed ( const IndexType & seed ) +{ + this->m_Seeds.push_back ( seed ); + this->Modified(); +} + /** * Standard PrintSelf method. */ diff --git a/Utilities/ITK/Code/BasicFilters/itkNoiseImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkNoiseImageFilter.txx index 599ce8101a..aa53bbc9aa 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNoiseImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkNoiseImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNoiseImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:45 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -156,7 +156,7 @@ NoiseImageFilter< TInputImage, TOutputImage> // calculate the standard deviation value var = (sumOfSquares - (sum*sum/num)) / (num - 1.0); - it.Set( static_cast<OutputPixelType>(sqrt(var)) ); + it.Set( static_cast<OutputPixelType>(vcl_sqrt(var)) ); ++bit; ++it; diff --git a/Utilities/ITK/Code/BasicFilters/itkNonThreadedShrinkImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkNonThreadedShrinkImageFilter.h index 732ea9d589..6883abc501 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNonThreadedShrinkImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkNonThreadedShrinkImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNonThreadedShrinkImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:45 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-07 18:58:49 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,6 +18,7 @@ #define __itkNonThreadedShrinkImageFilter_h #include "itkImageToImageFilter.h" +#include "itkShrinkImageFilter.h" namespace itk { @@ -35,11 +36,16 @@ namespace itk * ProcessObject::GenerateInputRequestedRegion() and * ProcessObject::GenerateOutputInformation(). * + * NOTE: This filter runs the ShrinkImageFilter with the number of + * threads set to 1. To avoid confusion, developers shopuld replace + * this class with ShrinkImageFilter. If you need to limit the number + * of threads, instantiate the afilter and apply the + * SetNumberOfThreads(1) methods. * \ingroup GeometricTransforms */ template <class TInputImage, class TOutputImage> class ITK_EXPORT NonThreadedShrinkImageFilter: - public ImageToImageFilter<TInputImage,TOutputImage> + public ShrinkImageFilter<TInputImage,TOutputImage> { public: /** Standard class typedefs. */ @@ -52,82 +58,24 @@ public: itkNewMacro(Self); /** Run-time type information (and related methods). */ - itkTypeMacro(NonThreadedShrinkImageFilter, ImageToImageFilter); + itkTypeMacro(NonThreadedShrinkImageFilter, ShrinkImageFilter); - /** Typedef to images */ - typedef TOutputImage OutputImageType; - typedef TInputImage InputImageType; - typedef typename OutputImageType::Pointer OutputImagePointer; - typedef typename InputImageType::Pointer InputImagePointer; - typedef typename InputImageType::ConstPointer InputImageConstPointer; - - /** Typedef to describe the output image region type. */ - typedef typename TOutputImage::RegionType OutputImageRegionType; - - /** ImageDimension enumeration. */ - itkStaticConstMacro(ImageDimension, unsigned int, - TInputImage::ImageDimension ); - itkStaticConstMacro(OutputImageDimension, unsigned int, - TOutputImage::ImageDimension ); - - /** Set the shrink factors. Values are clamped to - * a minimum value of 1. Default is 1 for all dimensions. */ - void SetShrinkFactors( unsigned int factors[] ); - void SetShrinkFactors( unsigned int factor ); - void SetShrinkFactor( unsigned int i, unsigned int factor ) + virtual void SetNumberOfThreads( int ) { - m_ShrinkFactors[i] = factor; + Superclass::SetNumberOfThreads(1); } - - /** Get the shrink factors. */ - const unsigned int * GetShrinkFactors() const - { return m_ShrinkFactors; } - - /** NonThreadedShrinkImageFilter produces an image which is a - * different resolution and with a different pixel spacing than its - * input image. As such, NonThreadedShrinkImageFilter needs to - * provide an implementation for GenerateOutputInformation() in - * order to inform the pipeline execution model. The original - * documentation of this method is below. - * \sa ProcessObject::GenerateOutputInformaton() */ - virtual void GenerateOutputInformation(); - - /** NonThreadedShrinkImageFilter needs a larger input requested - * region than the output requested region. As such, - * NonThreadedShrinkImageFilter needs to provide an implementation - * for GenerateInputRequestedRegion() in order to inform the - * pipeline execution model. - * * \sa ProcessObject::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion(); - -#ifdef ITK_USE_CONCEPT_CHECKING - /** Begin concept checking */ - itkConceptMacro(InputConvertibleToOutputCheck, - (Concept::Convertible<typename TInputImage::PixelType, - typename TOutputImage::PixelType>)); - itkConceptMacro(SameDimensionCheck, - (Concept::SameDimension<ImageDimension, OutputImageDimension>)); - /** End concept checking */ -#endif protected: - NonThreadedShrinkImageFilter(); - ~NonThreadedShrinkImageFilter() {}; - void PrintSelf(std::ostream& os, Indent indent) const; - - void GenerateData(); + NonThreadedShrinkImageFilter() + { + Superclass::SetNumberOfThreads(1); + } private: NonThreadedShrinkImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented - - unsigned int m_ShrinkFactors[ImageDimension]; }; } // end namespace itk -#ifndef ITK_MANUAL_INSTANTIATION -#include "itkNonThreadedShrinkImageFilter.txx" -#endif - #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkNonThreadedShrinkImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkNonThreadedShrinkImageFilter.txx deleted file mode 100644 index 846838be72..0000000000 --- a/Utilities/ITK/Code/BasicFilters/itkNonThreadedShrinkImageFilter.txx +++ /dev/null @@ -1,267 +0,0 @@ -/*========================================================================= - - Program: Insight Segmentation & Registration Toolkit - Module: $RCSfile: itkNonThreadedShrinkImageFilter.txx,v $ - Language: C++ - Date: $Date: 2008-10-16 19:33:45 $ - Version: $Revision: 1.23 $ - - Copyright (c) Insight Software Consortium. All rights reserved. - See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ -#ifndef __itkNonThreadedShrinkImageFilter_txx -#define __itkNonThreadedShrinkImageFilter_txx - -#include "itkNonThreadedShrinkImageFilter.h" -#include "itkImageRegionIterator.h" -#include "itkObjectFactory.h" -#include "itkProgressReporter.h" - -namespace itk -{ - -/** - * - */ -template <class TInputImage, class TOutputImage> -NonThreadedShrinkImageFilter<TInputImage,TOutputImage> -::NonThreadedShrinkImageFilter() -{ - for( unsigned int j = 0; j < ImageDimension; j++ ) - { - m_ShrinkFactors[j] = 1; - } -} - - -/** - * - */ -template <class TInputImage, class TOutputImage> -void -NonThreadedShrinkImageFilter<TInputImage,TOutputImage> -::PrintSelf(std::ostream& os, Indent indent) const -{ - Superclass::PrintSelf(os,indent); - - os << indent << "Shrink Factor: "; - for( unsigned int j = 0; j < ImageDimension; j++ ) - { - os << m_ShrinkFactors[j] << " "; - } - os << std::endl; -} - - -/** - * - */ -template <class TInputImage, class TOutputImage> -void -NonThreadedShrinkImageFilter<TInputImage,TOutputImage> -::SetShrinkFactors(unsigned int factors[]) -{ - unsigned int j; - for( j = 0; j < ImageDimension; j++ ) - { - if( factors[j] != m_ShrinkFactors[j] ) break; - } - if( j < ImageDimension ) - { - this->Modified(); - for( j = 0; j < ImageDimension; j++ ) - { - m_ShrinkFactors[j] = factors[j]; - if( m_ShrinkFactors[j] < 1 ) - { - m_ShrinkFactors[j] = 1; - } - } - } -} - - -/** - * - */ -template <class TInputImage, class TOutputImage> -void -NonThreadedShrinkImageFilter<TInputImage,TOutputImage> -::SetShrinkFactors(unsigned int factor) -{ - unsigned int j; - for( j = 0; j < ImageDimension; j++ ) - { - if( factor != m_ShrinkFactors[j] ) break; - } - if( j < ImageDimension ) - { - this->Modified(); - for( j = 0; j < ImageDimension; j++ ) - { - m_ShrinkFactors[j] = factor; - if( m_ShrinkFactors[j] < 1 ) - { - m_ShrinkFactors[j] = 1; - } - } - } -} - -/** - * - */ -template <class TInputImage, class TOutputImage> -void -NonThreadedShrinkImageFilter<TInputImage,TOutputImage> -::GenerateData() -{ - itkDebugMacro(<<"Actually executing"); - - // Get the input and output pointers - typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); - typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); - - // Since we are providing a GenerateData() method, we need to allocate the - // output buffer memory (if we provided a ThreadedGenerateData(), then - // the memory would have already been allocated for us). - outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() ); - outputPtr->Allocate(); - - // Define/declare an iterator that will walk the output region - typedef - ImageRegionIterator<TOutputImage> OutputIterator; - - OutputIterator outIt = OutputIterator(outputPtr, - outputPtr->GetRequestedRegion()); - - // Define a few indices that will be used to translate from an input pixel - // to an output pixel - typename TOutputImage::IndexType outputIndex; - typename TInputImage::IndexType inputIndex; - typename TInputImage::SizeType factorSize; - - for (unsigned int i=0; i < TInputImage::ImageDimension; i++) - { - factorSize[i] = m_ShrinkFactors[i]; - } - - // support progress methods/callbacks - ProgressReporter progress(this, 0, outputPtr->GetRequestedRegion().GetNumberOfPixels()); - - // walk the output image, and sample the input image - while ( !outIt.IsAtEnd() ) - { - // determine the index of the output pixel - outputIndex = outIt.GetIndex(); - - // determine the input pixel location associated with this output pixel - inputIndex = outputIndex * factorSize; - - // copy the input pixel to the output - outIt.Set( inputPtr->GetPixel(inputIndex) ); - ++outIt; - - progress.CompletedPixel(); - } -} - -/** - * - */ -template <class TInputImage, class TOutputImage> -void -NonThreadedShrinkImageFilter<TInputImage,TOutputImage> -::GenerateInputRequestedRegion() -{ - // call the superclass' implementation of this method - Superclass::GenerateInputRequestedRegion(); - - // get pointers to the input and output - InputImagePointer inputPtr = const_cast<TInputImage *> (this->GetInput()); - OutputImagePointer outputPtr = this->GetOutput(); - - if ( !inputPtr || !outputPtr ) - { - return; - } - - // we need to compute the input requested region (size and start index) - const typename TOutputImage::SizeType& outputRequestedRegionSize - = outputPtr->GetRequestedRegion().GetSize(); - const typename TOutputImage::IndexType& outputRequestedRegionStartIndex - = outputPtr->GetRequestedRegion().GetIndex(); - - typename TInputImage::SizeType inputRequestedRegionSize; - typename TInputImage::IndexType inputRequestedRegionStartIndex; - - for (unsigned int i = 0; i < TInputImage::ImageDimension; i++) - { - inputRequestedRegionSize[i] - = outputRequestedRegionSize[i] * m_ShrinkFactors[i]; - inputRequestedRegionStartIndex[i] - = outputRequestedRegionStartIndex[i] * (long)m_ShrinkFactors[i]; - } - - typename TInputImage::RegionType inputRequestedRegion; - inputRequestedRegion.SetSize( inputRequestedRegionSize ); - inputRequestedRegion.SetIndex( inputRequestedRegionStartIndex ); - - inputPtr->SetRequestedRegion( inputRequestedRegion ); -} - -/** - * - */ -template <class TInputImage, class TOutputImage> -void -NonThreadedShrinkImageFilter<TInputImage,TOutputImage> -::GenerateOutputInformation() -{ - // call the superclass' implementation of this method - Superclass::GenerateOutputInformation(); - - // get pointers to the input and output - typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); - typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); - - // we need to compute the output spacing, the output image size, and the - // output image start index - const typename TInputImage::SpacingType& - inputSpacing = inputPtr->GetSpacing(); - const typename TInputImage::SizeType& inputSize - = inputPtr->GetLargestPossibleRegion().GetSize(); - const typename TInputImage::IndexType& inputStartIndex - = inputPtr->GetLargestPossibleRegion().GetIndex(); - - typename TOutputImage::SpacingType outputSpacing; - typename TOutputImage::SizeType outputSize; - typename TOutputImage::IndexType outputStartIndex; - - for (unsigned int i = 0; i < TOutputImage::ImageDimension; i++) - { - outputSpacing[i] = inputSpacing[i] * (double) m_ShrinkFactors[i]; - outputSize[i] = (unsigned int) - vcl_floor(((double)(inputSize[i] - m_ShrinkFactors[i] + 1)) - / (double) m_ShrinkFactors[i]); - outputStartIndex[i] = (int) - vcl_ceil((double) inputStartIndex[i] / (double) m_ShrinkFactors[i] ); - } - - outputPtr->SetSpacing( outputSpacing ); - - typename TOutputImage::RegionType outputLargestPossibleRegion; - outputLargestPossibleRegion.SetSize( outputSize ); - outputLargestPossibleRegion.SetIndex( outputStartIndex ); - - outputPtr->SetLargestPossibleRegion( outputLargestPossibleRegion ); -} - -} // end namespace itk - -#endif diff --git a/Utilities/ITK/Code/BasicFilters/itkNormalVectorDiffusionFunction.h b/Utilities/ITK/Code/BasicFilters/itkNormalVectorDiffusionFunction.h index a859746ab6..b38d07c7ea 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNormalVectorDiffusionFunction.h +++ b/Utilities/ITK/Code/BasicFilters/itkNormalVectorDiffusionFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNormalVectorDiffusionFunction.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:45 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-06 11:15:08 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -139,9 +139,9 @@ protected: areas with large curvature. */ NodeValueType FluxStopFunction( const NodeValueType v ) const { - // the slow ::exp function could be replaced with a lookup table + // the slow exp function could be replaced with a lookup table if (v<=0.0) return NumericTraits<NodeValueType>::One; - else return static_cast<NodeValueType>(::exp(m_FluxStopConstant*v)); + else return static_cast<NodeValueType>(vcl_exp(m_FluxStopConstant*v)); } private: diff --git a/Utilities/ITK/Code/BasicFilters/itkNotImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkNotImageFilter.h index cfba3ee549..bcaae70113 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNotImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkNotImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNotImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:45 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,7 +59,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( !A ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkObjectMorphologyImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkObjectMorphologyImageFilter.h index de8afd8682..64e1b29b4b 100644 --- a/Utilities/ITK/Code/BasicFilters/itkObjectMorphologyImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkObjectMorphologyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkObjectMorphologyImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:56:22 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:27:45 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -130,7 +130,7 @@ public: itkGetConstReferenceMacro(Kernel, KernelType); /** Get the pixel value being used to identify the object of interest */ - itkGetMacro(ObjectValue, PixelType); + itkGetConstMacro(ObjectValue, PixelType); /** Set the pixel value being used to identify the object of interest */ itkSetMacro(ObjectValue, PixelType); @@ -156,7 +156,7 @@ public: { m_BoundaryCondition = &m_DefaultBoundaryCondition; } /** Get the current boundary condition. */ - itkGetMacro(BoundaryCondition, ImageBoundaryConditionPointerType); + itkGetConstMacro(BoundaryCondition, ImageBoundaryConditionPointerType); /** Enable/disable the use of boundary condition. Defaults to false. * if false, a neighborhood operator extends outside an image, it does @@ -168,7 +168,7 @@ public: * if false, a neighborhood operator extends outside an image, it does * not consider that outside extent when determining if a pixel is on * an object's boundary. */ - itkGetMacro(UseBoundaryCondition, bool); + itkGetConstMacro(UseBoundaryCondition, bool); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkOrImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkOrImageFilter.h index 0bb4543405..547cc9c768 100755 --- a/Utilities/ITK/Code/BasicFilters/itkOrImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkOrImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOrImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-14 19:56:22 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,7 +59,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { return static_cast<TOutput>( A | B ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkOrientImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkOrientImageFilter.h index c60224815e..bdb9e2e943 100644 --- a/Utilities/ITK/Code/BasicFilters/itkOrientImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkOrientImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOrientImageFilter.h,v $ Language: C++ -Date: $Date: 2008-10-14 19:56:22 $ -Version: $Revision: 1.11 $ +Date: $Date: 2009-04-25 12:27:46 $ +Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -210,7 +210,7 @@ public: * "off". */ itkBooleanMacro(UseImageDirection); - itkGetMacro(UseImageDirection, bool); + itkGetConstMacro(UseImageDirection, bool); itkSetMacro(UseImageDirection, bool); /** Get axes permute order. */ diff --git a/Utilities/ITK/Code/BasicFilters/itkParallelSparseFieldLevelSetImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkParallelSparseFieldLevelSetImageFilter.h index b22484888a..f502a5c1cf 100644 --- a/Utilities/ITK/Code/BasicFilters/itkParallelSparseFieldLevelSetImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkParallelSparseFieldLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkParallelSparseFieldLevelSetImageFilter.h,v $ Language: C++ -Date: $Date: 2008-10-17 16:30:48 $ -Version: $Revision: 1.17 $ +Date: $Date: 2009-04-25 12:27:47 $ +Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -308,11 +308,11 @@ public: * number of layers on ONE side of the active layer, so the total layers in * the sparse field is 2 * NumberOfLayers + 1 */ itkSetMacro(NumberOfLayers, StatusType); - itkGetMacro(NumberOfLayers, StatusType); + itkGetConstMacro(NumberOfLayers, StatusType); /** Set/Get the value of the isosurface to use in the input image. */ itkSetMacro(IsoSurfaceValue, ValueType); - itkGetMacro(IsoSurfaceValue, ValueType); + itkGetConstMacro(IsoSurfaceValue, ValueType); LayerPointerType GetActiveListForIndex (const IndexType index) { diff --git a/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.h index 23cf5a7bfc..5a458809c3 100644 --- a/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPasteImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:48 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:27:48 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -92,12 +92,12 @@ public: /** Set/Get the destination index (where in the first input the second * input will be pasted. */ itkSetMacro(DestinationIndex, InputImageIndexType); - itkGetMacro(DestinationIndex, InputImageIndexType); + itkGetConstMacro(DestinationIndex, InputImageIndexType); /** Set/Get the source region (what part of the second input will be * pasted. */ itkSetMacro(SourceRegion, SourceImageRegionType); - itkGetMacro(SourceRegion, SourceImageRegionType); + itkGetConstMacro(SourceRegion, SourceImageRegionType); /** Set/Get the "destination" image. This is the image that will be * obscured by the paste operation. */ diff --git a/Utilities/ITK/Code/BasicFilters/itkPathToImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkPathToImageFilter.h index 6164ff6411..07fa8afaca 100644 --- a/Utilities/ITK/Code/BasicFilters/itkPathToImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkPathToImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPathToImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:49 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-25 12:27:50 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -78,9 +78,9 @@ public: /** Set/Get the value for pixels on and off the path. * By default, this filter will return a "0" image with path pixels set to 1 */ itkSetMacro(PathValue, ValueType); - itkGetMacro(PathValue, ValueType); + itkGetConstMacro(PathValue, ValueType); itkSetMacro(BackgroundValue, ValueType); - itkGetMacro(BackgroundValue, ValueType); + itkGetConstMacro(BackgroundValue, ValueType); /** The origin of the output image. The origin is the geometric * coordinates of the index (0,0,...,0). It is stored internally @@ -92,7 +92,7 @@ public: /** Set/Get Size */ itkSetMacro(Size,SizeType); - itkGetMacro(Size,SizeType); + itkGetConstMacro(Size,SizeType); protected: PathToImageFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkPointSetToImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkPointSetToImageFilter.h index f235152eff..b63081e900 100644 --- a/Utilities/ITK/Code/BasicFilters/itkPointSetToImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkPointSetToImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointSetToImageFilter.h,v $ Language: C++ - Date: $Date: 2008-11-08 13:12:22 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:27:54 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -115,7 +115,7 @@ public: * the output produced by this filter will be a mask with inside/outside values * specified by the user. */ itkSetMacro(InsideValue, ValueType); - itkGetMacro(InsideValue, ValueType); + itkGetConstMacro(InsideValue, ValueType); /** Set/Get the value for pixels outside the point-set. * By default, this filter will return an image @@ -124,11 +124,11 @@ public: * the output produced by this filter will be a mask with inside/outside values * specified by the user. */ itkSetMacro(OutsideValue, ValueType); - itkGetMacro(OutsideValue, ValueType); + itkGetConstMacro(OutsideValue, ValueType); /** Set/Get Size */ itkSetMacro(Size,SizeType); - itkGetMacro(Size,SizeType); + itkGetConstMacro(Size,SizeType); protected: PointSetToImageFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkRGBToLuminanceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkRGBToLuminanceImageFilter.h index fef6ba6ecb..f51a2418e7 100755 --- a/Utilities/ITK/Code/BasicFilters/itkRGBToLuminanceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkRGBToLuminanceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBToLuminanceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:50 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,7 +51,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( A.GetLuminance() ); } }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.h b/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.h index a7597f717d..2aa41fe8c5 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.h +++ b/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRandomImageSource.h,v $ Language: C++ - Date: $Date: 2007-12-21 15:35:40 $ - Version: $Revision: 1.42 $ + Date: $Date: 2009-04-25 12:27:55 $ + Version: $Revision: 1.43 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,7 +85,7 @@ public: NumericTraits<OutputImagePixelType>::max()); /** Get the minimum possible pixel value. */ - itkGetMacro(Min, OutputImagePixelType); + itkGetConstMacro(Min, OutputImagePixelType); /** Set the maximum possible pixel value. By default, it is * NumericTraits<TOutputImage::PixelType>::max(). */ @@ -94,7 +94,7 @@ public: NumericTraits<OutputImagePixelType>::max()); /** Get the maximum possible pixel value. */ - itkGetMacro(Max, OutputImagePixelType); + itkGetConstMacro(Max, OutputImagePixelType); protected: RandomImageSource(); diff --git a/Utilities/ITK/Code/BasicFilters/itkRecursiveGaussianImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkRecursiveGaussianImageFilter.h index 0a4e39a971..269614882d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkRecursiveGaussianImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRecursiveGaussianImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:50 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-04-25 12:28:00 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -74,7 +74,7 @@ public: /** Set/Get the Sigma, measured in world coordinates, of the Gaussian * kernel. The default is 1.0. */ - itkGetMacro( Sigma, ScalarRealType ); + itkGetConstMacro( Sigma, ScalarRealType ); itkSetMacro( Sigma, ScalarRealType ); /** Enum type that indicates if the filter applies the equivalent operation @@ -102,7 +102,7 @@ public: For analyzing an image across Scale Space you want to enable this flag. It is disabled by default. */ itkSetMacro( NormalizeAcrossScale, bool ); - itkGetMacro( NormalizeAcrossScale, bool ); + itkGetConstMacro( NormalizeAcrossScale, bool ); /** Set/Get the Order of the Gaussian to convolve with. \li ZeroOrder is equivalent to convolving with a Gaussian. This @@ -111,7 +111,7 @@ public: \li SecondOrder is equivalent to convolving with the second derivative of a Gaussian. */ itkSetMacro( Order, OrderEnumType ); - itkGetMacro( Order, OrderEnumType ); + itkGetConstMacro( Order, OrderEnumType ); /** Explicitly set a zeroth order derivative. */ void SetZeroOrder(); diff --git a/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.h index 1d6c91cd42..77a3282757 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRecursiveSeparableImageFilter.h,v $ Language: C++ - Date: $Date: 2008-07-31 09:14:58 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-04-25 12:28:01 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,7 +81,7 @@ public: typedef TOutputImage OutputImageType; /** Get the direction in which the filter is to be applied. */ - itkGetMacro(Direction, unsigned int); + itkGetConstMacro(Direction, unsigned int); /** Set the direction in which the filter is to be applied. */ itkSetMacro(Direction, unsigned int); diff --git a/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.txx index 96b7d8e636..e1adc732d1 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRecursiveSeparableImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-07-31 09:14:58 $ - Version: $Revision: 1.42 $ + Date: $Date: 2009-04-06 13:46:37 $ + Version: $Revision: 1.43 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -226,8 +226,8 @@ RecursiveSeparableImageFilter<TInputImage,TOutputImage> // determine the actual number of pieces that will be generated typename TOutputImage::SizeType::SizeValueType range = requestedRegionSize[splitAxis]; - int valuesPerThread = (int)::ceil(range/(double)num); - int maxThreadIdUsed = (int)::ceil(range/(double)valuesPerThread) - 1; + int valuesPerThread = (int)vcl_ceil(range/(double)num); + int maxThreadIdUsed = (int)vcl_ceil(range/(double)valuesPerThread) - 1; // Split the region if (i < maxThreadIdUsed) diff --git a/Utilities/ITK/Code/BasicFilters/itkReflectImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkReflectImageFilter.h index 048a3484cb..0eaa87c4b5 100644 --- a/Utilities/ITK/Code/BasicFilters/itkReflectImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkReflectImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkReflectImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:50 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:28:02 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,7 +58,7 @@ public: typedef typename OutputImageType::PixelType OutputImagePixelType; /** Set the direction in which to reflect the data. */ - itkGetMacro( Direction, unsigned int ); + itkGetConstMacro( Direction, unsigned int ); itkSetMacro( Direction, unsigned int ); /** ImageDimension constants */ diff --git a/Utilities/ITK/Code/BasicFilters/itkRegionOfInterestImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkRegionOfInterestImageFilter.h index 7633330ff1..afed764dc4 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRegionOfInterestImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkRegionOfInterestImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegionOfInterestImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:51 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-25 12:28:05 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,7 +73,7 @@ public: /** Set/Get the output image region. */ itkSetMacro(RegionOfInterest, RegionType); - itkGetMacro(RegionOfInterest, RegionType); + itkGetConstMacro(RegionOfInterest, RegionType); /** ImageDimension enumeration */ itkStaticConstMacro(ImageDimension, unsigned int, diff --git a/Utilities/ITK/Code/BasicFilters/itkRelabelComponentImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkRelabelComponentImageFilter.h index b57e3369c7..bf19142c64 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRelabelComponentImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkRelabelComponentImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRelabelComponentImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:52 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-27 22:58:48 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -124,21 +124,27 @@ public: */ itkNewMacro(Self); + /** Type used as identifier for the different component lables. */ + typedef unsigned long int LabelType; + + /** Type used to count number of pixels in objects. */ + typedef unsigned long int ObjectSizeType; + /** Get the number of objects in the image. This information is only * valid after the filter has executed. */ - itkGetMacro(NumberOfObjects, unsigned long); + itkGetConstMacro(NumberOfObjects, LabelType); /** Get the original number of objects in the image before small * objects were discarded. This information is only valid after * the filter has executed. If the caller has not specified a * minimum object size, OriginalNumberOfObjects is the same as * NumberOfObjects. */ - itkGetMacro(OriginalNumberOfObjects, unsigned long); + itkGetConstMacro(OriginalNumberOfObjects, LabelType); /** Get/Set the number of objects enumerated and described when the * filter is printed. */ - itkSetMacro(NumberOfObjectsToPrint, unsigned long); - itkGetConstReferenceMacro(NumberOfObjectsToPrint, unsigned long); + itkSetMacro(NumberOfObjectsToPrint, LabelType); + itkGetConstReferenceMacro(NumberOfObjectsToPrint, LabelType); /** Set the minimum size in pixels for an object. All objects * smaller than this size will be discarded and will not appear @@ -146,21 +152,21 @@ public: * objects whose pixel counts are greater than or equal to the * minimum size. Call GetOriginalNumberOfObjects to find out how * many objects were present in the original label map. */ - itkSetMacro(MinimumObjectSize, unsigned long); + itkSetMacro(MinimumObjectSize, ObjectSizeType); /** Get the caller-defined minimum size of an object in pixels. * If the caller has not set the minimum, 0 will be returned, * which is to be interpreted as meaning that no minimum exists, * and all objects in the original label map will be passed * through to the output. */ - itkGetMacro(MinimumObjectSize, unsigned long); + itkGetConstMacro(MinimumObjectSize, ObjectSizeType); /** Get the size of each object in pixels. This information is only * valid after the filter has executed. Size of the background is * not calculated. Size of object #1 is * GetSizeOfObjectsInPixels()[0]. Size of object #2 is * GetSizeOfObjectsInPixels()[1]. Etc. */ - const std::vector<unsigned long>& GetSizeOfObjectsInPixels() const + const std::vector<ObjectSizeType>& GetSizeOfObjectsInPixels() const { return m_SizeOfObjectsInPixels; } /** Get the size of each object in physical space (in units of pixel @@ -174,7 +180,7 @@ public: /** Get the size of a particular object in pixels. This information is only * valid after the filter has executed. Size of the background * (object #0) is not calculated. */ - unsigned long GetSizeOfObjectInPixels(unsigned long obj) const + ObjectSizeType GetSizeOfObjectInPixels( LabelType obj ) const { if (obj > 0 && obj <= m_NumberOfObjects) { @@ -189,7 +195,7 @@ public: /** Get the size of a particular object in physical space (in units of pixel * size). This information is only valid after the filter has * executed. Size of the background (object #0) is not calculated. */ - float GetSizeOfObjectInPhysicalUnits(unsigned long obj) const + float GetSizeOfObjectInPhysicalUnits( LabelType obj ) const { if (obj > 0 && obj <= m_NumberOfObjects) { @@ -206,9 +212,9 @@ public: itkConceptMacro(InputEqualityComparableCheck, (Concept::EqualityComparable<InputPixelType>)); itkConceptMacro(UnsignedLongConvertibleToInputCheck, - (Concept::Convertible<unsigned long, InputPixelType>)); + (Concept::Convertible<LabelType, InputPixelType>)); itkConceptMacro(OutputLongConvertibleToUnsignedLongCheck, - (Concept::Convertible<OutputPixelType, unsigned long>)); + (Concept::Convertible<OutputPixelType, LabelType>)); itkConceptMacro(InputConvertibleToOutputCheck, (Concept::Convertible<InputPixelType, OutputPixelType>)); itkConceptMacro(SameDimensionCheck, @@ -240,9 +246,9 @@ protected: struct RelabelComponentObjectType { - unsigned long m_ObjectNumber; - unsigned long m_SizeInPixels; - float m_SizeInPhysicalUnits; + LabelType m_ObjectNumber; + ObjectSizeType m_SizeInPixels; + float m_SizeInPhysicalUnits; }; // put the function objects here for sorting in descending order @@ -276,13 +282,13 @@ protected: private: - unsigned long m_NumberOfObjects; - unsigned long m_NumberOfObjectsToPrint; - unsigned long m_OriginalNumberOfObjects; - unsigned long m_MinimumObjectSize; + LabelType m_NumberOfObjects; + LabelType m_NumberOfObjectsToPrint; + LabelType m_OriginalNumberOfObjects; + ObjectSizeType m_MinimumObjectSize; - std::vector<unsigned long> m_SizeOfObjectsInPixels; - std::vector<float> m_SizeOfObjectsInPhysicalUnits; + std::vector<ObjectSizeType> m_SizeOfObjectsInPixels; + std::vector<float> m_SizeOfObjectsInPhysicalUnits; }; diff --git a/Utilities/ITK/Code/BasicFilters/itkRelabelComponentImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkRelabelComponentImageFilter.txx index 2759896af7..8752e0b8db 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRelabelComponentImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkRelabelComponentImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRelabelComponentImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:52 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-27 22:58:48 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -54,7 +54,7 @@ RelabelComponentImageFilter< TInputImage, TOutputImage > // Use a map to keep track of the size of each object. Object // number -> ObjectType (which has Object number and the two sizes) - typedef itk::hash_map<unsigned long, RelabelComponentObjectType> MapType; + typedef itk::hash_map<LabelType, RelabelComponentObjectType> MapType; MapType sizeMap; typename MapType::iterator mapIt; typedef typename MapType::value_type MapValueType; @@ -88,18 +88,16 @@ RelabelComponentImageFilter< TInputImage, TOutputImage > // // walk the input - InputPixelType inputValue; - ImageRegionConstIterator<InputImageType> it; - it = ImageRegionConstIterator<InputImageType>(input, - input->GetRequestedRegion()); + ImageRegionConstIterator<InputImageType> it(input, input->GetRequestedRegion()); it.GoToBegin(); + while (!it.IsAtEnd()) { // Get the input pixel value - inputValue = it.Get(); + const LabelType inputValue = static_cast< LabelType>( it.Get() ); // if the input pixel is not the background - if (inputValue != NumericTraits<InputPixelType>::Zero) + if (inputValue != NumericTraits<LabelType>::Zero) { // Does this label already exist mapIt = sizeMap.find( inputValue ); @@ -130,7 +128,7 @@ RelabelComponentImageFilter< TInputImage, TOutputImage > VectorType sizeVector; typename VectorType::iterator vit; - typedef std::map<unsigned long, unsigned long> RelabelMapType; + typedef std::map< LabelType, LabelType > RelabelMapType; RelabelMapType relabelMap; // copy the original object map to a vector so we can sort it @@ -203,10 +201,9 @@ RelabelComponentImageFilter< TInputImage, TOutputImage > oit.GoToBegin(); while ( !oit.IsAtEnd() ) { - inputValue = it.Get(); - // std::cerr << std::endl << "inputValue: " << inputValue << " m_SizeOfObjectsInPixels[inputValue]: " << - // m_SizeOfObjectsInPixels[inputValue] << std::endl; - if (inputValue != NumericTraits<InputPixelType>::Zero) + const LabelType inputValue = static_cast< LabelType>( it.Get() ); + + if (inputValue != NumericTraits<LabelType>::Zero) { // lookup the mapped label @@ -239,12 +236,12 @@ RelabelComponentImageFilter< TInputImage, TOutputImage > << m_NumberOfObjectsToPrint << std::endl; os << indent << "MinimumObjectSizez: " << m_MinimumObjectSize << std::endl; - std::vector<unsigned long>::const_iterator it; + std::vector<ObjectSizeType>::const_iterator it; std::vector<float>::const_iterator fit; - unsigned long i; + LabelType i; // limit the number of objects to print - unsigned long numPrint = m_NumberOfObjectsToPrint; + LabelType numPrint = m_NumberOfObjectsToPrint; if (numPrint > m_SizeOfObjectsInPixels.size()) { numPrint = m_SizeOfObjectsInPixels.size(); diff --git a/Utilities/ITK/Code/BasicFilters/itkResampleImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkResampleImageFilter.h index bf8b206f20..23058c6abd 100644 --- a/Utilities/ITK/Code/BasicFilters/itkResampleImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkResampleImageFilter.h @@ -3,14 +3,14 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkResampleImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-18 13:30:38 $ - Version: $Revision: 1.59 $ + Date: $Date: 2009-04-25 12:28:07 $ + Version: $Revision: 1.62 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -69,7 +69,7 @@ namespace itk * ProcessObject::GenerateInputRequestedRegion() and * ProcessObject::GenerateOutputInformation(). * - * This filter is implemented as a multithreaded filter. It provides a + * This filter is implemented as a multithreaded filter. It provides a * ThreadedGenerateData() method for its implementation. * * \ingroup GeometricTransforms @@ -94,7 +94,7 @@ public: typedef typename InputImageType::RegionType InputImageRegionType; /** Method for creation through the object factory. */ - itkNewMacro(Self); + itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(ResampleImageFilter, ImageToImageFilter); @@ -109,7 +109,7 @@ public: /** Transform typedef. */ typedef double CoordRepType; typedef Transform<CoordRepType, - itkGetStaticConstMacro(ImageDimension), + itkGetStaticConstMacro(ImageDimension), itkGetStaticConstMacro(ImageDimension)> TransformType; typedef typename TransformType::ConstPointer TransformPointerType; @@ -130,7 +130,7 @@ public: /** Image pixel value typedef. */ typedef typename TOutputImage::PixelType PixelType; typedef typename TInputImage::PixelType InputPixelType; - + /** Typedef to describe the output image region type. */ typedef typename TOutputImage::RegionType OutputImageRegionType; @@ -139,6 +139,9 @@ public: typedef typename TOutputImage::PointType OriginPointType; typedef typename TOutputImage::DirectionType DirectionType; + /** base type for images of the current ImageDimension */ + typedef ImageBase<itkGetStaticConstMacro(ImageDimension)> ImageBaseType; + /** Set the coordinate transformation. * Set the coordinate transform to use for resampling. Note that this must * be in physical coordinates and it is the output-to-input transform, NOT @@ -146,7 +149,7 @@ public: * the filter uses an Identity transform. You must provide a different * transform here, before attempting to run the filter, if you do not want to * use the default Identity transform. */ - itkSetConstObjectMacro( Transform, TransformType ); + itkSetConstObjectMacro( Transform, TransformType ); /** Get a pointer to the coordinate transform. */ itkGetConstObjectMacro( Transform, TransformType ); @@ -167,7 +170,7 @@ public: /** Get the size of the output image. */ itkGetConstReferenceMacro( Size, SizeType ); - + /** Set the pixel value when a transformed pixel is outside of the * image. The default default pixel value is 0. */ itkSetMacro( DefaultPixelValue, PixelType ); @@ -194,25 +197,13 @@ public: itkGetConstReferenceMacro( OutputDirection, DirectionType ); /** Helper method to set the output parameters based on this image */ - void SetOutputParametersFromImage ( typename OutputImageType::Pointer Image ) - { - this->SetOutputOrigin ( Image->GetOrigin() ); - this->SetOutputSpacing ( Image->GetSpacing() ); - this->SetOutputDirection ( Image->GetDirection() ); - this->SetOutputStartIndex ( Image->GetLargestPossibleRegion().GetIndex() ); - this->SetSize ( Image->GetLargestPossibleRegion().GetSize() ); - } + void SetOutputParametersFromImage ( const ImageBaseType * image ); - /** Helper method to set the output parameters based on this image */ - void SetOutputParametersFromConstImage ( typename OutputImageType::ConstPointer Image ) - { - this->SetOutputOrigin ( Image->GetOrigin() ); - this->SetOutputSpacing ( Image->GetSpacing() ); - this->SetOutputDirection ( Image->GetDirection() ); - this->SetOutputStartIndex ( Image->GetLargestPossibleRegion().GetIndex() ); this->SetSize ( Image->GetLargestPossibleRegion().GetSize() ); - } - - /** Set the start index of the output largest possible region. + /** \deprecated in ITK 3.14, Please use SetOutputParametersFromImage(). + * Helper method to set the output parameters based on this image. */ + itkLegacyMacro( void SetOutputParametersFromConstImage ( const ImageBaseType * image ) ); + + /** Set the start index of the output largest possible region. * The default is an index of all zeros. */ itkSetMacro( OutputStartIndex, IndexType ); @@ -223,14 +214,14 @@ public: * the information is specified with the SetOutputSpacing, Origin, * and Direction methods. UseReferenceImage must be On and a * Reference image must be present to override the defaul behavior. - * NOTE: This function seems redundant with the + * NOTE: This function seems redundant with the * SetOutputParametersFromImage( image ) function */ void SetReferenceImage ( const TOutputImage *image ); const TOutputImage * GetReferenceImage( void ) const; itkSetMacro( UseReferenceImage, bool ); itkBooleanMacro( UseReferenceImage ); - itkGetMacro( UseReferenceImage, bool ); + itkGetConstMacro( UseReferenceImage, bool ); /** ResampleImageFilter produces an image which is a different size * than its input. As such, it needs to provide an implementation @@ -246,11 +237,11 @@ public: * \sa ProcessObject::GenerateInputRequestedRegion() */ virtual void GenerateInputRequestedRegion( void ); - /** This method is used to set the state of the filter before + /** This method is used to set the state of the filter before * multi-threading. */ virtual void BeforeThreadedGenerateData( void ); - /** This method is used to set the state of the filter after + /** This method is used to set the state of the filter after * multi-threading. */ virtual void AfterThreadedGenerateData( void ); @@ -287,12 +278,12 @@ protected: int threadId ); /** Implementation for resampling that works for with linear - * transformation types. + * transformation types. */ void LinearThreadedGenerateData( const OutputImageRegionType& outputRegionForThread, int threadId ); - + private: ResampleImageFilter( const Self& ); //purposely not implemented @@ -313,13 +304,13 @@ private: }; - + } // end namespace itk - + #ifndef ITK_MANUAL_INSTANTIATION #include "itkResampleImageFilter.txx" #endif - + #endif - + #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkResampleImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkResampleImageFilter.txx index 17777312d8..0a69ada700 100644 --- a/Utilities/ITK/Code/BasicFilters/itkResampleImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkResampleImageFilter.txx @@ -3,14 +3,14 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkResampleImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-11-15 11:06:55 $ - Version: $Revision: 1.64 $ + Date: $Date: 2009-03-25 21:10:39 $ + Version: $Revision: 1.66 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -54,7 +54,7 @@ ResampleImageFilter<TInputImage, TOutputImage,TInterpolatorPrecisionType> m_Size.Fill( 0 ); m_OutputStartIndex.Fill( 0 ); - + typedef double CoordRepType; m_Transform = IdentityTransform<CoordRepType, ImageDimension>::New(); m_Interpolator = LinearInterpolateImageFunction<InputImageType, CoordRepType>::New(); @@ -68,12 +68,12 @@ ResampleImageFilter<TInputImage, TOutputImage,TInterpolatorPrecisionType> * \todo Add details about this class */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage, TOutputImage,TInterpolatorPrecisionType> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); - + os << indent << "DefaultPixelValue: " << static_cast<typename NumericTraits<PixelType>::PrintType>(m_DefaultPixelValue) << std::endl; @@ -92,7 +92,7 @@ ResampleImageFilter<TInputImage, TOutputImage,TInterpolatorPrecisionType> * Set the output image spacing. */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::SetOutputSpacing( const double* spacing) @@ -106,7 +106,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> * Set the output image origin. */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::SetOutputOrigin( const double* origin) @@ -122,7 +122,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> * has to be set up before ThreadedGenerateData */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::BeforeThreadedGenerateData() { @@ -145,7 +145,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> * Set up state of filter after multi-threading. */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::AfterThreadedGenerateData() { @@ -158,7 +158,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> * ThreadedGenerateData */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::ThreadedGenerateData( const OutputImageRegionType& outputRegionForThread, @@ -184,7 +184,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> this->NonlinearThreadedGenerateData(outputRegionForThread, threadId); return; } - + // Check whether we can use a fast path for resampling. Fast path // can be used if the transformation is linear. Transform respond // to the IsLinear() call. @@ -197,12 +197,12 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> // Otherwise, we use the normal method where the transform is called // for computing the transformation of every point. this->NonlinearThreadedGenerateData(outputRegionForThread, threadId); - + } template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::NonlinearThreadedGenerateData( const OutputImageRegionType& outputRegionForThread, @@ -230,7 +230,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> // Support for progress methods/callbacks ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - + typedef typename InterpolatorType::OutputType OutputType; // Min/max values of the output pixel type AND these values @@ -240,7 +240,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> const OutputType minOutputValue = static_cast<OutputType>(minValue); const OutputType maxOutputValue = static_cast<OutputType>(maxValue); - + // Walk the output region outIt.GoToBegin(); @@ -260,7 +260,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> inputPtr->TransformPhysicalPointToContinuousIndex(inputPoint, inputIndex); // The inputIndex is precise to many decimal points, but this precision - // involves some error in the last bits. + // involves some error in the last bits. // Sometimes, when an index should be inside of the image, the // index will be slightly // greater than the largest index in the image, like 255.00000000002 @@ -276,7 +276,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> double newInputIndexFrac = vcl_floor(precisionConstant * inputIndexFrac)/precisionConstant; inputIndex[i] = roundedInputIndex + newInputIndexFrac; } - + // Evaluate input at right position and copy to the output if( m_Interpolator->IsInsideBuffer(inputIndex) ) { @@ -301,7 +301,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> } template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::LinearThreadedGenerateData( const OutputImageRegionType& outputRegionForThread, @@ -330,14 +330,14 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> typedef ContinuousIndex<CoordRepType, ImageDimension> ContinuousIndexType; ContinuousIndexType inputIndex; ContinuousIndexType tmpInputIndex; - + typedef typename PointType::VectorType VectorType; VectorType delta; // delta in input continuous index coordinate frame IndexType index; // Support for progress methods/callbacks ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - + typedef typename InterpolatorType::OutputType OutputType; // Cache information from the superclass @@ -350,34 +350,34 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> const OutputType minOutputValue = static_cast<OutputType>(minValue); const OutputType maxOutputValue = static_cast<OutputType>(maxValue); - - + + // Determine the position of the first pixel in the scanline index = outIt.GetIndex(); outputPtr->TransformIndexToPhysicalPoint( index, outputPoint ); - + // Compute corresponding input pixel position inputPoint = m_Transform->TransformPoint(outputPoint); inputPtr->TransformPhysicalPointToContinuousIndex(inputPoint, inputIndex); - + // As we walk across a scan line in the output image, we trace // an oriented/scaled/translated line in the input image. Cache // the delta along this line in continuous index space of the input // image. This allows us to use vector addition to model the // transformation. // - // To find delta, we take two pixels adjacent in a scanline - // and determine the continuous indices of these pixels when + // To find delta, we take two pixels adjacent in a scanline + // and determine the continuous indices of these pixels when // mapped to the input coordinate frame. We use the difference // between these two continuous indices as the delta to apply - // to an index to trace line in the input image as we move + // to an index to trace line in the input image as we move // across the scanline of the output image. // // We determine delta in this manner so that Images and // OrientedImages are both handled properly (with the delta for // OrientedImages taking into account the direction cosines). - // + // ++index[0]; outputPtr->TransformIndexToPhysicalPoint( index, tmpOutputPoint ); tmpInputPoint = m_Transform->TransformPoint( tmpOutputPoint ); @@ -426,7 +426,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> // will incremented in the scanline loop inputPoint = m_Transform->TransformPoint(outputPoint); inputPtr->TransformPhysicalPointToContinuousIndex(inputPoint, inputIndex); - + // The inputIndex is precise to many decimal points, but this precision // involves some error in the last bits. // Sometimes, when an index should be inside of the image, the @@ -464,7 +464,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> { outIt.Set(defaultValue); // default background value } - + progress.CompletedPixel(); ++outIt; inputIndex += delta; @@ -476,7 +476,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> } -/** +/** * Inform pipeline of necessary input image region * * Determining the actual input region is non-trivial, especially @@ -484,7 +484,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> * So we do the easy thing and request the entire input image. */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::GenerateInputRequestedRegion() { @@ -497,7 +497,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> } // get pointers to the input and output - InputImagePointer inputPtr = + InputImagePointer inputPtr = const_cast< TInputImage *>( this->GetInput() ); // Request the entire input image @@ -509,7 +509,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> } -/** +/** * Set the smart pointer to the reference image that will provide * the grid parameters for the output image. */ @@ -519,18 +519,18 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::GetReferenceImage() const { Self * surrogate = const_cast< Self * >( this ); - const OutputImageType * referenceImage = + const OutputImageType * referenceImage = static_cast<const OutputImageType *>(surrogate->ProcessObject::GetInput(1)); return referenceImage; } -/** +/** * Set the smart pointer to the reference image that will provide * the grid parameters for the output image. */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::SetReferenceImage( const TOutputImage *image ) { @@ -542,11 +542,37 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> } } -/** +/** Helper method to set the output parameters based on this image */ +template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> +void +ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> +::SetOutputParametersFromImage ( const ImageBaseType * image ) +{ + this->SetOutputOrigin ( image->GetOrigin() ); + this->SetOutputSpacing ( image->GetSpacing() ); + this->SetOutputDirection ( image->GetDirection() ); + this->SetOutputStartIndex ( image->GetLargestPossibleRegion().GetIndex() ); + this->SetSize ( image->GetLargestPossibleRegion().GetSize() ); +} + +#if !defined(ITK_LEGACY_REMOVE) +template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> +void +ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> +::SetOutputParametersFromConstImage ( const ImageBaseType * image ) +{ + itkGenericLegacyReplaceBodyMacro(itk::ResampleImageFilter::SetOutputParametersFromConstImage, + 3.14, + itk::ResampleImageFilter::SetOutputParametersFromImage); + this->SetOutputParametersFromImage(image); +} +#endif + +/** * Inform pipeline of required output region */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -void +void ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::GenerateOutputInformation() { @@ -591,15 +617,15 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> return; } -/** +/** * Verify if any of the components has been modified. */ template <class TInputImage, class TOutputImage, class TInterpolatorPrecisionType> -unsigned long +unsigned long ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> ::GetMTime( void ) const { - unsigned long latestTime = Object::GetMTime(); + unsigned long latestTime = Object::GetMTime(); if( m_Transform ) { diff --git a/Utilities/ITK/Code/BasicFilters/itkRescaleIntensityImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkRescaleIntensityImageFilter.h index 921bd980d5..24be9164c9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRescaleIntensityImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkRescaleIntensityImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRescaleIntensityImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:52 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,7 +58,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & x ) + inline TOutput operator()( const TInput & x ) const { RealType value = static_cast<RealType>(x) * m_Factor + m_Offset; TOutput result = static_cast<TOutput>( value ); diff --git a/Utilities/ITK/Code/BasicFilters/itkScalarConnectedComponentImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkScalarConnectedComponentImageFilter.h index f14b81d052..4339449e72 100644 --- a/Utilities/ITK/Code/BasicFilters/itkScalarConnectedComponentImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkScalarConnectedComponentImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarConnectedComponentImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 20:49:55 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -60,7 +60,7 @@ public: void SetDistanceThreshold(const TInput &thresh) {m_Threshold = thresh;} TInput GetDistanceThreshold() {return (m_Threshold);} - bool operator()(const TInput &a, const TInput &b) + bool operator()(const TInput &a, const TInput &b) const { return (vnl_math_abs(a-b) <= m_Threshold); } diff --git a/Utilities/ITK/Code/BasicFilters/itkShiftScaleImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkShiftScaleImageFilter.h index b29b34bd54..ff554e2b26 100644 --- a/Utilities/ITK/Code/BasicFilters/itkShiftScaleImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkShiftScaleImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShiftScaleImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 20:49:55 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-25 12:28:09 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -80,15 +80,15 @@ public: /** Set/Get the amount to Shift each Pixel. The shift is followed by a Scale. */ itkSetMacro(Shift,RealType); - itkGetMacro(Shift,RealType); + itkGetConstMacro(Shift,RealType); /** Set/Get the amount to Scale each Pixel. The Scale is applied after the Shift. */ itkSetMacro(Scale,RealType); - itkGetMacro(Scale,RealType); + itkGetConstMacro(Scale,RealType); /** Get the number of pixels that underflowed and overflowed. */ - itkGetMacro(UnderflowCount,long); - itkGetMacro(OverflowCount,long); + itkGetConstMacro(UnderflowCount,long); + itkGetConstMacro(OverflowCount,long); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkShiftScaleInPlaceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkShiftScaleInPlaceImageFilter.h index c6fc12c5c8..26af2b2af9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkShiftScaleInPlaceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkShiftScaleInPlaceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShiftScaleInPlaceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 20:49:55 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-25 12:28:09 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -87,15 +87,15 @@ public: /** Set/Get the amount to Shift each Pixel. The shift is followed by a Scale. */ itkSetMacro(Shift,RealType); - itkGetMacro(Shift,RealType); + itkGetConstMacro(Shift,RealType); /** Set/Get the amount to Scale each Pixel. The Scale is applied after the Shift. */ itkSetMacro(Scale,RealType); - itkGetMacro(Scale,RealType); + itkGetConstMacro(Scale,RealType); /** Get the number of pixels that underflowed and overflowed. */ - itkGetMacro(UnderflowCount,long); - itkGetMacro(OverflowCount,long); + itkGetConstMacro(UnderflowCount,long); + itkGetConstMacro(OverflowCount,long); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.h index efbd51cdb3..6c16f8cd5c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShrinkImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-17 19:58:02 $ - Version: $Revision: 1.44 $ + Date: $Date: 2009-04-09 18:34:25 $ + Version: $Revision: 1.46 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,7 +49,7 @@ namespace itk * This filter is implemented as a multithreaded filter. It provides a * ThreadedGenerateData() method for its implementation. * - * \ingroup GeometricTransforms + * \ingroup GeometricTransforms Streamed */ template <class TInputImage, class TOutputImage> class ITK_EXPORT ShrinkImageFilter: @@ -75,6 +75,10 @@ public: typedef typename InputImageType::Pointer InputImagePointer; typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename TOutputImage::IndexType OutputIndexType; + typedef typename TInputImage::IndexType InputIndexType; + typedef typename TOutputImage::OffsetType OutputOffsetType; + /** Typedef to describe the output image region type. */ typedef typename TOutputImage::RegionType OutputImageRegionType; diff --git a/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.txx index d402d22691..42284eade7 100644 --- a/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShrinkImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-12-17 19:58:02 $ - Version: $Revision: 1.55 $ + Date: $Date: 2009-05-05 21:45:49 $ + Version: $Revision: 1.61 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,7 +21,7 @@ #define __itkShrinkImageFilter_txx #include "itkShrinkImageFilter.h" -#include "itkImageRegionIterator.h" +#include "itkImageRegionIteratorWithIndex.h" #include "itkContinuousIndex.h" #include "itkObjectFactory.h" #include "itkProgressReporter.h" @@ -127,37 +127,70 @@ ShrinkImageFilter<TInputImage,TOutputImage> ::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId) { - itkDebugMacro(<<"Actually executing"); - // Get the input and output pointers InputImageConstPointer inputPtr = this->GetInput(); OutputImagePointer outputPtr = this->GetOutput(); - // Define/declare an iterator that will walk the output region for this - // thread. - typedef ImageRegionIterator<TOutputImage> OutputIterator; - - OutputIterator outIt(outputPtr, outputRegionForThread); - - // Define a few indices that will be used to translate from an input pixel + + // convert the factor for convenient multiplication + unsigned int i; + typename TOutputImage::SizeType factorSize; + for ( i=0; i < TInputImage::ImageDimension; i++ ) + { + factorSize[i] = m_ShrinkFactors[i]; + } + + // Define a few indices that will be used to transform from an input pixel // to an output pixel - typename TOutputImage::IndexType outputIndex; - typename TInputImage::IndexType inputIndex; + OutputIndexType outputIndex; + InputIndexType inputIndex; + OutputOffsetType offsetIndex; + typename TOutputImage::PointType tempPoint; + + // use this index to compute the offset everywhere in this class + outputIndex = outputPtr->GetLargestPossibleRegion().GetIndex(); + inputIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); + + // We wish to perform the following mapping of outputIndex to + // inputIndex on all points in our region + outputPtr->TransformIndexToPhysicalPoint( outputIndex, tempPoint ); + inputPtr->TransformPhysicalPointToIndex( tempPoint, inputIndex ); + + + // Given that the size is scaled by a constant factor eq: + // inputIndex = outputIndex * factorSize + // is equivalent up to a fixed offset which we now compute + typename OutputOffsetType::OffsetValueType zeroOffset = 0; + for ( i=0; i < TInputImage::ImageDimension; i++ ) + { + offsetIndex[i] = inputIndex[i] - outputIndex[i]*m_ShrinkFactors[i]; + // it is plausible that due to small amounts of loss of numerical + // precision that the offset it negaive, this would cause sampling + // out of out region, this is insurance against that possibility + offsetIndex[i] = vnl_math_max( zeroOffset, offsetIndex[i] ); + } + + // support progress methods/callbacks ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - - // walk the output region, and sample the input image - typename TOutputImage::PointType outputPoint; + + // Define/declare an iterator that will walk the output region for this + // thread. + typedef ImageRegionIteratorWithIndex<TOutputImage> OutputIterator; + OutputIterator outIt( outputPtr, outputRegionForThread ); + while ( !outIt.IsAtEnd() ) { // determine the index and physical location of the output pixel outputIndex = outIt.GetIndex(); - outputPtr->TransformIndexToPhysicalPoint(outputIndex, outputPoint); - - // determine the input pixel index associated with this output pixel - inputPtr->TransformPhysicalPointToIndex(outputPoint, inputIndex); - + + // an optimized version of + // outputPtr->TransformIndexToPhysicalPoint(outputIndex, tempPoint); + // inputPtr->TransformPhysicalPointToIndex(tempPoint, inputIndex); + // but without the rounding and precision issues + inputIndex = outputIndex * factorSize + offsetIndex; + // copy the input pixel to the output outIt.Set( inputPtr->GetPixel(inputIndex) ); ++outIt; @@ -186,28 +219,68 @@ ShrinkImageFilter<TInputImage,TOutputImage> return; } - // we need to compute the input requested region (size and start index) + // Compute the input requested region (size and start index) + // Use the image transformations to insure an input requested region + // that will provide the proper range unsigned int i; const typename TOutputImage::SizeType& outputRequestedRegionSize = outputPtr->GetRequestedRegion().GetSize(); const typename TOutputImage::IndexType& outputRequestedRegionStartIndex = outputPtr->GetRequestedRegion().GetIndex(); + - typename TInputImage::SizeType inputRequestedRegionSize; - typename TInputImage::IndexType inputRequestedRegionStartIndex; - - for (i = 0; i < TInputImage::ImageDimension; i++) + // convert the factor for convenient multiplication + typename TOutputImage::SizeType factorSize; + for ( i=0; i < TInputImage::ImageDimension; i++ ) { - inputRequestedRegionSize[i] - = outputRequestedRegionSize[i] * m_ShrinkFactors[i]; - inputRequestedRegionStartIndex[i] - = outputRequestedRegionStartIndex[i] * (long)m_ShrinkFactors[i]; + factorSize[i] = m_ShrinkFactors[i]; } - + + OutputIndexType outputIndex; + InputIndexType inputIndex, inputRequestedRegionIndex; + OutputOffsetType offsetIndex; + + typename TInputImage::SizeType inputRequestedRegionSize; + typename TOutputImage::PointType tempPoint; + + + // use this index to compute the offset everywhere in this class + outputIndex = outputPtr->GetLargestPossibleRegion().GetIndex(); + inputIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); + + // We wish to perform the following mapping of outputIndex to + // inputIndex on all points in our region + outputPtr->TransformIndexToPhysicalPoint( outputIndex, tempPoint ); + inputPtr->TransformPhysicalPointToIndex( tempPoint, inputIndex ); + + + // Given that the size is scaled by a constant factor eq: + // inputIndex = outputIndex * factorSize + // is equivalent up to a fixed offset which we now compute + typename OutputOffsetType::OffsetValueType zeroOffset = 0; + for ( i=0; i < TInputImage::ImageDimension; i++ ) + { + offsetIndex[i] = inputIndex[i] - outputIndex[i]*m_ShrinkFactors[i]; + // it is plausible that due to small amounts of loss of numerical + // precision that the offset it negaive, this would cause sampling + // out of out region, this is insurance against that possibility + offsetIndex[i] = vnl_math_max( zeroOffset, offsetIndex[i] ); + } + + inputRequestedRegionIndex = outputRequestedRegionStartIndex*factorSize + offsetIndex; + + // originally this was + // inputSize = outputRequestedRegionSize * factorSize + // but since we don't sample edge to edge, we can reduce the size + for ( i=0; i < TInputImage::ImageDimension; ++i ) + { + inputRequestedRegionSize[i] = (outputRequestedRegionSize[i] - 1 ) * factorSize[i] + 1; + } + + typename TInputImage::RegionType inputRequestedRegion; + inputRequestedRegion.SetIndex( inputRequestedRegionIndex ); inputRequestedRegion.SetSize( inputRequestedRegionSize ); - inputRequestedRegion.SetIndex( inputRequestedRegionStartIndex ); - inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() ); inputPtr->SetRequestedRegion( inputRequestedRegion ); @@ -249,28 +322,33 @@ ShrinkImageFilter<TInputImage,TOutputImage> for (i = 0; i < TOutputImage::ImageDimension; i++) { - - outputSpacing[i] = inputSpacing[i] * (float) m_ShrinkFactors[i]; + outputSpacing[i] = inputSpacing[i] * (double) m_ShrinkFactors[i]; + + // we round down so that all output pixels fit input input region outputSize[i] = (unsigned long) - vcl_floor((float) inputSize[i] / (float) m_ShrinkFactors[i]); + vcl_floor((double) inputSize[i] / (double) m_ShrinkFactors[i]); + if( outputSize[i] < 1 ) { outputSize[i] = 1; } - + + // because of the later origin shift this starting index is not + // critical outputStartIndex[i] = (long) - vcl_ceil((float) inputStartIndex[i] / (float) m_ShrinkFactors[i] ); + vcl_ceil((double) inputStartIndex[i] / (double) m_ShrinkFactors[i] ); } outputPtr->SetSpacing( outputSpacing ); + // compute origin offset // The physical center's of the input and output should be the same ContinuousIndex<double, TOutputImage::ImageDimension> inputCenterIndex; ContinuousIndex<double, TOutputImage::ImageDimension> outputCenterIndex; for (i = 0; i < TOutputImage::ImageDimension; i++) { - inputCenterIndex[i] = (inputSize[i] - 1) / 2.0; - outputCenterIndex[i] = (outputSize[i] - 1) / 2.0; + inputCenterIndex[i] = inputStartIndex[i] + (inputSize[i] - 1) / 2.0; + outputCenterIndex[i] = outputStartIndex[i] + (outputSize[i] - 1) / 2.0; } typename TOutputImage::PointType inputCenterPoint; @@ -281,7 +359,8 @@ ShrinkImageFilter<TInputImage,TOutputImage> typename TOutputImage::PointType outputOrigin = outputPtr->GetOrigin(); outputOrigin = outputOrigin + (inputCenterPoint - outputCenterPoint); outputPtr->SetOrigin(outputOrigin); - + + // set region typename TOutputImage::RegionType outputLargestPossibleRegion; outputLargestPossibleRegion.SetSize( outputSize ); outputLargestPossibleRegion.SetIndex( outputStartIndex ); diff --git a/Utilities/ITK/Code/BasicFilters/itkSigmoidImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSigmoidImageFilter.h index a2d09c3496..e90a9aa110 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSigmoidImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSigmoidImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSigmoidImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-24 08:14:12 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-01 14:36:31 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -68,7 +68,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { const double x = ( static_cast<double>(A) - m_Beta ) / m_Alpha; const double e = 1.0 / ( 1.0 + vcl_exp(- x ) ); diff --git a/Utilities/ITK/Code/BasicFilters/itkSignedDanielssonDistanceMapImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSignedDanielssonDistanceMapImageFilter.h index 0741d9fee9..03878a776f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSignedDanielssonDistanceMapImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSignedDanielssonDistanceMapImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSignedDanielssonDistanceMapImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 20:49:56 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-01 14:36:32 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,7 @@ namespace Functor template <class InputPixelType> class InvertIntensityFunctor { public: - InputPixelType operator()( InputPixelType input ) + InputPixelType operator()( InputPixelType input ) const { if (input) { @@ -141,6 +141,10 @@ public: /** Pointer Type for the vector distance image. */ typedef typename VectorImageType::Pointer VectorImagePointer; + /** Pointer Type for data object */ + typedef typename Superclass::DataObjectPointer DataObjectPointer; + + /** Set if the distance should be squared. */ itkSetMacro( SquaredDistance, bool ); @@ -192,6 +196,9 @@ public: /** Get vector field of distances. */ VectorImageType * GetVectorDistanceMap(void); + /** This is overloaded to create the VectorDistanceMap output image */ + virtual DataObjectPointer MakeOutput(unsigned int idx); + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(IntConvertibleToInputCheck, diff --git a/Utilities/ITK/Code/BasicFilters/itkSignedDanielssonDistanceMapImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkSignedDanielssonDistanceMapImageFilter.txx index 6ed0a9a625..6539b91246 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSignedDanielssonDistanceMapImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkSignedDanielssonDistanceMapImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSignedDanielssonDistanceMapImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-17 20:49:56 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-10 14:26:16 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,9 +35,6 @@ SignedDanielssonDistanceMapImageFilter<TInputImage,TOutputImage> { this->SetNumberOfRequiredOutputs( 3 ); - OutputImagePointer distanceMap = OutputImageType::New(); - this->SetNthOutput( 0, distanceMap.GetPointer() ); - OutputImagePointer voronoiMap = OutputImageType::New(); this->SetNthOutput( 1, voronoiMap.GetPointer() ); @@ -51,6 +48,20 @@ SignedDanielssonDistanceMapImageFilter<TInputImage,TOutputImage> this->m_InsideIsPositive = false; } + /** This is overloaded to create the VectorDistanceMap output image */ +template <class TInputImage,class TOutputImage> +typename SignedDanielssonDistanceMapImageFilter< + TInputImage,TOutputImage>::DataObjectPointer +SignedDanielssonDistanceMapImageFilter<TInputImage,TOutputImage> +::MakeOutput(unsigned int idx) +{ + if (idx == 2) + { + return static_cast<DataObject*>(VectorImageType::New().GetPointer()); + } + return Superclass::MakeOutput(idx); +} + /** * Return the distance map Image pointer */ @@ -160,13 +171,13 @@ void SignedDanielssonDistanceMapImageFilter<TInputImage,TOutputImage> if ( m_InsideIsPositive ) { - subtracter->SetInput1(filter2->GetOutput(0)); - subtracter->SetInput2(filter1->GetOutput(0)); + subtracter->SetInput1(filter2->GetDistanceMap()); + subtracter->SetInput2(filter1->GetDistanceMap()); } else { - subtracter->SetInput2(filter2->GetOutput(0)); - subtracter->SetInput1(filter1->GetOutput(0)); + subtracter->SetInput2(filter2->GetDistanceMap()); + subtracter->SetInput1(filter1->GetDistanceMap()); } subtracter->Update(); @@ -177,9 +188,12 @@ void SignedDanielssonDistanceMapImageFilter<TInputImage,TOutputImage> progress->RegisterInternalFilter(filter1,.5f); // Graft outputs - this->GraftNthOutput( 0, subtracter->GetOutput(0) ); - this->GraftNthOutput( 1, filter1->GetOutput(1) ); - this->GraftNthOutput( 2, filter1->GetOutput(2) ); + this->GraftNthOutput( 0, subtracter->GetOutput() ); + + // we must use not use this->GetOutput method because the + // output's are of different types then ImageSource + this->GraftNthOutput( 1, filter1->GetVoronoiMap() ); + this->GraftNthOutput( 2, filter1->GetVectorDistanceMap() ); } // end GenerateData() diff --git a/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.h index e04999ec75..77c788efb6 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSignedMaurerDistanceMapImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-14 18:39:05 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-05-12 17:22:53 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -60,7 +60,7 @@ namespace itk */ template <class TInputImage, class TOutputImage> -class SignedMaurerDistanceMapImageFilter : +class ITK_EXPORT SignedMaurerDistanceMapImageFilter : public ImageToImageFilter< TInputImage, TOutputImage > { public: diff --git a/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.txx index 46b9029bef..dd79f46688 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSignedMaurerDistanceMapImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-08-02 19:38:49 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-06 13:46:37 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,7 +37,7 @@ template <class InputPixelType> class InvertBinaryIntensityFunctor { public: - InputPixelType operator()( InputPixelType input ) + InputPixelType operator()( InputPixelType input ) const { if( input ) { @@ -108,8 +108,8 @@ SignedMaurerDistanceMapImageFilter<TInputImage, TOutputImage> // determine the actual number of pieces that will be generated typename TOutputImage::SizeType::SizeValueType range = requestedRegionSize[splitAxis]; - int valuesPerThread = (int)::ceil(range/(double)num); - int maxThreadIdUsed = (int)::ceil(range/(double)valuesPerThread) - 1; + int valuesPerThread = (int)vcl_ceil(range/(double)num); + int maxThreadIdUsed = (int)vcl_ceil(range/(double)valuesPerThread) - 1; // Split the region if (i < maxThreadIdUsed) @@ -331,7 +331,7 @@ SignedMaurerDistanceMapImageFilter<TInputImage, TOutputImage> // double. cableswig currently fail to build it with msvc 7.1 const OutputPixelType outputValue = static_cast<OutputPixelType>( - sqrt( static_cast<double>(vnl_math_abs( Ot.Get() ) ) ) ); + vcl_sqrt( static_cast<double>(vnl_math_abs( Ot.Get() ) ) ) ); if( It.Get() != this->m_BackgroundValue ) { diff --git a/Utilities/ITK/Code/BasicFilters/itkSimilarityIndexImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSimilarityIndexImageFilter.h index 618521332d..ef3c242497 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSimilarityIndexImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSimilarityIndexImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimilarityIndexImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 20:49:56 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:28:09 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -108,7 +108,7 @@ public: const InputImage2Type * GetInput2(void); /** Return the computed similarity index. */ - itkGetMacro(SimilarityIndex,RealType); + itkGetConstMacro(SimilarityIndex,RealType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.h b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.h index d59da35dd1..2718f7bf14 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshAdaptTopologyFilter.h,v $ Language: C++ -Date: $Date: 2008-10-17 20:49:56 $ -Version: $Revision: 1.12 $ +Date: $Date: 2009-05-12 17:22:53 $ +Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,7 +49,7 @@ namespace itk * */ template <class TInputMesh, class TOutputMesh> -class SimplexMeshAdaptTopologyFilter : public MeshToMeshFilter<TInputMesh, TOutputMesh> +class ITK_EXPORT SimplexMeshAdaptTopologyFilter : public MeshToMeshFilter<TInputMesh, TOutputMesh> { public: @@ -236,12 +236,12 @@ public: itkSetMacro(Threshold, double); - itkGetMacro(Threshold, double); + itkGetConstMacro(Threshold, double); itkSetMacro(SelectionMethod, int); - itkGetMacro(SelectionMethod, int); + itkGetConstMacro(SelectionMethod, int); - itkGetMacro(ModifiedCount, int); + itkGetConstMacro(ModifiedCount, int); protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.txx b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.txx index d0a6dbe830..fb58409948 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshAdaptTopologyFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-17 20:49:56 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-05-12 17:22:53 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -354,7 +354,10 @@ SimplexMeshAdaptTopologyFilter<TInputMesh, TOutputMesh> ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); - os << indent << "ToDo: implement PrinSelf!!!"; + os << indent << "Threshold: " << m_Threshold << std::endl; + os << indent << "SelectionMethod: " << m_SelectionMethod << std::endl; + os << indent << "ModifiedCount: " << m_ModifiedCount << std::endl; + } diff --git a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshToTriangleMeshFilter.h b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshToTriangleMeshFilter.h index d91e5f44fb..f60ce10d7f 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshToTriangleMeshFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshToTriangleMeshFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshToTriangleMeshFilter.h,v $ Language: C++ -Date: $Date: 2008-10-17 20:49:56 $ -Version: $Revision: 1.7 $ +Date: $Date: 2009-05-12 17:22:53 $ +Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -45,7 +45,7 @@ namespace itk * */ template <class TInputMesh, class TOutputMesh> -class SimplexMeshToTriangleMeshFilter : public MeshToMeshFilter<TInputMesh, TOutputMesh> +class ITK_EXPORT SimplexMeshToTriangleMeshFilter : public MeshToMeshFilter<TInputMesh, TOutputMesh> { public: diff --git a/Utilities/ITK/Code/BasicFilters/itkSinImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSinImageFilter.h index 26edb14b70..bf9e080717 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSinImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSinImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSinImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 20:49:56 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-04-01 14:36:33 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return (TOutput)vcl_sin((double)A); } }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkSmoothingRecursiveGaussianImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSmoothingRecursiveGaussianImageFilter.h index 4c26812a06..bb81d0ffe3 100755 --- a/Utilities/ITK/Code/BasicFilters/itkSmoothingRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSmoothingRecursiveGaussianImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSmoothingRecursiveGaussianImageFilter.h,v $ Language: C++ - Date: $Date: 2008-07-31 09:14:58 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-25 12:28:09 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -112,11 +112,11 @@ public: /** Set Sigma value. Sigma is measured in the units of image spacing. */ void SetSigma( ScalarRealType sigma ); - itkGetMacro(Sigma, ScalarRealType); + itkGetConstMacro(Sigma, ScalarRealType); /** Define which normalization factor will be used for the Gaussian */ void SetNormalizeAcrossScale( bool normalizeInScaleSpace ); - itkGetMacro( NormalizeAcrossScale, bool ); + itkGetConstMacro( NormalizeAcrossScale, bool ); void SetNumberOfThreads( int nb ); diff --git a/Utilities/ITK/Code/BasicFilters/itkSparseFieldLayer.txx b/Utilities/ITK/Code/BasicFilters/itkSparseFieldLayer.txx index 8c20e90278..30f484bf08 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSparseFieldLayer.txx +++ b/Utilities/ITK/Code/BasicFilters/itkSparseFieldLayer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSparseFieldLayer.txx,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:13 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-06 14:13:03 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,6 +18,7 @@ #define __itkSparseFieldLayer_txx #include "itkSparseFieldLayer.h" #include <math.h> +#include "vcl_cmath.h" namespace itk { @@ -65,7 +66,8 @@ SparseFieldLayer<TNodeType> std::vector<RegionType> regionlist; unsigned int size, regionsize; size=Size(); - regionsize=static_cast<unsigned int>(ceil(static_cast<float>(size)/static_cast<float>(num))); + regionsize=static_cast<unsigned int>( + vcl_ceil(static_cast<float>(size)/static_cast<float>(num))); ConstIterator position=Begin(); ConstIterator last=End(); diff --git a/Utilities/ITK/Code/BasicFilters/itkSparseFieldLevelSetImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSparseFieldLevelSetImageFilter.h index eca9cb6504..5cc742b584 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSparseFieldLevelSetImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSparseFieldLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSparseFieldLevelSetImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:13 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-25 12:28:10 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -284,16 +284,16 @@ public: * number of layers on ONE side of the active layer, so the total layers in * the sparse field is 2 * NumberOfLayers +1 */ itkSetMacro(NumberOfLayers, unsigned int); - itkGetMacro(NumberOfLayers, unsigned int); + itkGetConstMacro(NumberOfLayers, unsigned int); /** Set/Get the value of the isosurface to use in the input image. */ itkSetMacro(IsoSurfaceValue, ValueType); - itkGetMacro(IsoSurfaceValue, ValueType); + itkGetConstMacro(IsoSurfaceValue, ValueType); /** Get the RMS change calculated in the PREVIOUS iteration. This value is * the square root of the average square of the change value of all pixels * updated during the previous iteration. */ - // itkGetMacro(RMSChange, ValueType); + // itkGetConstMacro(RMSChange, ValueType); /** Get/Set the value of the InterpolateSurfaceLocation flag. This flag tells the solver whether or not to interpolate for the surface location @@ -301,7 +301,7 @@ public: applications may not use this value and can safely turn the flag off. */ itkSetMacro(InterpolateSurfaceLocation, bool); - itkGetMacro(InterpolateSurfaceLocation, bool); + itkGetConstMacro(InterpolateSurfaceLocation, bool); /** See Get/SetInterpolateSurfaceLocation */ void InterpolateSurfaceLocationOn() diff --git a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageFilter.h index dd09cf6408..2260363744 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectToImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:13 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-25 12:28:11 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -98,7 +98,7 @@ public: * the output produced by this filter will be a mask with inside/outside values * specified by the user. */ itkSetMacro( InsideValue, ValueType ); - itkGetMacro( InsideValue, ValueType ); + itkGetConstMacro( InsideValue, ValueType ); /** Set/Get the value for pixels outside the spatial object. * By default, this filter will return an image @@ -107,7 +107,7 @@ public: * the output produced by this filter will be a mask with inside/outside values * specified by the user. */ itkSetMacro( OutsideValue, ValueType ); - itkGetMacro( OutsideValue, ValueType ); + itkGetConstMacro( OutsideValue, ValueType ); /** The origin of the output image. The origin is the geometric * coordinates of the index (0,0,...,0). It is stored internally @@ -123,16 +123,16 @@ public: * image? A ChildrenDepth of 0 means to only include the object * itself. */ itkSetMacro( ChildrenDepth, unsigned int ); - itkGetMacro( ChildrenDepth, unsigned int ); + itkGetConstMacro( ChildrenDepth, unsigned int ); /** Set/Get Size */ itkSetMacro( Size, SizeType ); - itkGetMacro( Size, SizeType ); + itkGetConstMacro( Size, SizeType ); /** If UseObjectValue is set to true, then the filter uses * the ValueAt() function instead of IsInside() */ itkSetMacro( UseObjectValue, bool ); - itkGetMacro( UseObjectValue, bool ); + itkGetConstMacro( UseObjectValue, bool ); protected: SpatialObjectToImageFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageFilter.txx index e7ed3239a4..35895d0f66 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectToImageFilter.txx,v $ Language: C++ -Date: $Date: 2008-10-18 16:11:13 $ -Version: $Revision: 1.22 $ +Date: $Date: 2009-04-01 22:14:59 $ +Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -381,10 +381,10 @@ SpatialObjectToImageFilter<TInputSpatialObject, TOutputImage> double val = 0; - InputObject->ValueAt(objectPoint, val, m_ChildrenDepth); + bool evaluable = InputObject->ValueAt(objectPoint, val, m_ChildrenDepth); if( m_InsideValue != 0 || m_OutsideValue != 0 ) { - if( val) + if(evaluable) { if(m_UseObjectValue) { diff --git a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageStatisticsCalculator.h b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageStatisticsCalculator.h index 45411bea15..910ae6debc 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageStatisticsCalculator.h +++ b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageStatisticsCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectToImageStatisticsCalculator.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:28:11 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -86,7 +86,7 @@ public: /** Set/Get the direction of the sample */ itkSetMacro(SampleDirection,unsigned int); - itkGetMacro(SampleDirection,unsigned int); + itkGetConstMacro(SampleDirection,unsigned int); /** Set the input image. */ itkSetConstObjectMacro(Image,ImageType); diff --git a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageStatisticsCalculator.txx b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageStatisticsCalculator.txx index 2f32e42aef..633fcbdc57 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageStatisticsCalculator.txx +++ b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToImageStatisticsCalculator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectToImageStatisticsCalculator.txx,v $ Language: C++ -Date: $Date: 2008-10-18 20:32:37 $ -Version: $Revision: 1.26 $ +Date: $Date: 2009-05-02 05:43:55 $ +Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,15 @@ PURPOSE. See the above copyright notices for more information. #include "itkSpatialObjectToImageStatisticsCalculator.h" #include "itkImageRegionConstIteratorWithIndex.h" + +#ifdef ITK_USE_REVIEW_STATISTICS +#include "itkMeanSampleFilter.h" +#include "itkCovarianceSampleFilter.h" +#else #include "itkMeanCalculator.h" #include "itkCovarianceCalculator.h" +#endif + #include "itkImageMaskSpatialObject.h" namespace itk @@ -50,32 +57,59 @@ bool SpatialObjectToImageStatisticsCalculator<TInputImage,TInputSpatialObject,TSampleDimension> ::ComputeStatistics() { - typedef itk::Statistics::MeanCalculator< SampleType > - MeanAlgorithmType; +#ifdef ITK_USE_REVIEW_STATISTICS + typedef itk::Statistics::MeanSampleFilter< SampleType > MeanAlgorithmType; +#else + typedef itk::Statistics::MeanCalculator< SampleType > MeanAlgorithmType; +#endif typename MeanAlgorithmType::Pointer meanAlgorithm = MeanAlgorithmType::New(); + +#ifdef ITK_USE_REVIEW_STATISTICS + meanAlgorithm->SetInput( m_Sample ); +#else meanAlgorithm->SetInputSample( m_Sample ); +#endif + meanAlgorithm->Update(); +#ifdef ITK_USE_REVIEW_STATISTICS + typename MeanAlgorithmType::MeasurementVectorType mean = meanAlgorithm->GetMean(); +#else typename MeanAlgorithmType::OutputType mean = *(meanAlgorithm->GetOutput()); +#endif + for( unsigned int i=0; i< SampleDimension; i++ ) { m_Mean[i] = mean[i]; } - typedef itk::Statistics::CovarianceCalculator< SampleType > - CovarianceAlgorithmType; +#ifdef ITK_USE_REVIEW_STATISTICS + typedef itk::Statistics::CovarianceSampleFilter< SampleType > CovarianceAlgorithmType; +#else + typedef itk::Statistics::CovarianceCalculator< SampleType > CovarianceAlgorithmType; +#endif typename CovarianceAlgorithmType::Pointer covarianceAlgorithm = CovarianceAlgorithmType::New(); +#ifdef ITK_USE_REVIEW_STATISTICS + covarianceAlgorithm->SetInput( m_Sample ); +#else covarianceAlgorithm->SetInputSample( m_Sample ); covarianceAlgorithm->SetMean( meanAlgorithm->GetOutput() ); +#endif + covarianceAlgorithm->Update(); +#ifdef ITK_USE_REVIEW_STATISTICS + typename CovarianceAlgorithmType::MatrixType covarianceMatrix = covarianceAlgorithm->GetCovarianceMatrix(); +#else typename CovarianceAlgorithmType::OutputType covarianceMatrix = *(covarianceAlgorithm->GetOutput()); +#endif + for( unsigned int i=0; i< covarianceMatrix.Rows(); i++ ) { for( unsigned int j=0; j< covarianceMatrix.Rows(); j++ ) diff --git a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToPointSetFilter.h b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToPointSetFilter.h index fe772a2a8c..600bac677d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToPointSetFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSpatialObjectToPointSetFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectToPointSetFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-25 12:28:11 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -76,13 +76,13 @@ public: * PointSet? A ChildrenDepth of 0 means to only include the object * itself. */ itkSetMacro(ChildrenDepth, unsigned int); - itkGetMacro(ChildrenDepth, unsigned int); + itkGetConstMacro(ChildrenDepth, unsigned int); /* Set the sampling factor of the object. The resulting pointset will have a size * inversely proportional to the sampling factor.*/ itkSetMacro(SamplingFactor, unsigned int); - itkGetMacro(SamplingFactor, unsigned int); + itkGetConstMacro(SamplingFactor, unsigned int); protected: SpatialObjectToPointSetFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkSqrtImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSqrtImageFilter.h index 4024d6d3c6..dda47480e9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSqrtImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSqrtImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSqrtImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-04-01 14:36:34 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return (TOutput)vcl_sqrt((double)A); } diff --git a/Utilities/ITK/Code/BasicFilters/itkSquareImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSquareImageFilter.h index 7dd1b8d2b3..f26c948f21 100755 --- a/Utilities/ITK/Code/BasicFilters/itkSquareImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSquareImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSquareImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-01 14:36:34 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -45,7 +45,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { const RealType ra = static_cast<RealType>( A ); return static_cast<TOutput>( ra * ra ); diff --git a/Utilities/ITK/Code/BasicFilters/itkSquaredDifferenceImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSquaredDifferenceImageFilter.h index a5be650680..326ccab4b2 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSquaredDifferenceImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSquaredDifferenceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSquaredDifferenceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-01 14:36:35 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -62,7 +62,7 @@ public: return !(*this != other); } inline TOutput operator()( const TInput1 & A, - const TInput2 & B) + const TInput2 & B) const { const double dA = static_cast<double>( A ); const double dB = static_cast<double>( B ); diff --git a/Utilities/ITK/Code/BasicFilters/itkStandardDeviationProjectionImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkStandardDeviationProjectionImageFilter.h index 3d0a54c289..2ee0f20139 100644 --- a/Utilities/ITK/Code/BasicFilters/itkStandardDeviationProjectionImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkStandardDeviationProjectionImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkStandardDeviationProjectionImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-01 14:36:35 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -64,7 +64,7 @@ public: m_Values.clear(); } - inline void operator()( const TInputPixel &input ) + inline void operator()( const TInputPixel &input ) { m_Sum = m_Sum + input; m_Values.push_back( input ); diff --git a/Utilities/ITK/Code/BasicFilters/itkSubtractImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSubtractImageFilter.h index 395ec3a567..561f3e7fe9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSubtractImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSubtractImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSubtractImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.28 $ + Date: $Date: 2009-04-01 14:36:35 $ + Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,7 +49,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { return (TOutput)(A - B); } }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkSymmetricEigenAnalysisImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSymmetricEigenAnalysisImageFilter.h index 74a08e85af..8549681d0d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSymmetricEigenAnalysisImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSymmetricEigenAnalysisImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSymmetricEigenAnalysisImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-02 14:31:10 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-01 14:36:36 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,7 +51,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & x ) + inline TOutput operator()( const TInput & x ) const { TOutput eigenValues; m_Calculator.ComputeEigenValues( x, eigenValues ); diff --git a/Utilities/ITK/Code/BasicFilters/itkTanImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkTanImageFilter.h index ff6d3aa7d6..d6d70639ad 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTanImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTanImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTanImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-04-01 14:36:36 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return (TOutput)vcl_tan((double)A); } }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkTensorFractionalAnisotropyImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkTensorFractionalAnisotropyImageFilter.h index ba47f6b555..eb6723f132 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTensorFractionalAnisotropyImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTensorFractionalAnisotropyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTensorFractionalAnisotropyImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-01 14:36:36 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,7 +41,7 @@ public: { return !(*this != other); } - inline RealValueType operator()( const TInput & x ) + inline RealValueType operator()( const TInput & x ) const { return x.GetFractionalAnisotropy(); } diff --git a/Utilities/ITK/Code/BasicFilters/itkTensorRelativeAnisotropyImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkTensorRelativeAnisotropyImageFilter.h index 1d3d136da0..581c1530fb 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTensorRelativeAnisotropyImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTensorRelativeAnisotropyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTensorRelativeAnisotropyImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-01 14:36:36 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,7 +41,7 @@ public: { return !(*this != other); } - inline RealValueType operator()( const TInput & x ) + inline RealValueType operator()( const TInput & x ) const { return x.GetRelativeAnisotropy(); } diff --git a/Utilities/ITK/Code/BasicFilters/itkTernaryAddImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkTernaryAddImageFilter.h index 40fcf35fc8..73596bf0d5 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTernaryAddImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTernaryAddImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTernaryAddImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-01 14:36:36 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,7 +49,7 @@ public: } inline TOutput operator()( const TInput1 & A, const TInput2 & B, - const TInput3 & C) + const TInput3 & C) const { return (TOutput)(A + B + C); } }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkTernaryMagnitudeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkTernaryMagnitudeImageFilter.h index ed2c75b913..ff35ca8ab1 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTernaryMagnitudeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTernaryMagnitudeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTernaryMagnitudeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:14 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-04-01 14:36:36 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,7 +49,7 @@ public: } inline TOutput operator()( const TInput1 & A, const TInput2 & B, - const TInput3 & C) + const TInput3 & C) const { return (TOutput) vcl_sqrt((double)(A*A + B*B + C*C) ); } }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkTernaryMagnitudeSquaredImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkTernaryMagnitudeSquaredImageFilter.h index 061495a62e..4533114b2c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTernaryMagnitudeSquaredImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTernaryMagnitudeSquaredImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTernaryMagnitudeSquaredImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:15 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-01 14:36:37 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,7 +49,7 @@ public: } inline TOutput operator()( const TInput1 & A, const TInput2 & B, - const TInput3 & C) + const TInput3 & C) const { return (TOutput)(A*A + B*B + C*C); } }; } diff --git a/Utilities/ITK/Code/BasicFilters/itkThresholdImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkThresholdImageFilter.h index 0bbcefb504..69112c6404 100644 --- a/Utilities/ITK/Code/BasicFilters/itkThresholdImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkThresholdImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkThresholdImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:15 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-25 12:28:11 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,7 +73,7 @@ public: itkSetMacro(OutsideValue,PixelType); /** Get the "outside" pixel value. */ - itkGetMacro(OutsideValue,PixelType); + itkGetConstMacro(OutsideValue,PixelType); /** The values greater than or equal to the value are set to OutsideValue. */ void ThresholdAbove(const PixelType &thresh); @@ -86,11 +86,11 @@ public: /** Set/Get methods to set the lower threshold */ itkSetMacro(Lower, PixelType); - itkGetMacro(Lower, PixelType); + itkGetConstMacro(Lower, PixelType); /** Set/Get methods to set the upper threshold */ itkSetMacro(Upper, PixelType); - itkGetMacro(Upper, PixelType); + itkGetConstMacro(Upper, PixelType); /** Some additional typedefs. */ typedef TImage InputImageType; diff --git a/Utilities/ITK/Code/BasicFilters/itkThresholdLabelerImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkThresholdLabelerImageFilter.h index badf0be17f..3b168bb962 100644 --- a/Utilities/ITK/Code/BasicFilters/itkThresholdLabelerImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkThresholdLabelerImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkThresholdLabelerImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:15 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-05-12 17:22:57 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,7 +42,7 @@ namespace itk namespace Functor { template< class TInput, class TOutput > -class ThresholdLabeler +class ITK_EXPORT ThresholdLabeler { public: ThresholdLabeler() { m_LabelOffset = NumericTraits<TOutput>::One; } @@ -73,7 +73,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { unsigned int size = m_Thresholds.size(); if (size == 0) @@ -188,7 +188,7 @@ public: /** Set the offset which labels have to start from. */ itkSetClampMacro(LabelOffset,OutputPixelType, NumericTraits<OutputPixelType>::Zero,NumericTraits<OutputPixelType>::max() ); - itkGetMacro(LabelOffset,OutputPixelType); + itkGetConstMacro(LabelOffset,OutputPixelType); protected: ThresholdLabelerImageFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkTileImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkTileImageFilter.h index 2323e58721..9bacc4f184 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTileImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTileImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTileImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:15 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-25 12:28:11 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -97,7 +97,7 @@ public: * the filter will compute a value that will acoomodate all of the * images. */ itkSetMacro(Layout,LayoutArrayType); - itkGetMacro(Layout,LayoutArrayType); + itkGetConstMacro(Layout,LayoutArrayType); /** Set the pixel value for locations that are not covered by an * input image. The default default pixel value is Zero. */ @@ -105,7 +105,7 @@ public: /** Get the pixel value for locations that are not covered by an * input image. */ - itkGetMacro(DefaultPixelValue,OutputPixelType); + itkGetConstMacro(DefaultPixelValue,OutputPixelType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToBinaryImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToBinaryImageFilter.h index 33b6482fb1..00cf5beb7e 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToBinaryImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToBinaryImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTriangleMeshToBinaryImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:15 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:28:11 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -143,7 +143,7 @@ public: * the output produced by this filter will be a mask with inside/outside values * specified by the user. */ itkSetMacro(InsideValue, ValueType); - itkGetMacro(InsideValue, ValueType); + itkGetConstMacro(InsideValue, ValueType); /** Set/Get the value for pixels outside the spatial object. * By default, this filter will return an image @@ -151,7 +151,7 @@ public: * the output produced by this filter will be a mask with inside/outside values * specified by the user. */ itkSetMacro(OutsideValue, ValueType); - itkGetMacro(OutsideValue, ValueType); + itkGetConstMacro(OutsideValue, ValueType); /** The origin of the output image. The origin is the geometric * coordinates of the index (0,0,...,0). It is stored internally @@ -164,11 +164,11 @@ public: /** Set/Get Index */ itkSetMacro(Index,IndexType); - itkGetMacro(Index,IndexType); + itkGetConstMacro(Index,IndexType); /** Set/Get Size */ itkSetMacro(Size,SizeType); - itkGetMacro(Size,SizeType); + itkGetConstMacro(Size,SizeType); /** Set the mesh input of this process object. */ void SetInput(InputMeshType *input); @@ -188,7 +188,7 @@ public: /* Set the tolerance for doing spatial searches of the polydata. */ itkSetMacro(Tolerance, double); - itkGetMacro(Tolerance, double); + itkGetConstMacro(Tolerance, double); protected: TriangleMeshToBinaryImageFilter(); diff --git a/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToBinaryImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToBinaryImageFilter.txx index 250773acdf..27efd6aef5 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToBinaryImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToBinaryImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTriangleMeshToBinaryImageFilter.txx,v $ Language: C++ -Date: $Date: 2008-10-06 14:59:58 $ -Version: $Revision: 1.11 $ +Date: $Date: 2009-04-06 13:46:37 $ +Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -297,8 +297,8 @@ TriangleMeshToBinaryImageFilter<TInputMesh, TOutputImage> std::swap(p1,p2); } - int zmin = (int)(ceil(p1[2])); - int zmax = (int)(ceil(p2[2])); + int zmin = (int)(vcl_ceil(p1[2])); + int zmax = (int)(vcl_ceil(p2[2])); if (zmin > extent[5] || zmax < extent[4]) { @@ -377,8 +377,8 @@ TriangleMeshToBinaryImageFilter<TInputMesh, TOutputImage> continue; } double temp = 1.0/(Y2 - Y1); - int ymin = (int)(ceil(Y1)); - int ymax = (int)(ceil(Y2)); + int ymin = (int)(vcl_ceil(Y1)); + int ymax = (int)(vcl_ceil(Y2)); for (int y = ymin; y < ymax; y++) { double r = (Y2 - y)*temp; @@ -568,8 +568,8 @@ TriangleMeshToBinaryImageFilter<TInputMesh,TOutputImage> for (int i = 0; i < n; i++) { - int x1 = (int)(ceil(nlist[2*i])); - int x2 = (int)(floor(nlist[2*i+1])); + int x1 = (int)(vcl_ceil(nlist[2*i])); + int x2 = (int)(vcl_floor(nlist[2*i+1])); if (x2 < extent[0] || x1 > (extent[1])) { diff --git a/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToSimplexMeshFilter.h b/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToSimplexMeshFilter.h index c6ded70e2e..ee910b9fbb 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToSimplexMeshFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTriangleMeshToSimplexMeshFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTriangleMeshToSimplexMeshFilter.h,v $ Language: C++ -Date: $Date: 2007-12-29 17:51:23 $ -Version: $Revision: 1.5 $ +Date: $Date: 2009-05-12 17:23:01 $ +Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -45,7 +45,7 @@ namespace itk * */ template <class TInputMesh, class TOutputMesh> -class TriangleMeshToSimplexMeshFilter : public MeshToMeshFilter<TInputMesh, TOutputMesh> +class ITK_EXPORT TriangleMeshToSimplexMeshFilter : public MeshToMeshFilter<TInputMesh, TOutputMesh> { public: /** Standard "Self" typedef. */ diff --git a/Utilities/ITK/Code/BasicFilters/itkTwoOutputExampleImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkTwoOutputExampleImageFilter.h index 932c91819e..0ed2f207b3 100644 --- a/Utilities/ITK/Code/BasicFilters/itkTwoOutputExampleImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkTwoOutputExampleImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTwoOutputExampleImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-18 16:11:15 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-25 12:28:11 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -64,7 +64,7 @@ public: itkSetMacro(OutsideValue,PixelType); /** Get the "outside" pixel value. */ - itkGetMacro(OutsideValue,PixelType); + itkGetConstMacro(OutsideValue,PixelType); /** The values greater than or equal to the value are set to OutsideValue. */ void ThresholdAbove(PixelType &thresh); diff --git a/Utilities/ITK/Code/BasicFilters/itkVTKImageImport.h b/Utilities/ITK/Code/BasicFilters/itkVTKImageImport.h index e09d9155ac..2c5c31fabd 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVTKImageImport.h +++ b/Utilities/ITK/Code/BasicFilters/itkVTKImageImport.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVTKImageImport.h,v $ Language: C++ - Date: $Date: 2008-10-09 15:31:37 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-25 12:28:11 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -99,59 +99,59 @@ public: /** What to do when receiving UpdateInformation(). */ itkSetMacro(UpdateInformationCallback, UpdateInformationCallbackType); - itkGetMacro(UpdateInformationCallback, UpdateInformationCallbackType); + itkGetConstMacro(UpdateInformationCallback, UpdateInformationCallbackType); /** What to do when receiving PipelineModified(). */ itkSetMacro(PipelineModifiedCallback, PipelineModifiedCallbackType); - itkGetMacro(PipelineModifiedCallback, PipelineModifiedCallbackType); + itkGetConstMacro(PipelineModifiedCallback, PipelineModifiedCallbackType); /** What to do when receiving SetWholeExtent(). */ itkSetMacro(WholeExtentCallback, WholeExtentCallbackType); - itkGetMacro(WholeExtentCallback, WholeExtentCallbackType); + itkGetConstMacro(WholeExtentCallback, WholeExtentCallbackType); /** What to do when receiving SetSpacing(). */ itkSetMacro(SpacingCallback, SpacingCallbackType); - itkGetMacro(SpacingCallback, SpacingCallbackType); + itkGetConstMacro(SpacingCallback, SpacingCallbackType); itkSetMacro(FloatSpacingCallback, FloatSpacingCallbackType); - itkGetMacro(FloatSpacingCallback, FloatSpacingCallbackType); + itkGetConstMacro(FloatSpacingCallback, FloatSpacingCallbackType); void SetSpacingCallback(FloatSpacingCallbackType f) { this->SetFloatSpacingCallback(f); } /** What to do when receiving SetOrigin(). */ itkSetMacro(OriginCallback, OriginCallbackType); - itkGetMacro(OriginCallback, OriginCallbackType); + itkGetConstMacro(OriginCallback, OriginCallbackType); itkSetMacro(FloatOriginCallback, FloatOriginCallbackType); - itkGetMacro(FloatOriginCallback, FloatOriginCallbackType); + itkGetConstMacro(FloatOriginCallback, FloatOriginCallbackType); void SetOriginCallback(FloatOriginCallbackType f) { this->SetFloatOriginCallback(f); } /** What to do when receiving UpdateInformation(). */ itkSetMacro(ScalarTypeCallback, ScalarTypeCallbackType); - itkGetMacro(ScalarTypeCallback, ScalarTypeCallbackType); + itkGetConstMacro(ScalarTypeCallback, ScalarTypeCallbackType); /** What to do when receiving SetNumberOfComponents(). */ itkSetMacro(NumberOfComponentsCallback, NumberOfComponentsCallbackType); - itkGetMacro(NumberOfComponentsCallback, NumberOfComponentsCallbackType); + itkGetConstMacro(NumberOfComponentsCallback, NumberOfComponentsCallbackType); /** What to do when receiving PropagateUpdateExtent(). */ itkSetMacro(PropagateUpdateExtentCallback,PropagateUpdateExtentCallbackType); - itkGetMacro(PropagateUpdateExtentCallback,PropagateUpdateExtentCallbackType); + itkGetConstMacro(PropagateUpdateExtentCallback,PropagateUpdateExtentCallbackType); /** What to do when receiving UpdateData(). */ itkSetMacro(UpdateDataCallback, UpdateDataCallbackType); - itkGetMacro(UpdateDataCallback, UpdateDataCallbackType); + itkGetConstMacro(UpdateDataCallback, UpdateDataCallbackType); /** What to do when receiving DataExtent(). */ itkSetMacro(DataExtentCallback, DataExtentCallbackType); - itkGetMacro(DataExtentCallback, DataExtentCallbackType); + itkGetConstMacro(DataExtentCallback, DataExtentCallbackType); /** What to do when receiving BufferPointer(). */ itkSetMacro(BufferPointerCallback, BufferPointerCallbackType); - itkGetMacro(BufferPointerCallback, BufferPointerCallbackType); + itkGetConstMacro(BufferPointerCallback, BufferPointerCallbackType); /** Specify callback data. */ itkSetMacro2(CallbackUserData, void*); - itkGetMacro(CallbackUserData, void*); + itkGetConstMacro(CallbackUserData, void*); protected: VTKImageImport(); diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorConfidenceConnectedImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkVectorConfidenceConnectedImageFilter.h index fed7e0250a..c16e95cf0c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorConfidenceConnectedImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkVectorConfidenceConnectedImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorConfidenceConnectedImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:53 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-25 12:28:11 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -115,15 +115,15 @@ public: /** Set/Get the multiplier to define the confidence interval. Multiplier * can be anything greater than zero. A typical value is 2.5 */ itkSetMacro(Multiplier, double); - itkGetMacro(Multiplier, double); + itkGetConstMacro(Multiplier, double); /** Set/Get the number of iterations */ itkSetMacro(NumberOfIterations, unsigned int); - itkGetMacro(NumberOfIterations, unsigned int); + itkGetConstMacro(NumberOfIterations, unsigned int); /** Set/Get value to replace thresholded pixels */ itkSetMacro(ReplaceValue, OutputImagePixelType); - itkGetMacro(ReplaceValue, OutputImagePixelType); + itkGetConstMacro(ReplaceValue, OutputImagePixelType); /** Get/Set the radius of the neighborhood over which the statistics are evaluated */ diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorConnectedComponentImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkVectorConnectedComponentImageFilter.h index 9302969dce..84f9c40795 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorConnectedComponentImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkVectorConnectedComponentImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorConnectedComponentImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:53 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-01 14:36:37 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,7 +59,7 @@ public: { return !(*this != other); } - bool operator()(const TInput &a, const TInput &b) + bool operator()(const TInput &a, const TInput &b) const { typename TInput::ValueType dotProduct = vnl_math_abs(a * b); return (1.0 - dotProduct <= m_Threshold); diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorCurvatureNDAnisotropicDiffusionFunction.txx b/Utilities/ITK/Code/BasicFilters/itkVectorCurvatureNDAnisotropicDiffusionFunction.txx index 573b5c4206..1be6f3575b 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorCurvatureNDAnisotropicDiffusionFunction.txx +++ b/Utilities/ITK/Code/BasicFilters/itkVectorCurvatureNDAnisotropicDiffusionFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorCurvatureNDAnisotropicDiffusionFunction.txx,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:54 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-05-15 13:55:13 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -102,11 +102,14 @@ VectorCurvatureNDAnisotropicDiffusionFunction<TImage> // ``Half'' derivatives dx_forward[i] = it.GetPixel(m_Center + m_Stride[i]) - it.GetPixel(m_Center); + dx_forward[i] = dx_forward[i] * this->m_ScaleCoefficients[i]; dx_backward[i]= it.GetPixel(m_Center) - it.GetPixel(m_Center - m_Stride[i]); + dx_backward[i] = dx_backward[i] * this->m_ScaleCoefficients[i]; // Centralized differences dx[i] = m_InnerProduct(x_slice[i], it, dx_op); + dx[i] = dx[i] * this->m_ScaleCoefficients[i]; } for (k = 0; k < VectorDimension; k++) @@ -123,15 +126,17 @@ VectorCurvatureNDAnisotropicDiffusionFunction<TImage> if (j != i) { dx_aug = m_InnerProduct(xa_slice[j][i],it, dx_op); + dx_aug = dx_aug * this->m_ScaleCoefficients[j]; dx_dim = m_InnerProduct(xd_slice[j][i],it, dx_op); + dx_dim = dx_dim * this->m_ScaleCoefficients[j]; grad_mag_sq[k] += 0.25f * (dx[j][k]+dx_aug[k]) * (dx[j][k]+dx_aug[k]); grad_mag_sq_d[k] += 0.25f * (dx[j][k]+dx_dim[k]) * (dx[j][k]+dx_dim[k]); } } } - grad_mag[k] = ::sqrt(m_MIN_NORM + grad_mag_sq[k]); - grad_mag_d[k] = ::sqrt(m_MIN_NORM + grad_mag_sq_d[k]); + grad_mag[k] = vcl_sqrt(m_MIN_NORM + grad_mag_sq[k]); + grad_mag_d[k] = vcl_sqrt(m_MIN_NORM + grad_mag_sq_d[k]); // this grad mag should depend only on the current k for (i = 0; i < ImageDimension; i++) { @@ -161,8 +166,8 @@ VectorCurvatureNDAnisotropicDiffusionFunction<TImage> } else { - Cx[i] = ::exp( grad_mag_sq_tmp / m_K ); - Cxd[i] = ::exp( grad_mag_sq_d_tmp / m_K ); + Cx[i] = vcl_exp( grad_mag_sq_tmp / m_K ); + Cxd[i] = vcl_exp( grad_mag_sq_d_tmp / m_K ); } } @@ -201,7 +206,7 @@ VectorCurvatureNDAnisotropicDiffusionFunction<TImage> } - ans[k] = ::sqrt(propagation_gradient) * speed; + ans[k] = vcl_sqrt(propagation_gradient) * speed; } return ans; diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorExpandImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkVectorExpandImageFilter.h index b8eebb757d..4960027a27 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorExpandImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkVectorExpandImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorExpandImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:54 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-05-19 20:36:25 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,11 +41,18 @@ namespace itk * SetInterpolator(). Note that the input interpolator must derive * from base class VectorInterpolateImageFunction. * + * \warning: The following is valid only when the flag + * ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY is OFF. * When the LargestPossibleRegion is requested, the output image will * contain padding at the upper edge of each dimension. The width * of padding in the i'th dimension is (ExpandFactors[i] - 1). Users can * specify the padding value used by setting the EdgePaddingValue. * + * \warning: The following is valid only when the flag + * ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY is ON + * The output image will not contain any padding, and therefore the + * EdgePaddingValue will not be used. + * * This filter will produce an output with different pixel spacing * that its input image such that: * diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorExpandImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkVectorExpandImageFilter.txx index 6c4f2c2d7a..ca9713868a 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorExpandImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkVectorExpandImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorExpandImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:54 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-05-19 20:36:26 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -251,8 +251,11 @@ VectorExpandImageFilter<TInputImage,TOutputImage> // clamped to be minimum for 1. for(unsigned int j = 0; j < ImageDimension; j++ ) { - inputIndex[j] = (double) outputIndex[j] / - (double) m_ExpandFactors[j]; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + inputIndex[j] = ( (double) outputIndex[j] + 0.5 ) / (double) m_ExpandFactors[j] - 0.5; +#else + inputIndex[j] = (double) outputIndex[j] / (double) m_ExpandFactors[j]; +#endif } // interpolate value and write to output @@ -389,10 +392,15 @@ VectorExpandImageFilter<TInputImage,TOutputImage> = inputPtr->GetLargestPossibleRegion().GetSize(); const typename TInputImage::IndexType& inputStartIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); + const typename TInputImage::PointType& + inputOrigin = inputPtr->GetOrigin(); typename OutputImageType::SpacingType outputSpacing; typename TOutputImage::SizeType outputSize; typename TOutputImage::IndexType outputStartIndex; + typename TOutputImage::PointType outputOrigin; + + typename TInputImage::SpacingType inputOriginShift; for (unsigned int i = 0; i < TOutputImage::ImageDimension; i++) { @@ -403,9 +411,22 @@ VectorExpandImageFilter<TInputImage,TOutputImage> outputStartIndex[i] = (long) ((ExpandFactorsType)inputStartIndex[i] * m_ExpandFactors[i]+ (ExpandFactorsType)0.5); +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + const double fraction = (double)(m_ExpandFactors[i] - 1) / (double)m_ExpandFactors[i]; + inputOriginShift[i] = - ( inputSpacing[i] / 2.0 ) * fraction; +#endif } +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + const typename TInputImage::DirectionType inputDirection = inputPtr->GetDirection(); + const typename TOutputImage::SpacingType outputOriginShift = inputDirection * inputOriginShift; + + outputOrigin = inputOrigin + outputOriginShift; +#else + outputOrigin = inputOrigin; +#endif outputPtr->SetSpacing( outputSpacing ); + outputPtr->SetOrigin( outputOrigin ); typename TOutputImage::RegionType outputLargestPossibleRegion; outputLargestPossibleRegion.SetSize( outputSize ); diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.h index 61f6e1db25..daac623a21 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorGradientMagnitudeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:55 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-04-25 12:28:12 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -209,7 +209,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input image in its calculations */ void SetUseImageSpacing(bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); /** Directly Set/Get the array of weights used in the gradient calculations. Note that calling UseImageSpacingOn will clobber these values. */ @@ -227,7 +227,7 @@ public: to FALSE/OFF, the calculation is done as a square root of weighted sum of the derivatives squared. Default is UsePrincipleComponents = true. */ itkSetMacro(UsePrincipleComponents, bool); - itkGetMacro(UsePrincipleComponents, bool); + itkGetConstMacro(UsePrincipleComponents, bool); void SetUsePrincipleComponentsOn() { this->SetUsePrincipleComponents(true); diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.txx index bc59b86414..3e1de55b01 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorGradientMagnitudeImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:55 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -176,7 +176,7 @@ VectorGradientMagnitudeImageFilter<TInputImage, TRealType, TOutputImage> { itkExceptionMacro( << "Component weights must be positive numbers" ); } - m_SqrtComponentWeights[i] = ::sqrt(m_ComponentWeights[i]); + m_SqrtComponentWeights[i] = vcl_sqrt(m_ComponentWeights[i]); } diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorGradientNDAnisotropicDiffusionFunction.txx b/Utilities/ITK/Code/BasicFilters/itkVectorGradientNDAnisotropicDiffusionFunction.txx index 89593fa366..867a71c87b 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorGradientNDAnisotropicDiffusionFunction.txx +++ b/Utilities/ITK/Code/BasicFilters/itkVectorGradientNDAnisotropicDiffusionFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorGradientNDAnisotropicDiffusionFunction.txx,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:56 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-05-15 13:55:09 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -93,11 +93,17 @@ VectorGradientNDAnisotropicDiffusionFunction<TImage> // Calculate the directional and centralized derivatives. for (i = 0; i < ImageDimension; i++) { + // ``Half'' derivatives dx_forward[i] = it.GetPixel(m_Center + m_Stride[i]) - it.GetPixel(m_Center); + dx_forward[i] = dx_forward[i] * this->m_ScaleCoefficients[i]; dx_backward[i]= it.GetPixel(m_Center) - it.GetPixel(m_Center - m_Stride[i]); + dx_backward[i] = dx_backward[i] * this->m_ScaleCoefficients[i]; + + // Centralized differences dx[i] = m_InnerProduct(x_slice[i], it, dx_op); + dx[i] = dx[i] * this->m_ScaleCoefficients[i]; } // Calculate the conductance term for each dimension. @@ -117,7 +123,9 @@ VectorGradientNDAnisotropicDiffusionFunction<TImage> if ( j != i) { dx_aug = m_InnerProduct(xa_slice[j][i], it, dx_op); + dx_aug = dx_aug * this->m_ScaleCoefficients[j]; dx_dim = m_InnerProduct(xd_slice[j][i], it, dx_op); + dx_dim = dx_dim * this->m_ScaleCoefficients[j]; GradMag += 0.25f * vnl_math_sqr( dx[j][k]+dx_aug[k] ); GradMag_d += 0.25f * vnl_math_sqr( dx[j][k]+dx_dim[k] ); } @@ -131,8 +139,8 @@ VectorGradientNDAnisotropicDiffusionFunction<TImage> } else { - Cx[i] = ::exp( GradMag / m_K ); - Cxd[i] = ::exp( GradMag_d / m_K ); + Cx[i] = vcl_exp( GradMag / m_K ); + Cxd[i] = vcl_exp( GradMag_d / m_K ); } } diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorIndexSelectionCastImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkVectorIndexSelectionCastImageFilter.h index 46c4bb7276..50ae631b0e 100755 --- a/Utilities/ITK/Code/BasicFilters/itkVectorIndexSelectionCastImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkVectorIndexSelectionCastImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorIndexSelectionCastImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 20:50:03 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-01 14:42:12 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,7 +46,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & A ) + inline TOutput operator()( const TInput & A ) const { return static_cast<TOutput>( A[m_Index] ); } @@ -56,7 +56,7 @@ private: }; } - /** \class VectorIndexSelectionCastImageFilter +/** \class VectorIndexSelectionCastImageFilter * * \brief Extracts the selected index of the vector that is the input * pixel type diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorResampleImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkVectorResampleImageFilter.h index 56615d2790..9269719e5f 100755 --- a/Utilities/ITK/Code/BasicFilters/itkVectorResampleImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkVectorResampleImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorResampleImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 20:50:03 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-25 12:28:12 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -141,7 +141,7 @@ public: itkSetMacro(DefaultPixelValue,PixelType); /** Get the pixel value when a transformed pixel is outside of the image */ - itkGetMacro(DefaultPixelValue,PixelType); + itkGetConstMacro(DefaultPixelValue,PixelType); /** Set the output image spacing. */ itkSetMacro(OutputSpacing, SpacingType); diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorRescaleIntensityImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkVectorRescaleIntensityImageFilter.h index bb21830634..29af99ce1a 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorRescaleIntensityImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkVectorRescaleIntensityImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorRescaleIntensityImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 20:50:03 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:37 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,7 +47,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput & x ) + inline TOutput operator()( const TInput & x ) const { TOutput result; for(unsigned int i=0; i<VectorDimension; i++) diff --git a/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.h index 7ba44d8629..473a95287e 100644 --- a/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWarpImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-25 12:28:12 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -16,7 +16,7 @@ =========================================================================*/ #ifndef __itkWarpImageFilter_h #define __itkWarpImageFilter_h - +#include "itkImageBase.h" #include "itkImageToImageFilter.h" #include "itkInterpolateImageFunction.h" #include "itkLinearInterpolateImageFunction.h" @@ -76,7 +76,7 @@ namespace itk * \warning This filter assumes that the input type, output type * and deformation field type all have the same number of dimensions. * - * \ingroup GeometricTransforms MultiThreaded + * \ingroup GeometricTransforms MultiThreaded Streamed */ template < class TInputImage, @@ -120,6 +120,8 @@ public: TInputImage::ImageDimension ); itkStaticConstMacro(DeformationFieldDimension, unsigned int, TDeformationField::ImageDimension ); + /** typedef for base image type at the current ImageDimension */ + typedef ImageBase<itkGetStaticConstMacro(ImageDimension)> ImageBaseType; /** Deformation field typedef support. */ typedef TDeformationField DeformationFieldType; @@ -169,11 +171,27 @@ public: itkSetMacro(OutputDirection, DirectionType ); itkGetConstReferenceMacro(OutputDirection, DirectionType ); + /** Helper method to set the output parameters based on this image */ + void SetOutputParametersFromImage ( const ImageBaseType *image ); + + /** Set the start index of the output largest possible region. + * The default is an index of all zeros. */ + itkSetMacro( OutputStartIndex, IndexType ); + + /** Get the start index of the output largest possible region. */ + itkGetConstReferenceMacro( OutputStartIndex, IndexType ); + + /** Set the size of the output image. */ + itkSetMacro( OutputSize, SizeType ); + + /** Get the size of the output image. */ + itkGetConstReferenceMacro( OutputSize, SizeType ); + /** Set the edge padding value */ itkSetMacro( EdgePaddingValue, PixelType ); /** Get the edge padding value */ - itkGetMacro( EdgePaddingValue, PixelType ); + itkGetConstMacro( EdgePaddingValue, PixelType ); /** WarpImageFilter produces an image which is a different * size than its input image. As such, it needs to provide an @@ -226,13 +244,24 @@ private: WarpImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented + /** This function should be in an interpolator but none of the ITK + * interpolators at this point handle edge conditions properly + */ + DisplacementType EvaluateDeformationAtPhysicalPoint(const PointType &p); + PixelType m_EdgePaddingValue; SpacingType m_OutputSpacing; PointType m_OutputOrigin; DirectionType m_OutputDirection; InterpolatorPointer m_Interpolator; - + SizeType m_OutputSize; // Size of the output image + IndexType m_OutputStartIndex; // output image start index + bool m_DefFieldSizeSame; + // variables for deffield interpoator + IndexType m_StartIndex,m_EndIndex; + + }; } // end namespace itk diff --git a/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.txx index d4bf651214..01ed82d006 100644 --- a/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWarpImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-03-24 21:48:17 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,8 @@ #include "itkImageRegionIteratorWithIndex.h" #include "itkNumericTraits.h" #include "itkProgressReporter.h" - +#include "itkContinuousIndex.h" +#include "vnl/vnl_math.h" namespace itk { @@ -40,16 +41,15 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> m_OutputSpacing.Fill( 1.0 ); m_OutputOrigin.Fill( 0.0 ); m_OutputDirection.SetIdentity(); - + m_OutputSize.Fill(0); m_EdgePaddingValue = NumericTraits<PixelType>::Zero; - + m_OutputStartIndex.Fill(0); // Setup default interpolator typename DefaultInterpolatorType::Pointer interp = DefaultInterpolatorType::New(); m_Interpolator = static_cast<InterpolatorType*>( interp.GetPointer() ); - } /** @@ -66,6 +66,8 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> os << indent << "OutputSpacing: " << m_OutputSpacing << std::endl; os << indent << "OutputOrigin: " << m_OutputOrigin << std::endl; os << indent << "OutputDirection: " << m_OutputDirection << std::endl; + os << indent << "OutputSize: " << m_OutputSize << std::endl; + os << indent << "OutputStartIndex: " << m_OutputStartIndex << std::endl; os << indent << "EdgePaddingValue: " << static_cast<typename NumericTraits<PixelType>::PrintType>(m_EdgePaddingValue) << std::endl; @@ -103,6 +105,19 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> this->SetOutputOrigin(p); } +/** Helper method to set the output parameters based on this image */ +template <class TInputImage,class TOutputImage,class TDeformationField> +void +WarpImageFilter<TInputImage,TOutputImage,TDeformationField> +::SetOutputParametersFromImage ( const ImageBaseType * image ) +{ + this->SetOutputOrigin ( image->GetOrigin() ); + this->SetOutputSpacing ( image->GetSpacing() ); + this->SetOutputDirection ( image->GetDirection() ); + this->SetOutputStartIndex ( image->GetLargestPossibleRegion().GetIndex() ); + this->SetOutputSize ( image->GetLargestPossibleRegion().GetSize() ); +} + /** * Set deformation field as Inputs[1] for this ProcessObject. * @@ -149,10 +164,24 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> { itkExceptionMacro(<< "Interpolator not set"); } + DeformationFieldPointer fieldPtr = this->GetDeformationField(); // Connect input image to interpolator m_Interpolator->SetInputImage( this->GetInput() ); - + typename DeformationFieldType::RegionType defRegion = + fieldPtr->GetLargestPossibleRegion(); + typename OutputImageType::RegionType outRegion = + this->GetOutput()->GetLargestPossibleRegion(); + m_DefFieldSizeSame = outRegion == defRegion; + if(!m_DefFieldSizeSame) + { + m_StartIndex = fieldPtr->GetBufferedRegion().GetIndex(); + for(unsigned i = 0; i < ImageDimension; i++) + { + m_EndIndex[i] = m_StartIndex[i] + + fieldPtr->GetBufferedRegion().GetSize()[i] - 1; + } + } } /** @@ -165,10 +194,108 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> { // Disconnect input image from interpolator m_Interpolator->SetInputImage( NULL ); - } +template <class TInputImage,class TOutputImage,class TDeformationField> +typename WarpImageFilter<TInputImage, + TOutputImage, + TDeformationField>::DisplacementType +WarpImageFilter<TInputImage,TOutputImage,TDeformationField> +::EvaluateDeformationAtPhysicalPoint(const PointType &point) +{ + DeformationFieldPointer fieldPtr = this->GetDeformationField(); + ContinuousIndex<double,ImageDimension> index; + fieldPtr->TransformPhysicalPointToContinuousIndex(point,index); + unsigned int dim; // index over dimension + /** + * Compute base index = closest index below point + * Compute distance from point to base index + */ + signed long baseIndex[ImageDimension]; + IndexType neighIndex; + double distance[ImageDimension]; + + for( dim = 0; dim < ImageDimension; dim++ ) + { + baseIndex[dim] = (long) vcl_floor(index[dim] ); + + if( baseIndex[dim] >= m_StartIndex[dim] ) + { + if( baseIndex[dim] < m_EndIndex[dim] ) + { + distance[dim] = index[dim] - double( baseIndex[dim] ); + } + else + { + baseIndex[dim] = m_EndIndex[dim]; + distance[dim] = 0.0; + } + } + else + { + baseIndex[dim] = m_StartIndex[dim]; + distance[dim] = 0.0; + } + } + + /** + * Interpolated value is the weight some of each of the surrounding + * neighbors. The weight for each neighbour is the fraction overlap + * of the neighbor pixel with respect to a pixel centered on point. + */ + DisplacementType output; + output.Fill(0); + + double totalOverlap = 0.0; + unsigned int numNeighbors(1 << TInputImage::ImageDimension); + + for( unsigned int counter = 0; counter < numNeighbors; counter++ ) + { + double overlap = 1.0; // fraction overlap + unsigned int upper = counter; // each bit indicates upper/lower neighbour + + // get neighbor index and overlap fraction + for( dim = 0; dim < ImageDimension; dim++ ) + { + + if( upper & 1 ) + { + neighIndex[dim] = baseIndex[dim] + 1; + overlap *= distance[dim]; + } + else + { + neighIndex[dim] = baseIndex[dim]; + overlap *= 1.0 - distance[dim]; + } + + upper >>= 1; + + } + + // get neighbor value only if overlap is not zero + if( overlap ) + { + const DisplacementType input = + fieldPtr->GetPixel( neighIndex ); + for(unsigned int k = 0; k < DisplacementType::Dimension; k++ ) + { + output[k] += overlap * static_cast<double>( input[k] ); + } + totalOverlap += overlap; + } + + if( totalOverlap == 1.0 ) + { + // finished + break; + } + + } + return ( output ); +} + /** * Compute the output for the region specified by outputRegionForThread. */ @@ -190,46 +317,76 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> // iterator for the output image ImageRegionIteratorWithIndex<OutputImageType> outputIt( outputPtr, outputRegionForThread ); - - // iterator for the deformation field - ImageRegionIterator<DeformationFieldType> fieldIt( - fieldPtr, outputRegionForThread ); - IndexType index; PointType point; DisplacementType displacement; - - while( !outputIt.IsAtEnd() ) + if(this->m_DefFieldSizeSame) { - // get the output image index - index = outputIt.GetIndex(); - outputPtr->TransformIndexToPhysicalPoint( index, point ); - - // get the required displacement - displacement = fieldIt.Get(); + // iterator for the deformation field + ImageRegionIterator<DeformationFieldType> + fieldIt(fieldPtr, outputRegionForThread ); - // compute the required input image point - for(unsigned int j = 0; j < ImageDimension; j++ ) + while( !outputIt.IsAtEnd() ) { - point[j] += displacement[j]; + // get the output image index + index = outputIt.GetIndex(); + outputPtr->TransformIndexToPhysicalPoint( index, point ); + + // get the required displacement + displacement = fieldIt.Get(); + + // compute the required input image point + for(unsigned int j = 0; j < ImageDimension; j++ ) + { + point[j] += displacement[j]; + } + + // get the interpolated value + if( m_Interpolator->IsInsideBuffer( point ) ) + { + PixelType value = + static_cast<PixelType>(m_Interpolator->Evaluate( point ) ); + outputIt.Set( value ); + } + else + { + outputIt.Set( m_EdgePaddingValue ); + } + ++outputIt; + ++fieldIt; + progress.CompletedPixel(); } - - // get the interpolated value - if( m_Interpolator->IsInsideBuffer( point ) ) + } + else + { + while( !outputIt.IsAtEnd() ) { - PixelType value = static_cast<PixelType>( - m_Interpolator->Evaluate( point ) ); - outputIt.Set( value ); + // get the output image index + index = outputIt.GetIndex(); + outputPtr->TransformIndexToPhysicalPoint( index, point ); + + displacement = this->EvaluateDeformationAtPhysicalPoint(point); + // compute the required input image point + for(unsigned int j = 0; j < ImageDimension; j++ ) + { + point[j] += displacement[j]; + } + + // get the interpolated value + if( m_Interpolator->IsInsideBuffer( point ) ) + { + PixelType value = + static_cast<PixelType>(m_Interpolator->Evaluate( point ) ); + outputIt.Set( value ); + } + else + { + outputIt.Set( m_EdgePaddingValue ); + } + ++outputIt; + progress.CompletedPixel(); } - else - { - outputIt.Set( m_EdgePaddingValue ); - } - ++outputIt; - ++fieldIt; - progress.CompletedPixel(); } - } @@ -255,11 +412,14 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> // deformation field. DeformationFieldPointer fieldPtr = this->GetDeformationField(); OutputImagePointer outputPtr = this->GetOutput(); - if( fieldPtr ) + if(fieldPtr.IsNotNull() ) { fieldPtr->SetRequestedRegion( outputPtr->GetRequestedRegion() ); + if(!fieldPtr->VerifyRequestedRegion()) + { + fieldPtr->SetRequestedRegion(fieldPtr->GetLargestPossibleRegion()); + } } - } @@ -278,12 +438,19 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> outputPtr->SetDirection( m_OutputDirection ); DeformationFieldPointer fieldPtr = this->GetDeformationField(); - if( fieldPtr ) + if( this->m_OutputSize[0] == 0 && + fieldPtr.IsNotNull()) { outputPtr->SetLargestPossibleRegion( fieldPtr-> GetLargestPossibleRegion() ); } - + else + { + OutputImageRegionType region; + region.SetSize(this->m_OutputSize); + region.SetIndex(this->m_OutputStartIndex); + outputPtr->SetLargestPossibleRegion(region); + } } diff --git a/Utilities/ITK/Code/BasicFilters/itkWarpVectorImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkWarpVectorImageFilter.h index d9852b7e56..c45c2cb89b 100755 --- a/Utilities/ITK/Code/BasicFilters/itkWarpVectorImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkWarpVectorImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWarpVectorImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-25 12:28:12 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -145,6 +145,9 @@ public: typedef typename TOutputImage::DirectionType DirectionType; /** Set the deformation field. */ + void SetDeformationField( const DeformationFieldType * field ); + + /** Set the deformation field (non const for backward compatibility). */ void SetDeformationField( DeformationFieldType * field ); /** Get a pointer the deformation field. */ @@ -178,7 +181,7 @@ public: itkSetMacro( EdgePaddingValue, PixelType ); /** Get the edge padding value */ - itkGetMacro( EdgePaddingValue, PixelType ); + itkGetConstMacro( EdgePaddingValue, PixelType ); /** WarpVectorImageFilter produces an image which is a different * size than its input image. As such, it needs to provide an diff --git a/Utilities/ITK/Code/BasicFilters/itkWarpVectorImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkWarpVectorImageFilter.txx index 4169ca289a..4ac977b0a5 100755 --- a/Utilities/ITK/Code/BasicFilters/itkWarpVectorImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkWarpVectorImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWarpVectorImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-05 20:21:36 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,6 +100,23 @@ WarpVectorImageFilter<TInputImage,TOutputImage,TDeformationField> template <class TInputImage,class TOutputImage,class TDeformationField> void WarpVectorImageFilter<TInputImage,TOutputImage,TDeformationField> +::SetDeformationField( + const DeformationFieldType * field ) +{ + // const cast is needed because the pipeline is not const-correct. + DeformationFieldType * input = + const_cast< DeformationFieldType * >( field ); + this->ProcessObject::SetNthInput( 1, input ); +} + + +/** + * Set deformation field as Inputs[1] for this ProcessObject + * (non const for backward compatibility) + */ +template <class TInputImage,class TOutputImage,class TDeformationField> +void +WarpVectorImageFilter<TInputImage,TOutputImage,TDeformationField> ::SetDeformationField( DeformationFieldType * field ) { diff --git a/Utilities/ITK/Code/BasicFilters/itkWeightedAddImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkWeightedAddImageFilter.h index e0df88677d..e0b59fc136 100755 --- a/Utilities/ITK/Code/BasicFilters/itkWeightedAddImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkWeightedAddImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWeightedAddImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-01 14:36:37 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -74,7 +74,7 @@ public: return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { const RealType sum1 = A * m_Alpha; const RealType sum2 = B * m_Beta; diff --git a/Utilities/ITK/Code/BasicFilters/itkWhiteTopHatImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkWhiteTopHatImageFilter.h index 8bbf884910..7339406ba9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkWhiteTopHatImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkWhiteTopHatImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWhiteTopHatImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-28 14:36:34 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -94,6 +94,9 @@ public: itkGetConstReferenceMacro(SafeBorder, bool); itkBooleanMacro(SafeBorder); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(InputAdditiveOperatorsCheck, @@ -102,8 +105,8 @@ public: (Concept::Convertible<InputImagePixelType, OutputImagePixelType>)); itkConceptMacro(InputGreaterThanComparableCheck, (Concept::GreaterThanComparable<InputImagePixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/BasicFilters/itkXorImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkXorImageFilter.h index 2290a0dc28..9c9e173fb3 100755 --- a/Utilities/ITK/Code/BasicFilters/itkXorImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkXorImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkXorImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-01 14:36:37 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,7 +59,7 @@ public: { return !(*this != other); } - inline TOutput operator()( const TInput1 & A, const TInput2 & B) + inline TOutput operator()( const TInput1 & A, const TInput2 & B) const { return static_cast<TOutput>( A ^ B ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkZeroCrossingBasedEdgeDetectionImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkZeroCrossingBasedEdgeDetectionImageFilter.h index ac4dc2ed26..03d78b155e 100644 --- a/Utilities/ITK/Code/BasicFilters/itkZeroCrossingBasedEdgeDetectionImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkZeroCrossingBasedEdgeDetectionImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkZeroCrossingBasedEdgeDetectionImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-25 12:28:12 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -107,14 +107,14 @@ public: /** Standard get/set macros for Gaussian filter parameters. */ itkSetMacro(Variance, ArrayType); - itkGetMacro(Variance, const ArrayType); + itkGetConstMacro(Variance, const ArrayType); itkSetMacro(MaximumError, ArrayType); - itkGetMacro(MaximumError, const ArrayType); + itkGetConstMacro(MaximumError, const ArrayType); /** Get/Set the label values for the ZeroCrossingImageFilter */ - itkGetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); itkSetMacro(BackgroundValue, OutputImagePixelType); - itkGetMacro(ForegroundValue, OutputImagePixelType); + itkGetConstMacro(ForegroundValue, OutputImagePixelType); itkSetMacro(ForegroundValue, OutputImagePixelType); /** Set the variance parameter needed by the embedded gaussian filter */ diff --git a/Utilities/ITK/Code/BasicFilters/itkZeroCrossingImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkZeroCrossingImageFilter.h index d9ec6d8dd6..1b483d9e56 100644 --- a/Utilities/ITK/Code/BasicFilters/itkZeroCrossingImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkZeroCrossingImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkZeroCrossingImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:03 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-04-25 12:28:13 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,11 +100,11 @@ public: /** Set/Get the label value for zero-crossing pixels. */ itkSetMacro(ForegroundValue, OutputImagePixelType); - itkGetMacro(ForegroundValue, OutputImagePixelType); + itkGetConstMacro(ForegroundValue, OutputImagePixelType); /** Set/Get the label value for non-zero-crossing pixels. */ itkSetMacro(BackgroundValue, OutputImagePixelType); - itkGetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Common/itkAffineTransform.h b/Utilities/ITK/Code/Common/itkAffineTransform.h index 96cc092bdc..1dbdeb5ad9 100644 --- a/Utilities/ITK/Code/Common/itkAffineTransform.h +++ b/Utilities/ITK/Code/Common/itkAffineTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAffineTransform.h,v $ Language: C++ - Date: $Date: 2008-10-07 08:18:58 $ - Version: $Revision: 1.69 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.70 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -151,6 +151,11 @@ public: typedef typename Superclass::OffsetType OffsetType; typedef typename Superclass::TranslationType TranslationType; + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; + /** Compose affine transformation with a translation * * This method modifies self to include a translation of the @@ -233,6 +238,12 @@ public: * Note that the shear is applied centered at the origin. */ void Shear(int axis1, int axis2, TScalarType coef, bool pre=0); + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + /** Back transform by an affine transformation * * This method finds the point or vector that maps to a given diff --git a/Utilities/ITK/Code/Common/itkAffineTransform.txx b/Utilities/ITK/Code/Common/itkAffineTransform.txx index 7fdd359b43..ce01c517c4 100644 --- a/Utilities/ITK/Code/Common/itkAffineTransform.txx +++ b/Utilities/ITK/Code/Common/itkAffineTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAffineTransform.txx,v $ Language: C++ - Date: $Date: 2006-10-14 19:58:31 $ - Version: $Revision: 1.57 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.60 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -175,7 +175,7 @@ AffineTransform<TScalarType, NDimensions> } trans[axis1][axis1] = vcl_cos(angle); trans[axis1][axis2] = vcl_sin(angle); - trans[axis2][axis1] = -sin(angle); + trans[axis2][axis1] = -vcl_sin(angle); trans[axis2][axis2] = vcl_cos(angle); if (pre) { @@ -204,8 +204,8 @@ AffineTransform<TScalarType, NDimensions> MatrixType trans; trans[0][0] = vcl_cos(angle); - trans[0][1] = -sin(angle); - trans[1][0] = vcl_sin(angle); + trans[0][1] = -vcl_sin(angle); + trans[1][0] = vcl_sin(angle); trans[1][1] = vcl_cos(angle); if (pre) { @@ -308,6 +308,25 @@ AffineTransform<TScalarType, NDimensions> return; } +/** Get an inverse of this transform. */ +template<class TScalarType, unsigned int NDimensions> +bool +AffineTransform<TScalarType, NDimensions> +::GetInverse(Self* inverse) const +{ + return this->Superclass::GetInverse(inverse); +} + +/** Return an inverse of this transform. */ +template<class TScalarType, unsigned int NDimensions> +typename AffineTransform<TScalarType, NDimensions>::InverseTransformBasePointer +AffineTransform<TScalarType, NDimensions> +::GetInverseTransform() const +{ + Pointer inv = New(); + return this->GetInverse(inv) ? inv.GetPointer() : NULL; +} + /** Compute a distance between two affine transforms */ template<class TScalarType, unsigned int NDimensions> diff --git a/Utilities/ITK/Code/Common/itkAnnulusOperator.txx b/Utilities/ITK/Code/Common/itkAnnulusOperator.txx index defcb1210d..d13cdaf58b 100644 --- a/Utilities/ITK/Code/Common/itkAnnulusOperator.txx +++ b/Utilities/ITK/Code/Common/itkAnnulusOperator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnnulusOperator.txx,v $ Language: C++ - Date: $Date: 2008-01-07 13:33:59 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-05 10:56:39 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -92,7 +92,7 @@ AnnulusOperator<TPixel, TDimension, TAllocator> double outerRadius = m_InnerRadius + m_Thickness; for (i=0; i < TDimension; ++i) { - r[i] = static_cast<SizeValueType>(ceil(outerRadius / m_Spacing[i])); + r[i] = static_cast<SizeValueType>(vcl_ceil(outerRadius / m_Spacing[i])); } this->SetRadius(r); diff --git a/Utilities/ITK/Code/Common/itkAzimuthElevationToCartesianTransform.txx b/Utilities/ITK/Code/Common/itkAzimuthElevationToCartesianTransform.txx index f1d4d849be..38362011d8 100644 --- a/Utilities/ITK/Code/Common/itkAzimuthElevationToCartesianTransform.txx +++ b/Utilities/ITK/Code/Common/itkAzimuthElevationToCartesianTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAzimuthElevationToCartesianTransform.txx,v $ Language: C++ - Date: $Date: 2006-10-14 19:58:31 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-05 10:56:39 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -131,14 +131,14 @@ AzimuthElevationToCartesianTransform<TScalarType, NDimensions>:: TransformCartesianToAzEl(const OutputPointType &point) const { InputPointType result; // Converted point - result[0] = (atan(point[0] / point[2])) * (360 / (2*vnl_math::pi)) + result[0] = (vcl_atan(point[0] / point[2])) * (360 / (2*vnl_math::pi)) + ((m_MaxAzimuth-1)/2.0); - result[1] = (atan(point[1] / point[2])) * (360 / (2*vnl_math::pi)) + result[1] = (vcl_atan(point[1] / point[2])) * (360 / (2*vnl_math::pi)) + ((m_MaxElevation-1)/2.0); - result[2] = ((sqrt( point[0] * point[0] + - point[1] * point[1] + - point[2] * point[2]) / m_RadiusSampleSize) - - m_FirstSampleDistance); + result[2] = ((vcl_sqrt( point[0] * point[0] + + point[1] * point[1] + + point[2] * point[2]) / m_RadiusSampleSize) + - m_FirstSampleDistance); return result; } diff --git a/Utilities/ITK/Code/Common/itkBSplineDeformableTransform.h b/Utilities/ITK/Code/Common/itkBSplineDeformableTransform.h index 65e93a9946..9d1429c576 100644 --- a/Utilities/ITK/Code/Common/itkBSplineDeformableTransform.h +++ b/Utilities/ITK/Code/Common/itkBSplineDeformableTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineDeformableTransform.h,v $ Language: C++ - Date: $Date: 2008-10-07 12:04:40 $ - Version: $Revision: 1.39 $ + Date: $Date: 2009-05-13 15:26:06 $ + Version: $Revision: 1.41 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -273,22 +273,18 @@ public: /** This method specifies the region over which the grid resides. */ virtual void SetGridRegion( const RegionType& region ); - itkGetMacro( GridRegion, RegionType ); itkGetConstMacro( GridRegion, RegionType ); /** This method specifies the grid spacing or resolution. */ virtual void SetGridSpacing( const SpacingType& spacing ); - itkGetMacro( GridSpacing, SpacingType ); itkGetConstMacro( GridSpacing, SpacingType ); /** This method specifies the grid directions . */ virtual void SetGridDirection( const DirectionType & spacing ); - itkGetMacro( GridDirection, DirectionType ); itkGetConstMacro( GridDirection, DirectionType ); /** This method specifies the grid origin. */ virtual void SetGridOrigin( const OriginType& origin ); - itkGetMacro( GridOrigin, OriginType ); itkGetConstMacro( GridOrigin, OriginType ); /** Typedef of the bulk transform. */ @@ -427,6 +423,7 @@ private: bool m_SplineOrderOdd; SizeType m_SupportSize; IndexType m_ValidRegionLast; + IndexType m_ValidRegionFirst; /** Array holding images wrapped from the flat parameters. */ ImagePointer m_WrappedImage[NDimensions]; diff --git a/Utilities/ITK/Code/Common/itkBSplineDeformableTransform.txx b/Utilities/ITK/Code/Common/itkBSplineDeformableTransform.txx index 4bf66f0148..cc29be0589 100644 --- a/Utilities/ITK/Code/Common/itkBSplineDeformableTransform.txx +++ b/Utilities/ITK/Code/Common/itkBSplineDeformableTransform.txx @@ -3,14 +3,14 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineDeformableTransform.txx,v $ Language: C++ - Date: $Date: 2008-11-07 19:39:44 $ - Version: $Revision: 1.42 $ + Date: $Date: 2009-05-13 22:04:48 $ + Version: $Revision: 1.45 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -71,7 +71,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> // Setup variables for computing interpolation m_Offset = SplineOrder / 2; - if ( SplineOrder % 2 ) + if ( SplineOrder % 2 ) { m_SplineOrderOdd = true; } @@ -121,11 +121,11 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> m_IndexToPoint = m_GridDirection * scale; m_PointToIndex = m_IndexToPoint.GetInverse(); - + m_LastJacobianIndex = m_ValidRegion.GetIndex(); - + } - + // Destructor template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> @@ -195,12 +195,10 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> typename RegionType::IndexType index = m_GridRegion.GetIndex(); for ( unsigned int j = 0; j < SpaceDimension; j++ ) { - index[j] += - static_cast< typename RegionType::IndexValueType >( m_Offset ); - size[j] -= - static_cast< typename RegionType::SizeValueType> ( 2 * m_Offset ); - m_ValidRegionLast[j] = index[j] + - static_cast< typename RegionType::IndexValueType >( size[j] ) - 1; + index[j] += static_cast< typename RegionType::IndexValueType >( m_Offset ); + size[j] -= static_cast< typename RegionType::SizeValueType> ( 2 * m_Offset ); + m_ValidRegionFirst[j] = index[j]; + m_ValidRegionLast[j] = index[j] + static_cast< typename RegionType::IndexValueType >( size[j] ) - 1; } m_ValidRegion.SetSize( size ); m_ValidRegion.SetIndex( index ); @@ -208,7 +206,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> // // If we are using the default parameters, update their size and set to identity. // - + // Input parameters point to internal buffer => using default parameters. if (m_InputParametersPointer == &m_InternalParametersBuffer) { @@ -325,7 +323,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> parameters->Fill( 0.0 ); this->Modified(); } - else + else { itkExceptionMacro( << "Input parameters for the spline haven't been set ! " << "Set them using the SetParameters or SetCoefficientImage method first." ); @@ -344,7 +342,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> if ( parameters.Size() != this->GetNumberOfParameters() ) { itkExceptionMacro(<<"Mismatched between parameters size " - << parameters.size() + << parameters.size() << " and region size " << m_GridRegion.GetNumberOfPixels() ); } @@ -369,7 +367,7 @@ void BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> ::SetFixedParameters( const ParametersType & passedParameters ) { - + ParametersType parameters( NDimensions * (3 + NDimensions) ); // check if the number of parameters match the @@ -389,7 +387,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> else if ( passedParameters.Size() != NDimensions * (3 + NDimensions) ) { itkExceptionMacro(<< "Mismatched between parameters size " - << passedParameters.size() + << passedParameters.size() << " and number of fixed parameters " << NDimensions * (3 + NDimensions) ); } @@ -401,7 +399,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> } } - /********************************************************* + /********************************************************* Fixed Parameters store the following information: Grid Size Grid Origin @@ -409,7 +407,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> Grid Direction The size of these is equal to the NInputDimensions *********************************************************/ - + /** Set the Grid Parameters */ SizeType gridSize; for (unsigned int i=0; i<NDimensions; i++) @@ -418,14 +416,14 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> } RegionType bsplineRegion; bsplineRegion.SetSize( gridSize ); - + /** Set the Origin Parameters */ OriginType origin; for (unsigned int i=0; i<NDimensions; i++) { origin[i] = parameters[NDimensions+i]; } - + /** Set the Spacing Parameters */ SpacingType spacing; for (unsigned int i=0; i<NDimensions; i++) @@ -442,8 +440,8 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> direction[di][dj] = parameters[3*NDimensions+(di*NDimensions+dj)]; } } - - + + this->SetGridSpacing( spacing ); this->SetGridDirection( direction ); this->SetGridOrigin( origin ); @@ -507,7 +505,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> if ( parameters.Size() != this->GetNumberOfParameters() ) { itkExceptionMacro(<<"Mismatched between parameters size " - << parameters.size() + << parameters.size() << " and region size " << m_GridRegion.GetNumberOfPixels() ); } @@ -527,14 +525,14 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> // Get the parameters template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> -const +const typename BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> ::ParametersType & BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> ::GetParameters( void ) const { - /** NOTE: For efficiency, this class does not keep a copy of the parameters - - * it just keeps pointer to input parameters. + /** NOTE: For efficiency, this class does not keep a copy of the parameters - + * it just keeps pointer to input parameters. */ if (NULL == m_InputParametersPointer) { @@ -547,14 +545,14 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> // Get the parameters template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> -const +const typename BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> ::ParametersType & BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> ::GetFixedParameters( void ) const { RegionType resRegion = this->GetGridRegion( ); - + for (unsigned int i=0; i<NDimensions; i++) { this->m_FixedParameters[i] = (resRegion.GetSize())[i]; @@ -562,7 +560,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> for (unsigned int i=0; i<NDimensions; i++) { this->m_FixedParameters[NDimensions+i] = (this->GetGridOrigin())[i]; - } + } for (unsigned int i=0; i<NDimensions; i++) { this->m_FixedParameters[2*NDimensions+i] = (this->GetGridSpacing())[i]; @@ -574,15 +572,14 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> this->m_FixedParameters[3*NDimensions+(di*NDimensions+dj)] = (this->GetGridDirection())[di][dj]; } } - + return (this->m_FixedParameters); } - // Set the B-Spline coefficients using input images template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> -void +void BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> ::SetCoefficientImage( ImagePointer images[] ) { @@ -604,7 +601,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> } -} +} // Print self template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> @@ -637,8 +634,8 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> os << m_WrappedImage[j].GetPointer() << ", "; } os << m_WrappedImage[j].GetPointer() << " ]" << std::endl; - - os << indent << "InputParametersPointer: " + + os << indent << "InputParametersPointer: " << m_InputParametersPointer << std::endl; os << indent << "ValidRegion: " << m_ValidRegion << std::endl; os << indent << "LastJacobianIndex: " << m_LastJacobianIndex << std::endl; @@ -649,25 +646,27 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> if ( m_BulkTransform ) { - os << indent << "BulkTransformType: " + os << indent << "BulkTransformType: " << m_BulkTransform->GetNameOfClass() << std::endl; } - + } // Transform a point template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> -bool +bool BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> -::InsideValidRegion( +::InsideValidRegion( const ContinuousIndexType& index ) const { bool inside = true; - if ( !m_ValidRegion.IsInside( index ) ) +#ifndef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + if( !m_ValidRegion.IsInside( index ) ) { inside = false; } +#endif if ( inside && m_SplineOrderOdd ) { @@ -675,10 +674,17 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> for( unsigned int j = 0; j < SpaceDimension; j++ ) { if ( index[j] >= static_cast<ValueType>( m_ValidRegionLast[j] ) ) - { + { inside = false; break; } +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + if ( index[j] < static_cast<ValueType>( m_ValidRegionFirst[j] ) ) + { + inside = false; + break; + } +#endif } } @@ -687,12 +693,12 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> // Transform a point template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> -void +void BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> -::TransformPoint( - const InputPointType & point, - OutputPointType & outputPoint, - WeightsType & weights, +::TransformPoint( + const InputPointType & point, + OutputPointType & outputPoint, + WeightsType & weights, ParameterIndexArrayType & indices, bool& inside ) const { @@ -752,7 +758,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> // multiply weigth with coefficient for ( j = 0; j < SpaceDimension; j++ ) { - outputPoint[j] += static_cast<ScalarType>( + outputPoint[j] += static_cast<ScalarType>( weights[counter] * m_Iterator[j].Get()); } @@ -766,7 +772,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> ++( m_Iterator[j] ); } } - + // return results for ( j = 0; j < SpaceDimension; j++ ) { @@ -793,9 +799,9 @@ template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> typename BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> ::OutputPointType BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> -::TransformPoint(const InputPointType &point) const +::TransformPoint(const InputPointType &point) const { - + WeightsType weights( m_WeightsFunction->GetNumberOfWeights() ); ParameterIndexArrayType indices( m_WeightsFunction->GetNumberOfWeights() ); OutputPointType outputPoint; @@ -807,12 +813,12 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> } - -// Compute the Jacobian in one position + +// Compute the Jacobian in one position template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> -const +const typename BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> -::JacobianType & +::JacobianType & BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> ::GetJacobian( const InputPointType & point ) const { @@ -854,7 +860,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> } } - + ContinuousIndexType index; this->TransformPointToContinuousIndex( point, index ); @@ -906,7 +912,7 @@ BSplineDeformableTransform<TScalarType, NDimensions, VSplineOrder> } -// Compute the Jacobian in one position +// Compute the Jacobian in one position template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> void BSplineDeformableTransform<TScalarType, NDimensions,VSplineOrder> @@ -919,7 +925,7 @@ BSplineDeformableTransform<TScalarType, NDimensions,VSplineOrder> ContinuousIndexType index; - this->TransformPointToContinuousIndex( point, index ); + this->TransformPointToContinuousIndex( point, index ); // NOTE: if the support region does not lie totally within the grid // we assume zero displacement and return the input point @@ -929,7 +935,7 @@ BSplineDeformableTransform<TScalarType, NDimensions,VSplineOrder> indexes.Fill(0); return; } - + // Compute interpolation weights IndexType supportIndex; @@ -953,7 +959,7 @@ BSplineDeformableTransform<TScalarType, NDimensions,VSplineOrder> // go to next coefficient in the support region ++ counter; ++m_Iterator; - + } } @@ -985,7 +991,7 @@ BSplineDeformableTransform<TScalarType, NDimensions,VSplineOrder> template<class TScalarType, unsigned int NDimensions, unsigned int VSplineOrder> -unsigned int +unsigned int BSplineDeformableTransform<TScalarType, NDimensions,VSplineOrder> ::GetNumberOfAffectedWeights() const { diff --git a/Utilities/ITK/Code/Common/itkBSplineInterpolationWeightFunction.h b/Utilities/ITK/Code/Common/itkBSplineInterpolationWeightFunction.h index a70f0d596d..90e3f7cbff 100644 --- a/Utilities/ITK/Code/Common/itkBSplineInterpolationWeightFunction.h +++ b/Utilities/ITK/Code/Common/itkBSplineInterpolationWeightFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineInterpolationWeightFunction.h,v $ Language: C++ - Date: $Date: 2008-10-07 12:04:40 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:23:59 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -97,10 +97,10 @@ public: WeightsType & weights, IndexType & startIndex ) const; /** Get support region size. */ - itkGetMacro( SupportSize, SizeType ); + itkGetConstMacro( SupportSize, SizeType ); /** Get number of weights. */ - itkGetMacro( NumberOfWeights, unsigned long ); + itkGetConstMacro( NumberOfWeights, unsigned long ); protected: BSplineInterpolationWeightFunction(); diff --git a/Utilities/ITK/Code/Common/itkBloxCoreAtomImage.h b/Utilities/ITK/Code/Common/itkBloxCoreAtomImage.h index d25d0e0bf3..131774bbc8 100644 --- a/Utilities/ITK/Code/Common/itkBloxCoreAtomImage.h +++ b/Utilities/ITK/Code/Common/itkBloxCoreAtomImage.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBloxCoreAtomImage.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:07 $ - Version: $Revision: 1.33 $ + Date: $Date: 2009-04-25 12:24:02 $ + Version: $Revision: 1.34 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -93,13 +93,13 @@ public: typedef CovariantVector<double, NDimension> GradientType; /** get macro for m_MedialNodeCount. */ - itkGetMacro(MedialNodeCount, int); + itkGetConstMacro(MedialNodeCount, int); typedef std::vector<PixelType*> NodePointerListType; typedef std::vector<PixelType*> * NodePointerListPointer; /** get macro for m_NodePointerList. */ - itkGetMacro(NodePointerList, NodePointerListPointer); + itkGetConstMacro(NodePointerList, NodePointerListPointer); /** Convenient typedefs obtained from Superclass. * Note: Unlike "normal" images BloxCoreAtomImages support neither Scalar nor diff --git a/Utilities/ITK/Code/Common/itkBoundingBox.txx b/Utilities/ITK/Code/Common/itkBoundingBox.txx index 4dc0b2d07d..12742825fd 100644 --- a/Utilities/ITK/Code/Common/itkBoundingBox.txx +++ b/Utilities/ITK/Code/Common/itkBoundingBox.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBoundingBox.txx,v $ Language: C++ - Date: $Date: 2007-01-10 15:02:44 $ - Version: $Revision: 1.39 $ + Date: $Date: 2009-04-05 10:56:39 $ + Version: $Revision: 1.40 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -93,7 +93,7 @@ BoundingBox<TPointIdentifier , VPointDimension, TCoordRep, TPointsContainer > radius[i] = m_Bounds[2*i+1]-center[i]; } - for(unsigned int j=0;j<pow(2.0,(double)VPointDimension);j++) + for(unsigned int j=0;j<vcl_pow(2.0,(double)VPointDimension);j++) { PointType pnt; for(unsigned int i=0; i<VPointDimension;i++) diff --git a/Utilities/ITK/Code/Common/itkCenteredAffineTransform.h b/Utilities/ITK/Code/Common/itkCenteredAffineTransform.h index d7b2b3eeab..b8b82072c5 100644 --- a/Utilities/ITK/Code/Common/itkCenteredAffineTransform.h +++ b/Utilities/ITK/Code/Common/itkCenteredAffineTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredAffineTransform.h,v $ Language: C++ - Date: $Date: 2008-10-07 12:04:56 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -75,6 +75,11 @@ public: typedef typename Superclass::MatrixType MatrixType; typedef typename Superclass::OffsetType OffsetType; + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; + /** Set/Get the transformation from a container of parameters. @@ -96,6 +101,12 @@ public: * is invertible at this point. */ const JacobianType & GetJacobian(const InputPointType &point ) const; + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + protected: /** Construct an CenteredAffineTransform object */ CenteredAffineTransform(); diff --git a/Utilities/ITK/Code/Common/itkCenteredAffineTransform.txx b/Utilities/ITK/Code/Common/itkCenteredAffineTransform.txx index e248efd8f7..a9461908a4 100644 --- a/Utilities/ITK/Code/Common/itkCenteredAffineTransform.txx +++ b/Utilities/ITK/Code/Common/itkCenteredAffineTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredAffineTransform.txx,v $ Language: C++ - Date: $Date: 2006-03-18 18:06:25 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -184,6 +184,25 @@ GetJacobian( const InputPointType & p ) const } +// Get an inverse of this transform +template<class TScalarType, unsigned int NDimensions> +bool +CenteredAffineTransform<TScalarType, NDimensions> +::GetInverse(Self* inverse) const +{ + return this->Superclass::GetInverse(inverse); +} + +// Return an inverse of this transform +template<class TScalarType, unsigned int NDimensions> +typename CenteredAffineTransform<TScalarType, NDimensions>::InverseTransformBasePointer +CenteredAffineTransform<TScalarType, NDimensions> +::GetInverseTransform() const +{ + Pointer inv = New(); + return this->GetInverse(inv) ? inv.GetPointer() : NULL; +} + } // namespace #endif diff --git a/Utilities/ITK/Code/Common/itkCenteredEuler3DTransform.h b/Utilities/ITK/Code/Common/itkCenteredEuler3DTransform.h index 42380e8451..39df8a672b 100644 --- a/Utilities/ITK/Code/Common/itkCenteredEuler3DTransform.h +++ b/Utilities/ITK/Code/Common/itkCenteredEuler3DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredEuler3DTransform.h,v $ Language: C++ - Date: $Date: 2008-10-07 12:04:59 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -77,6 +77,11 @@ public: typedef typename Superclass::TranslationType TranslationType; typedef typename Superclass::OffsetType OffsetType; + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; + /** Set the transformation from a container of parameters * This is typically used by optimizers. * There are six parameters. The first three represent the @@ -95,6 +100,12 @@ public: * transform is invertible at this point. */ const JacobianType & GetJacobian(const InputPointType &point ) const; + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + protected: CenteredEuler3DTransform(); CenteredEuler3DTransform(unsigned int SpaceDimension, diff --git a/Utilities/ITK/Code/Common/itkCenteredEuler3DTransform.txx b/Utilities/ITK/Code/Common/itkCenteredEuler3DTransform.txx index ae20706c03..7b31b8d105 100644 --- a/Utilities/ITK/Code/Common/itkCenteredEuler3DTransform.txx +++ b/Utilities/ITK/Code/Common/itkCenteredEuler3DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredEuler3DTransform.txx,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:07 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -202,6 +202,25 @@ GetJacobian( const InputPointType & p ) const return this->m_Jacobian; } +// Get an inverse of this transform +template<class TScalarType> +bool +CenteredEuler3DTransform<TScalarType> +::GetInverse(Self* inverse) const +{ + return this->Superclass::GetInverse(inverse); +} + +// Return an inverse of this transform +template<class TScalarType> +typename CenteredEuler3DTransform<TScalarType>::InverseTransformBasePointer +CenteredEuler3DTransform<TScalarType> +::GetInverseTransform() const +{ + Pointer inv = New(); + return this->GetInverse(inv) ? inv.GetPointer() : NULL; +} + // Print self template<class TScalarType> diff --git a/Utilities/ITK/Code/Common/itkCenteredRigid2DTransform.h b/Utilities/ITK/Code/Common/itkCenteredRigid2DTransform.h index 7371953266..9c22d5e30f 100644 --- a/Utilities/ITK/Code/Common/itkCenteredRigid2DTransform.h +++ b/Utilities/ITK/Code/Common/itkCenteredRigid2DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredRigid2DTransform.h,v $ Language: C++ - Date: $Date: 2008-10-07 12:04:59 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,6 +100,11 @@ public: /** VnlVector type. */ typedef typename Superclass::InputVnlVectorType InputVnlVectorType; typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; + + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; /** Set the transformation from a container of parameters * This is typically used by optimizers. @@ -140,6 +145,12 @@ public: * which is the inverse of self. */ void CloneInverseTo( Pointer & newinverse ) const; + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + /** * This method creates and returns a new CenteredRigid2DTransform object * which has the same parameters as self. */ diff --git a/Utilities/ITK/Code/Common/itkCenteredRigid2DTransform.txx b/Utilities/ITK/Code/Common/itkCenteredRigid2DTransform.txx index eb51bde6fd..a0913c3103 100644 --- a/Utilities/ITK/Code/Common/itkCenteredRigid2DTransform.txx +++ b/Utilities/ITK/Code/Common/itkCenteredRigid2DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredRigid2DTransform.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:36:58 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -189,10 +189,35 @@ CenteredRigid2DTransform<TScalarType>:: CloneInverseTo( Pointer & result ) const { result = New(); - result->SetCenter( this->GetCenter() ); // inverse have the same center - result->SetAngle( -this->GetAngle() ); - result->SetTranslation( -( this->GetInverseMatrix() + this->GetInverse(result.GetPointer()); +} + +// return an inverse transformation +template<class TScalarType> +bool +CenteredRigid2DTransform<TScalarType>:: +GetInverse( Self* inverse) const +{ + if(!inverse) + { + return false; + } + + inverse->SetCenter( this->GetCenter() ); // inverse have the same center + inverse->SetAngle( -this->GetAngle() ); + inverse->SetTranslation( -( this->GetInverseMatrix() * this->GetTranslation() ) ); + return true; +} + +// Return an inverse of this transform +template<class TScalarType> +typename CenteredRigid2DTransform<TScalarType>::InverseTransformBasePointer +CenteredRigid2DTransform<TScalarType> +::GetInverseTransform() const +{ + Pointer inv = New(); + return GetInverse(inv) ? inv.GetPointer() : NULL; } // Create and return an clone transformation diff --git a/Utilities/ITK/Code/Common/itkCenteredSimilarity2DTransform.h b/Utilities/ITK/Code/Common/itkCenteredSimilarity2DTransform.h index cdf9b3cf39..32c3cb94b9 100644 --- a/Utilities/ITK/Code/Common/itkCenteredSimilarity2DTransform.h +++ b/Utilities/ITK/Code/Common/itkCenteredSimilarity2DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredSimilarity2DTransform.h,v $ Language: C++ - Date: $Date: 2008-10-07 12:04:59 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -105,6 +105,11 @@ public: /** VnlVector type. */ typedef typename Superclass::InputVnlVectorType InputVnlVectorType; typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; + + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; /** Set the transformation from a container of parameters * This is typically used by optimizers. @@ -147,6 +152,12 @@ public: * which is the inverse of self. */ void CloneInverseTo( Pointer & newinverse ) const; + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + /** * This method creates and returns a new Rigid2DTransform object * which has the same parameters. */ diff --git a/Utilities/ITK/Code/Common/itkCenteredSimilarity2DTransform.txx b/Utilities/ITK/Code/Common/itkCenteredSimilarity2DTransform.txx index dc72c78c11..6579275471 100644 --- a/Utilities/ITK/Code/Common/itkCenteredSimilarity2DTransform.txx +++ b/Utilities/ITK/Code/Common/itkCenteredSimilarity2DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredSimilarity2DTransform.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:36:58 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -194,11 +194,36 @@ CenteredSimilarity2DTransform<TScalarType>:: CloneInverseTo( Pointer & result ) const { result = New(); - result->SetCenter( this->GetCenter() ); // inverse have the same center - result->SetScale( 1.0 / this->GetScale() ); - result->SetAngle( -this->GetAngle() ); - result->SetTranslation( -( this->GetInverseMatrix() + this->GetInverse(result.GetPointer()); +} + +// return an inverse transformation +template<class TScalarType> +bool +CenteredSimilarity2DTransform<TScalarType>:: +GetInverse( Self* inverse) const +{ + if(!inverse) + { + return false; + } + + inverse->SetCenter( this->GetCenter() ); // inverse have the same center + inverse->SetScale( 1.0 / this->GetScale() ); + inverse->SetAngle( -this->GetAngle() ); + inverse->SetTranslation( -( this->GetInverseMatrix() * this->GetTranslation() ) ); + return true; +} + +// Return an inverse of this transform +template<class TScalarType> +typename CenteredSimilarity2DTransform<TScalarType>::InverseTransformBasePointer +CenteredSimilarity2DTransform<TScalarType> +::GetInverseTransform() const +{ + Pointer inv = New(); + return GetInverse(inv) ? inv.GetPointer() : NULL; } // Create and return a clone of the transformation diff --git a/Utilities/ITK/Code/Common/itkCentralDifferenceImageFunction.h b/Utilities/ITK/Code/Common/itkCentralDifferenceImageFunction.h index d834bf05e4..18c4765fb7 100644 --- a/Utilities/ITK/Code/Common/itkCentralDifferenceImageFunction.h +++ b/Utilities/ITK/Code/Common/itkCentralDifferenceImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCentralDifferenceImageFunction.h,v $ Language: C++ - Date: $Date: 2008-11-10 16:55:01 $ - Version: $Revision: 1.35 $ + Date: $Date: 2009-04-25 12:24:02 $ + Version: $Revision: 1.36 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -123,7 +123,7 @@ public: * ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE (i.e ON by default when ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE is ON, * and OFF by default when ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE is OFF).*/ itkSetMacro( UseImageDirection, bool ); - itkGetMacro( UseImageDirection, bool ); + itkGetConstMacro( UseImageDirection, bool ); itkBooleanMacro( UseImageDirection ); protected: diff --git a/Utilities/ITK/Code/Common/itkColorTable.h b/Utilities/ITK/Code/Common/itkColorTable.h index 784e9385f1..567dc48397 100644 --- a/Utilities/ITK/Code/Common/itkColorTable.h +++ b/Utilities/ITK/Code/Common/itkColorTable.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkColorTable.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:07 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-25 12:24:02 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -61,7 +61,7 @@ public: void useGray(unsigned int n=256){UseGrayColors(n);} void useHeat(unsigned int n=256){UseHeatColors(n);} - itkGetMacro(NumberOfColors, unsigned int); + itkGetConstMacro(NumberOfColors, unsigned int); unsigned int size(void); RGBPixel<TPixel>* GetColor(unsigned int colorId); diff --git a/Utilities/ITK/Code/Common/itkConicShellInteriorExteriorSpatialFunction.h b/Utilities/ITK/Code/Common/itkConicShellInteriorExteriorSpatialFunction.h index 0d5a0dab33..d1d149e1ab 100644 --- a/Utilities/ITK/Code/Common/itkConicShellInteriorExteriorSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkConicShellInteriorExteriorSpatialFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConicShellInteriorExteriorSpatialFunction.h,v $ Language: C++ - Date: $Date: 2007-01-30 23:39:52 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-25 12:24:03 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -86,7 +86,7 @@ public: OutputType Evaluate(const InputType& position) const; /** Set/Get the origin of the function. */ - itkGetMacro( Origin, InputType); + itkGetConstMacro( Origin, InputType); itkSetMacro( Origin, InputType); /** Set/Get the gradient at the origin of the function. */ @@ -94,19 +94,19 @@ public: void SetOriginGradient(GradientType grad); /** Set/Get the minimum search distance. */ - itkGetMacro( DistanceMin, double); + itkGetConstMacro( DistanceMin, double); itkSetMacro( DistanceMin, double); /** Set/Get the maximum search distance. */ - itkGetMacro( DistanceMax, double); + itkGetConstMacro( DistanceMax, double); itkSetMacro( DistanceMax, double); /** Set/Get the tolerance of the in/out comparison. */ - itkGetMacro( Epsilon, double); + itkGetConstMacro( Epsilon, double); itkSetMacro( Epsilon, double); /** Set/Get direction along the gradient to search. */ - itkGetMacro( Polarity, bool); + itkGetConstMacro( Polarity, bool); itkSetMacro( Polarity, bool); protected: diff --git a/Utilities/ITK/Code/Common/itkCoreAtomImageToDistanceMatrixProcess.h b/Utilities/ITK/Code/Common/itkCoreAtomImageToDistanceMatrixProcess.h index 8f3825fb47..d2e607e9d8 100644 --- a/Utilities/ITK/Code/Common/itkCoreAtomImageToDistanceMatrixProcess.h +++ b/Utilities/ITK/Code/Common/itkCoreAtomImageToDistanceMatrixProcess.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCoreAtomImageToDistanceMatrixProcess.h,v $ Language: C++ - Date: $Date: 2008-08-04 15:56:22 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:24:03 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -57,7 +57,7 @@ public: itkTypeMacro(CoreAtomImageToDistanceMatrixProcess, ProcessObject); //Get macro for m_NumNodes - itkGetMacro(NumberOfNodes, int); + itkGetConstMacro(NumberOfNodes, int); /** Typedef for core atom image */ typedef TSourceImage CoreAtomImageType; diff --git a/Utilities/ITK/Code/Common/itkDenseFiniteDifferenceImageFilter.txx b/Utilities/ITK/Code/Common/itkDenseFiniteDifferenceImageFilter.txx index 26af5edc52..02d11277f4 100644 --- a/Utilities/ITK/Code/Common/itkDenseFiniteDifferenceImageFilter.txx +++ b/Utilities/ITK/Code/Common/itkDenseFiniteDifferenceImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDenseFiniteDifferenceImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-11-07 19:39:44 $ - Version: $Revision: 1.32 $ + Date: $Date: 2009-05-04 14:42:56 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,7 +40,7 @@ DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage> } // Check if we are doing in-place filtering - if ( this->GetInPlace() && (typeid(TInputImage) == typeid(TOutputImage)) ) + if ( this->GetInPlace() && this->CanRunInPlace() ) { typename TInputImage::Pointer tempPtr = dynamic_cast<TInputImage *>( output.GetPointer() ); diff --git a/Utilities/ITK/Code/Common/itkDifferenceImageFilter.h b/Utilities/ITK/Code/Common/itkDifferenceImageFilter.h index 783ceaf86e..ab713537b0 100644 --- a/Utilities/ITK/Code/Common/itkDifferenceImageFilter.h +++ b/Utilities/ITK/Code/Common/itkDifferenceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDifferenceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 09:09:39 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-25 12:24:03 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -69,23 +69,23 @@ public: /** Set/Get the maximum distance away to look for a matching pixel. Default is 0. */ itkSetMacro(ToleranceRadius, int); - itkGetMacro(ToleranceRadius, int); + itkGetConstMacro(ToleranceRadius, int); /** Set/Get the minimum threshold for pixels to be different. Default is 0. */ itkSetMacro(DifferenceThreshold, OutputPixelType); - itkGetMacro(DifferenceThreshold, OutputPixelType); + itkGetConstMacro(DifferenceThreshold, OutputPixelType); /** Set/Get ignore boundary pixels. Useful when resampling may have * introduced difference pixel values along the image edge * Default = false */ itkSetMacro(IgnoreBoundaryPixels, bool); - itkGetMacro(IgnoreBoundaryPixels, bool); + itkGetConstMacro(IgnoreBoundaryPixels, bool); /** Get parameters of the difference image after execution. */ - itkGetMacro(MeanDifference, RealType); - itkGetMacro(TotalDifference, AccumulateType); - itkGetMacro(NumberOfPixelsWithDifferences, unsigned long); + itkGetConstMacro(MeanDifference, RealType); + itkGetConstMacro(TotalDifference, AccumulateType); + itkGetConstMacro(NumberOfPixelsWithDifferences, unsigned long); protected: DifferenceImageFilter(); diff --git a/Utilities/ITK/Code/Common/itkDiffusionTensor3D.h b/Utilities/ITK/Code/Common/itkDiffusionTensor3D.h index 6402a32029..ee2eb65f55 100644 --- a/Utilities/ITK/Code/Common/itkDiffusionTensor3D.h +++ b/Utilities/ITK/Code/Common/itkDiffusionTensor3D.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiffusionTensor3D.h,v $ Language: C++ - Date: $Date: 2008-10-07 09:09:39 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-23 21:43:57 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -86,7 +86,7 @@ public: /** Propagating some typedef from the superclass */ typedef typename Superclass::ValueType ValueType; typedef typename Superclass::ComponentType ComponentType; -#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && (__GNUC__ == 3 && __GNUC_MINOR__ == 2 && __GNUC_PATCHLEVEL__ == 3) +#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && (__GNUC__ == 3) typedef ComponentType ComponentArrayType[6]; #else typedef typename Superclass::ComponentArrayType ComponentArrayType; diff --git a/Utilities/ITK/Code/Common/itkElasticBodyReciprocalSplineKernelTransform.h b/Utilities/ITK/Code/Common/itkElasticBodyReciprocalSplineKernelTransform.h index b983b71324..3689d20c11 100644 --- a/Utilities/ITK/Code/Common/itkElasticBodyReciprocalSplineKernelTransform.h +++ b/Utilities/ITK/Code/Common/itkElasticBodyReciprocalSplineKernelTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkElasticBodyReciprocalSplineKernelTransform.h,v $ Language: C++ - Date: $Date: 2008-10-07 12:03:53 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-25 12:24:05 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,7 +73,7 @@ public: itkSetMacro( Alpha, TScalarType ); /** Get alpha */ - itkGetMacro( Alpha, TScalarType ); + itkGetConstMacro( Alpha, TScalarType ); /** These (rather redundant) typedefs are needed because on SGI, typedefs * are not inherited */ diff --git a/Utilities/ITK/Code/Common/itkElasticBodySplineKernelTransform.h b/Utilities/ITK/Code/Common/itkElasticBodySplineKernelTransform.h index d6655db078..91846d1577 100644 --- a/Utilities/ITK/Code/Common/itkElasticBodySplineKernelTransform.h +++ b/Utilities/ITK/Code/Common/itkElasticBodySplineKernelTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkElasticBodySplineKernelTransform.h,v $ Language: C++ - Date: $Date: 2008-10-07 12:03:53 $ - Version: $Revision: 1.35 $ + Date: $Date: 2009-04-25 12:24:05 $ + Version: $Revision: 1.36 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,7 +73,7 @@ public: itkSetMacro( Alpha, TScalarType ); /** Get alpha */ - itkGetMacro( Alpha, TScalarType ); + itkGetConstMacro( Alpha, TScalarType ); /** These (rather redundant) typedefs are needed because on SGI, typedefs * are not inherited */ diff --git a/Utilities/ITK/Code/Common/itkEllipsoidInteriorExteriorSpatialFunction.h b/Utilities/ITK/Code/Common/itkEllipsoidInteriorExteriorSpatialFunction.h index 0112221b36..87ab136bf2 100644 --- a/Utilities/ITK/Code/Common/itkEllipsoidInteriorExteriorSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkEllipsoidInteriorExteriorSpatialFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEllipsoidInteriorExteriorSpatialFunction.h,v $ Language: C++ - Date: $Date: 2008-10-07 12:03:53 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-25 12:24:05 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -62,11 +62,11 @@ public: typedef vnl_matrix_fixed<double, VDimension, VDimension> OrientationType; /** Set/Get and set the center of the ellipsoid. */ - itkGetMacro(Center, InputType); + itkGetConstMacro(Center, InputType); itkSetMacro(Center, InputType); /** Get and set the axes lengths of the ellipsoid. */ - itkGetMacro(Axes, InputType); + itkGetConstMacro(Axes, InputType); itkSetMacro(Axes, InputType); /** Set the orientation vectors (must be orthogonal) of the ellipsoid axes. diff --git a/Utilities/ITK/Code/Common/itkEuler2DTransform.h b/Utilities/ITK/Code/Common/itkEuler2DTransform.h index 9b9a23513c..a81552424f 100644 --- a/Utilities/ITK/Code/Common/itkEuler2DTransform.h +++ b/Utilities/ITK/Code/Common/itkEuler2DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEuler2DTransform.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:56 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -84,6 +84,11 @@ public: typedef typename Superclass::InputVnlVectorType InputVnlVectorType; typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; typedef typename Superclass::MatrixType MatrixType; + + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; /** * This method creates and returns a new Euler2DTransform object @@ -91,6 +96,12 @@ public: */ void CloneInverseTo( Pointer & newinverse ) const; + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + /** * This method creates and returns a new Euler2DTransform object * which has the same parameters as self. diff --git a/Utilities/ITK/Code/Common/itkEuler2DTransform.txx b/Utilities/ITK/Code/Common/itkEuler2DTransform.txx index 581a4fc499..334f725be4 100644 --- a/Utilities/ITK/Code/Common/itkEuler2DTransform.txx +++ b/Utilities/ITK/Code/Common/itkEuler2DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEuler2DTransform.txx,v $ Language: C++ - Date: $Date: 2008-10-13 15:36:31 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-09 09:23:20 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,9 +47,35 @@ Euler2DTransform<TScalarType>:: CloneInverseTo( Pointer & result ) const { result = New(); - result->SetCenter( this->GetCenter() ); // inverse have the same center - result->SetAngle( -this->GetAngle() ); - result->SetTranslation( -( this->GetInverseMatrix() * this->GetTranslation() ) ); + this->GetInverse(result.GetPointer()); +} + +// return an inverse transformation +template<class TScalarType> +bool +Euler2DTransform<TScalarType>:: +GetInverse( Self* inverse) const +{ + if(!inverse) + { + return false; + } + + inverse->SetCenter( this->GetCenter() ); // inverse have the same center + inverse->SetAngle( -this->GetAngle() ); + inverse->SetTranslation( -( this->GetInverseMatrix() * this->GetTranslation() ) ); + + return true; +} + +// Return an inverse of this transform +template<class TScalarType> +typename Euler2DTransform<TScalarType>::InverseTransformBasePointer +Euler2DTransform<TScalarType> +::GetInverseTransform() const +{ + Pointer inv = New(); + return GetInverse(inv) ? inv.GetPointer() : NULL; } // Create and return an inverse transformation diff --git a/Utilities/ITK/Code/Common/itkEuler3DTransform.txx b/Utilities/ITK/Code/Common/itkEuler3DTransform.txx index a70f6a53ff..4e457c2d9f 100644 --- a/Utilities/ITK/Code/Common/itkEuler3DTransform.txx +++ b/Utilities/ITK/Code/Common/itkEuler3DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEuler3DTransform.txx,v $ Language: C++ - Date: $Date: 2008-10-13 15:36:31 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-04-05 10:56:39 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -152,9 +152,9 @@ Euler3DTransform<TScalarType> { if(m_ComputeZYX) { - m_AngleY = -asin(this->GetMatrix()[2][0]); + m_AngleY = -vcl_asin(this->GetMatrix()[2][0]); double C = vcl_cos(m_AngleY); - if(fabs(C)>0.00005) + if(vcl_fabs(C)>0.00005) { double x = this->GetMatrix()[2][2] / C; double y = this->GetMatrix()[2][1] / C; @@ -175,7 +175,7 @@ Euler3DTransform<TScalarType> { m_AngleX = vcl_asin(this->GetMatrix()[2][1]); double A = vcl_cos(m_AngleX); - if(fabs(A)>0.00005) + if(vcl_fabs(A)>0.00005) { double x = this->GetMatrix()[2][2] / A; double y = -this->GetMatrix()[2][0] / A; diff --git a/Utilities/ITK/Code/Common/itkEventObject.h b/Utilities/ITK/Code/Common/itkEventObject.h index 6ccad28d3f..26dc9a11f1 100644 --- a/Utilities/ITK/Code/Common/itkEventObject.h +++ b/Utilities/ITK/Code/Common/itkEventObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEventObject.h,v $ Language: C++ - Date: $Date: 2008-10-13 15:36:31 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-05-25 08:34:20 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,14 +41,14 @@ namespace itk * particular kinds of events produced by a specific itk::Object. This * mechanism decouples classes among them. * - * As oppossed to itk::Exception, itk::EventObject does not represent error + * As opposed to itk::Exception, itk::EventObject does not represent error * states, but simply flow of information allowing to trigger actions - * as a consecuence of changes occurring in state on some itk::Objects. + * as a consequence of changes occurring in state on some itk::Objects. * * itk::EventObject carries information in its own type, it relies on the * appropiate use of the RTTI (Run Time Type Information). * - * A set of standard EventObjects is defined near the end of itkIndent.h. + * A set of standard EventObjects is defined near the end of itkEventObject.h. * * \sa itk::Command * \sa itk::ExceptionObject diff --git a/Utilities/ITK/Code/Common/itkFileOutputWindow.h b/Utilities/ITK/Code/Common/itkFileOutputWindow.h index 1e247e5a6b..29b72b1157 100644 --- a/Utilities/ITK/Code/Common/itkFileOutputWindow.h +++ b/Utilities/ITK/Code/Common/itkFileOutputWindow.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFileOutputWindow.h,v $ Language: C++ - Date: $Date: 2008-10-16 23:25:41 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:24:06 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,7 +59,7 @@ public: /** Set/Get the buffer flushing mode */ itkSetMacro(Flush,bool); - itkGetMacro(Flush,bool); + itkGetConstMacro(Flush,bool); itkBooleanMacro(Flush); /** Setting append will cause the log file to be @@ -67,7 +67,7 @@ public: * it will be overwritten each time the FileOutputWindow * is created. */ itkSetMacro(Append, bool); - itkGetMacro(Append, bool); + itkGetConstMacro(Append, bool); itkBooleanMacro(Append); protected: diff --git a/Utilities/ITK/Code/Common/itkFiniteCylinderSpatialFunction.h b/Utilities/ITK/Code/Common/itkFiniteCylinderSpatialFunction.h index e23555725b..e8531a3618 100644 --- a/Utilities/ITK/Code/Common/itkFiniteCylinderSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkFiniteCylinderSpatialFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFiniteCylinderSpatialFunction.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:56 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-25 12:24:07 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -57,20 +57,20 @@ public: typedef typename Superclass::OutputType OutputType; /** Set/Get and set the center of the cylinder. */ - itkGetMacro(Center, InputType); + itkGetConstMacro(Center, InputType); itkSetMacro(Center, InputType); /** Get and set the medial axis length of the cylinder. */ - itkGetMacro(AxisLength, double); + itkGetConstMacro(AxisLength, double); itkSetMacro(AxisLength, double); /** Get and set the radius length of the cylinder. */ - itkGetMacro(Radius, double); + itkGetConstMacro(Radius, double); itkSetMacro(Radius, double); /** Set the orientation vectors (must be orthogonal) of the ellipsoid axes. * Must be normalized!!!!! */ - itkGetMacro(Orientation, InputType); + itkGetConstMacro(Orientation, InputType); itkSetMacro(Orientation, InputType); /** Evaluates the function at a given position. */ diff --git a/Utilities/ITK/Code/Common/itkFiniteCylinderSpatialFunction.txx b/Utilities/ITK/Code/Common/itkFiniteCylinderSpatialFunction.txx index 6b58f18242..a08bf3b4ba 100644 --- a/Utilities/ITK/Code/Common/itkFiniteCylinderSpatialFunction.txx +++ b/Utilities/ITK/Code/Common/itkFiniteCylinderSpatialFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFiniteCylinderSpatialFunction.txx,v $ Language: C++ -Date: $Date: 2008-10-16 23:25:41 $ -Version: $Revision: 1.8 $ +Date: $Date: 2009-04-06 16:49:29 $ +Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -63,8 +63,8 @@ FiniteCylinderSpatialFunction<VDimension, TInput> //the point is within the length of the cylinder along the medial axis const double distanceFromCenter = dot_product( medialAxisVector.GetVnlVector(), pointVector.GetVnlVector() ); - if(fabs(distanceFromCenter) <= (halfAxisLength) - && m_Radius >= vcl_sqrt(pow(pointVector.GetVnlVector().magnitude(),2.0) - vcl_pow(distanceFromCenter,2.0))) + if(vcl_fabs(distanceFromCenter) <= (halfAxisLength) + && m_Radius >= vcl_sqrt(vcl_pow(pointVector.GetVnlVector().magnitude(),2.0) - vcl_pow(distanceFromCenter,2.0))) { return 1; } diff --git a/Utilities/ITK/Code/Common/itkFiniteDifferenceSparseImageFilter.h b/Utilities/ITK/Code/Common/itkFiniteDifferenceSparseImageFilter.h index 30a64de4e4..bb26de6f60 100644 --- a/Utilities/ITK/Code/Common/itkFiniteDifferenceSparseImageFilter.h +++ b/Utilities/ITK/Code/Common/itkFiniteDifferenceSparseImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFiniteDifferenceSparseImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:56 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-25 12:24:07 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -107,7 +107,7 @@ public: void SetSparseFunction( SparseFunctionType *sf ); itkSetMacro(PrecomputeFlag, bool); - itkGetMacro(PrecomputeFlag, bool); + itkGetConstMacro(PrecomputeFlag, bool); protected: FiniteDifferenceSparseImageFilter(); diff --git a/Utilities/ITK/Code/Common/itkFourierSeriesPath.txx b/Utilities/ITK/Code/Common/itkFourierSeriesPath.txx index 5b92d060f6..c5796162c6 100644 --- a/Utilities/ITK/Code/Common/itkFourierSeriesPath.txx +++ b/Utilities/ITK/Code/Common/itkFourierSeriesPath.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFourierSeriesPath.txx,v $ Language: C++ - Date: $Date: 2008-10-16 23:25:41 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-05 18:12:09 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,7 +36,7 @@ FourierSeriesPath<VDimension> numHarmonics = m_CosCoefficients->Size(); output.Fill(0); - const double PI = 4.0 * atan( 1.0 ); + const double PI = 4.0 * vcl_atan( 1.0 ); if( numHarmonics > 0 ) { output += m_CosCoefficients->ElementAt(0); } @@ -64,7 +64,7 @@ FourierSeriesPath<VDimension> numHarmonics = m_CosCoefficients->Size(); output.Fill(0); - const double PI = 4.0 * atan( 1.0 ); + const double PI = 4.0 * vcl_atan( 1.0 ); for(int n=1; n<numHarmonics; n++) { diff --git a/Utilities/ITK/Code/Common/itkFrustumSpatialFunction.h b/Utilities/ITK/Code/Common/itkFrustumSpatialFunction.h index 0843a1bfe4..5809efc3bc 100644 --- a/Utilities/ITK/Code/Common/itkFrustumSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkFrustumSpatialFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFrustumSpatialFunction.h,v $ Language: C++ - Date: $Date: 2008-10-16 23:25:41 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-25 12:24:07 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -67,28 +67,28 @@ public: OutputType Evaluate(const InputType& position) const; /** Get and set the center of the sphere */ - itkGetMacro( Apex, InputType); + itkGetConstMacro( Apex, InputType); itkSetMacro( Apex, InputType); /** Get and set the angle of the pyramid axis * with respect to the Z axis */ - itkGetMacro( AngleZ, double); + itkGetConstMacro( AngleZ, double); itkSetMacro( AngleZ, double); /** Get and set the aperture angle in X */ - itkGetMacro( ApertureAngleX, double); + itkGetConstMacro( ApertureAngleX, double); itkSetMacro( ApertureAngleX, double); /** Get and set the aperture angle in Y */ - itkGetMacro( ApertureAngleY, double); + itkGetConstMacro( ApertureAngleY, double); itkSetMacro( ApertureAngleY, double); /** Get and set the top plane distance to the Apex */ - itkGetMacro( TopPlane, double); + itkGetConstMacro( TopPlane, double); itkSetMacro( TopPlane, double); /** Get and set the bottom plane distance to the Apex */ - itkGetMacro( BottomPlane, double); + itkGetConstMacro( BottomPlane, double); itkSetMacro( BottomPlane, double); /** Set macro to set the plane in which the frustum should rotate */ diff --git a/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.h b/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.h index 4cde2c34be..1e5e3f5b08 100644 --- a/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.h +++ b/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianBlurImageFunction.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:56 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-05-14 02:11:46 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -138,7 +138,7 @@ public: * used in the Gaussian kernel */ itkSetMacro( MaximumKernelWidth, int ); - itkGetMacro( MaximumKernelWidth, int ); + itkGetConstMacro( MaximumKernelWidth, int ); /** Set/GetUseImageSpacing() This flag is used by the underling * GaussianOperator to decide if the image spacing should be used @@ -146,7 +146,7 @@ public: * and UseImageSpacingOff() provide a similar functionality. */ itkSetMacro( UseImageSpacing, bool ); - itkGetMacro( UseImageSpacing, bool ); + itkGetConstMacro( UseImageSpacing, bool ); itkBooleanMacro( UseImageSpacing ); @@ -164,6 +164,9 @@ protected: private: + virtual TOutput EvaluateAtIndex( + const IndexType & index, const OperatorArrayType & operatorArray ) const; + SigmaArrayType m_Sigma; OperatorImageFunctionPointer m_OperatorImageFunction; mutable OperatorArrayType m_OperatorArray; diff --git a/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.txx b/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.txx index 48602aa694..12af06c433 100644 --- a/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianBlurImageFunction.txx,v $ Language: C++ - Date: $Date: 2008-10-17 01:08:45 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-05-14 12:32:23 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -235,10 +235,19 @@ template <class TInputImage,class TOutput> TOutput GaussianBlurImageFunction<TInputImage,TOutput> ::EvaluateAtIndex(const IndexType& index) const +{ + return this->EvaluateAtIndex( index, m_OperatorArray ); +} + +/** Evaluate the function at the specifed point */ +template <class TInputImage,class TOutput> +TOutput +GaussianBlurImageFunction<TInputImage,TOutput> +::EvaluateAtIndex(const IndexType& index, const OperatorArrayType & operatorArray ) const { // First time we use the complete image and fill the internal image m_OperatorImageFunction->SetInputImage(m_Caster->GetOutput()); - m_OperatorImageFunction->SetOperator(m_OperatorArray[0]); + m_OperatorImageFunction->SetOperator(operatorArray[0]); // if 1D Image we return the result if(itkGetStaticConstMacro(ImageDimension) == 1) @@ -246,7 +255,7 @@ GaussianBlurImageFunction<TInputImage,TOutput> return m_OperatorImageFunction->EvaluateAtIndex(index); } - // Compute the centered index fo the neighborhood + // Compute the centered index of the neighborhood IndexType centerIndex; for(unsigned int i=0;i<itkGetStaticConstMacro(ImageDimension);i++) { @@ -284,20 +293,20 @@ GaussianBlurImageFunction<TInputImage,TOutput> } regionN.SetIndex(ind); - itk::ImageLinearConstIteratorWithIndex<InternalImageType> it(m_Caster->GetOutput(),region); + typename InternalImageType::RegionType regionS = region; + regionS.Crop( m_Caster->GetOutput()->GetBufferedRegion() ); + + itk::ImageLinearConstIteratorWithIndex<InternalImageType> it(m_Caster->GetOutput(),regionS); itk::ImageLinearIteratorWithIndex<InternalImageType> itN(m_InternalImage,regionN); it.SetDirection(1); itN.SetDirection(1); it.GoToBeginOfLine(); itN.GoToBeginOfLine(); - while(!it.IsAtEnd()) + while( !it.IsAtEnd() ) { - while(!it.IsAtEndOfLine()) + while( !it.IsAtEndOfLine() ) { - if(m_Caster->GetOutput()->GetLargestPossibleRegion().IsInside(it.GetIndex())) - { - itN.Set(m_OperatorImageFunction->EvaluateAtIndex(it.GetIndex())); - } + itN.Set(m_OperatorImageFunction->EvaluateAtIndex(it.GetIndex())); ++it; ++itN; } @@ -323,7 +332,7 @@ GaussianBlurImageFunction<TInputImage,TOutput> m_OperatorImageFunction->SetInputImage(m_InternalImage); - m_OperatorImageFunction->SetOperator(m_OperatorArray[direction]); + m_OperatorImageFunction->SetOperator(operatorArray[direction]); itk::ImageLinearIteratorWithIndex<InternalImageType> itr(m_InternalImage,region); @@ -426,117 +435,7 @@ GaussianBlurImageFunction<TInputImage,TOutput> this->RecomputeContinuousGaussianKernel(offset); - // First time we use the complete image and fill the internal image - m_OperatorImageFunction->SetInputImage(m_Caster->GetOutput()); - m_OperatorImageFunction->SetOperator(m_ContinuousOperatorArray[0]); - - // if 1D Image we return the result - if(itkGetStaticConstMacro(ImageDimension) == 1) - { - return m_OperatorImageFunction->EvaluateAtIndex(index); - } - - // Compute the centered index fo the neighborhood - IndexType centerIndex; - for(unsigned int i=0;i<itkGetStaticConstMacro(ImageDimension);i++) - { - centerIndex[i] = (unsigned long)((float)m_InternalImage->GetBufferedRegion().GetSize()[i]/2.0); - } - - // first direction - typename InternalImageType::IndexType ind; - ind = index; - - //Define the region of the iterator - typename InternalImageType::RegionType region; - typename InternalImageType::SizeType size = m_InternalImage->GetBufferedRegion().GetSize(); - size[0]=1; - region.SetSize(size); - - for(unsigned int i = 0;i<itkGetStaticConstMacro(ImageDimension);i++) - { - if(i != 0) - { - ind[i] -= centerIndex[i]; - } - } - region.SetIndex(ind); - - typename InternalImageType::RegionType regionN; - regionN.SetSize(size); - ind = centerIndex; - for(unsigned int i = 0;i<itkGetStaticConstMacro(ImageDimension);i++) - { - if(i != 0) - { - ind[i] = 0; - } - } - regionN.SetIndex(ind); - - itk::ImageLinearConstIteratorWithIndex<InternalImageType> it(m_Caster->GetOutput(),region); - itk::ImageLinearIteratorWithIndex<InternalImageType> itN(m_InternalImage,regionN); - it.SetDirection(1); - itN.SetDirection(1); - it.GoToBeginOfLine(); - itN.GoToBeginOfLine(); - while(!it.IsAtEnd()) - { - while(!it.IsAtEndOfLine()) - { - if(m_Caster->GetOutput()->GetLargestPossibleRegion().IsInside(it.GetIndex())) - { - itN.Set(m_OperatorImageFunction->EvaluateAtIndex(it.GetIndex())); - } - ++it; - ++itN; - } - it.NextLine(); - itN.NextLine(); - } - - // Do the convolution in other directions - for(unsigned int direction=1;direction<itkGetStaticConstMacro(ImageDimension);direction++) - { - - size[direction] = 1; - ind = centerIndex; - for(unsigned int i = 0;i<itkGetStaticConstMacro(ImageDimension);i++) - { - if(i > direction) - { - ind[i] = 0; - } - } - region.SetSize(size); - region.SetIndex(ind); - - - m_OperatorImageFunction->SetInputImage(m_InternalImage); - m_OperatorImageFunction->SetOperator(m_ContinuousOperatorArray[direction]); - - itk::ImageLinearIteratorWithIndex<InternalImageType> itr(m_InternalImage,region); - - unsigned int dir = direction +1; - if(dir == itkGetStaticConstMacro(ImageDimension)) - { - dir = itkGetStaticConstMacro(ImageDimension)-1; - } - - itr.SetDirection(dir); - itr.GoToBeginOfLine(); - while(!itr.IsAtEnd()) - { - while(!itr.IsAtEndOfLine()) - { - itr.Set(m_OperatorImageFunction->EvaluateAtIndex(itr.GetIndex())); - ++itr; - } - itr.NextLine(); - } - } - - return m_InternalImage->GetPixel(centerIndex); + return this->EvaluateAtIndex( index, m_ContinuousOperatorArray ); } /** Evaluate the function at specified ContinousIndex position.*/ @@ -551,7 +450,6 @@ GaussianBlurImageFunction<TInputImage,TOutput> point[i] = index[i]; } return this->Evaluate(point); - } } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkGaussianDerivativeSpatialFunction.h b/Utilities/ITK/Code/Common/itkGaussianDerivativeSpatialFunction.h index 9cf719a5e1..2cc39c15fc 100644 --- a/Utilities/ITK/Code/Common/itkGaussianDerivativeSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkGaussianDerivativeSpatialFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianDerivativeSpatialFunction.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:56 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:24:09 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -78,15 +78,15 @@ public: /** Gets and sets for gaussian parameters */ itkSetMacro(Scale, double); - itkGetMacro(Scale, double); + itkGetConstMacro(Scale, double); itkSetMacro(Normalized, bool); - itkGetMacro(Normalized, bool); + itkGetConstMacro(Normalized, bool); itkSetMacro(Sigma, ArrayType); - itkGetMacro(Sigma, ArrayType); + itkGetConstMacro(Sigma, ArrayType); itkSetMacro(Mean, ArrayType); - itkGetMacro(Mean, ArrayType); + itkGetConstMacro(Mean, ArrayType); itkSetMacro(Direction, unsigned int); - itkGetMacro(Direction, unsigned int); + itkGetConstMacro(Direction, unsigned int); protected: GaussianDerivativeSpatialFunction(); diff --git a/Utilities/ITK/Code/Common/itkGaussianOperator.txx b/Utilities/ITK/Code/Common/itkGaussianOperator.txx index 79877564b7..66e82e2684 100644 --- a/Utilities/ITK/Code/Common/itkGaussianOperator.txx +++ b/Utilities/ITK/Code/Common/itkGaussianOperator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianOperator.txx,v $ Language: C++ - Date: $Date: 2009-02-09 18:56:24 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,7 +34,7 @@ GaussianOperator<TPixel,VDimension, TAllocator> int j; typename CoefficientVector::iterator it; - const double et = ::exp(-m_Variance); + const double et = vcl_exp(-m_Variance); const double cap = 1.0 - m_MaximumError; // Create the kernel coefficients as a std::vector @@ -93,7 +93,7 @@ GaussianOperator<TPixel,VDimension, TAllocator> else { const double m = 3.75 / d; - accumulator =(::exp(d)/::sqrt(d))*(0.39894228+m*(0.1328592e-1 + accumulator =(vcl_exp(d)/vcl_sqrt(d))*(0.39894228+m*(0.1328592e-1 +m*(0.225319e-2+m*(-0.157565e-2+m*(0.916281e-2 +m*(-0.2057706e-1+m*(0.2635537e-1+m*(-0.1647633e-1 +m*0.392377e-2)))))))); @@ -125,7 +125,7 @@ GaussianOperator<TPixel,VDimension, TAllocator> accumulator = 0.39894228+m*(-0.3988024e-1+m*(-0.362018e-2 +m*(0.163801e-2+m*(-0.1031555e-1+m*accumulator)))); - accumulator *= (::exp(d)/::sqrt(d)); + accumulator *= (vcl_exp(d)/vcl_sqrt(d)); } if( y<0.0 ) @@ -163,12 +163,12 @@ GaussianOperator<TPixel,VDimension, TAllocator> qip = accumulator=0.0; qi = 1.0; - for( j = 2*(n+(int)::sqrt(ACCURACY*n)); j > 0; j-- ) + for( j = 2*(n+(int)vcl_sqrt(ACCURACY*n)); j > 0; j-- ) { qim = qip+j*toy*qi; qip = qi; qi = qim; - if (fabs(qi) > 1.0e10) + if (vcl_fabs(qi) > 1.0e10) { accumulator *= 1.0e-10; qi *= 1.0e-10; diff --git a/Utilities/ITK/Code/Common/itkGaussianSpatialFunction.h b/Utilities/ITK/Code/Common/itkGaussianSpatialFunction.h index 28321b0469..8d4fb1fc86 100644 --- a/Utilities/ITK/Code/Common/itkGaussianSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkGaussianSpatialFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianSpatialFunction.h,v $ Language: C++ - Date: $Date: 2008-10-17 01:08:45 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:24:09 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -70,13 +70,13 @@ public: /** Gets and sets for gaussian parameters */ itkSetMacro(Scale, double); - itkGetMacro(Scale, double); + itkGetConstMacro(Scale, double); itkSetMacro(Normalized, bool); - itkGetMacro(Normalized, bool); + itkGetConstMacro(Normalized, bool); itkSetMacro(Sigma, ArrayType); - itkGetMacro(Sigma, ArrayType); + itkGetConstMacro(Sigma, ArrayType); itkSetMacro(Mean, ArrayType); - itkGetMacro(Mean, ArrayType); + itkGetConstMacro(Mean, ArrayType); protected: GaussianSpatialFunction(); diff --git a/Utilities/ITK/Code/Common/itkGaussianSpatialFunction.txx b/Utilities/ITK/Code/Common/itkGaussianSpatialFunction.txx index 9295178401..936c1b2e14 100644 --- a/Utilities/ITK/Code/Common/itkGaussianSpatialFunction.txx +++ b/Utilities/ITK/Code/Common/itkGaussianSpatialFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianSpatialFunction.txx,v $ Language: C++ - Date: $Date: 2008-10-17 01:08:45 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-05-11 16:54:23 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,6 +18,7 @@ #define __itkGaussianSpatialFunction_txx #include <math.h> +#include "vnl/vnl_math.h" #include "itkGaussianSpatialFunction.h" namespace itk @@ -51,22 +52,16 @@ GaussianSpatialFunction<TOutput, VImageDimension, TInput> // Normalizing the Gaussian is important for statistical applications // but is generally not desirable for creating images because of the // very small numbers involved (would need to use doubles) - double prefixDenom; + double prefixDenom = 1.0; if (m_Normalized) { - prefixDenom = m_Sigma[0]; + const double squareRootOfTwoPi = vcl_sqrt( 2.0 * vnl_math::pi ); - for(unsigned int i = 1; i < VImageDimension; i++) + for(unsigned int i = 0; i < VImageDimension; i++) { - prefixDenom *= m_Sigma[i]; + prefixDenom *= m_Sigma[i] * squareRootOfTwoPi; } - - prefixDenom *= 2 * 3.1415927; - } - else - { - prefixDenom = 1.0; } double suffixExp = 0; @@ -89,21 +84,8 @@ GaussianSpatialFunction<TOutput, VImageDimension, TInput> { Superclass::PrintSelf(os,indent); - unsigned int i; - os << indent << "Sigma: ["; - for( i=0; i+1 < VImageDimension; i++ ) - { - os << m_Sigma[i] << ", "; - } - os << "]" << std::endl; - - os << indent << "Mean: ["; - for( i=0; i+1 < VImageDimension; i++ ) - { - os << m_Mean[i] << ", "; - } - os << "]" << std::endl; - + os << indent << "Sigma: " << m_Sigma << std::endl; + os << indent << "Mean: " << m_Mean << std::endl; os << indent << "Scale: " << m_Scale << std::endl; os << indent << "Normalized?: " << m_Normalized << std::endl; } diff --git a/Utilities/ITK/Code/Common/itkIdentityTransform.h b/Utilities/ITK/Code/Common/itkIdentityTransform.h index b23c848885..aa8c023617 100644 --- a/Utilities/ITK/Code/Common/itkIdentityTransform.h +++ b/Utilities/ITK/Code/Common/itkIdentityTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIdentityTransform.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:56 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -104,6 +104,11 @@ public: itkGetStaticConstMacro(InputSpaceDimension)> InputPointType; typedef Point<TScalarType, itkGetStaticConstMacro(OutputSpaceDimension)> OutputPointType; + + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; /** Method to transform a point. */ virtual OutputPointType TransformPoint(const InputPointType &point ) const @@ -166,6 +171,12 @@ public: return this->m_Jacobian; } + /** Return an inverse of the identity transform - another identity transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const + { + return this->New().GetPointer(); + } + /** Indicates that this transform is linear. That is, given two * points P and Q, and scalar coefficients a and b, then * diff --git a/Utilities/ITK/Code/Common/itkImageBase.h b/Utilities/ITK/Code/Common/itkImageBase.h index d3c117cbd2..a29ba52ad3 100644 --- a/Utilities/ITK/Code/Common/itkImageBase.h +++ b/Utilities/ITK/Code/Common/itkImageBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageBase.h,v $ Language: C++ - Date: $Date: 2009-02-18 17:40:55 $ - Version: $Revision: 1.76 $ + Date: $Date: 2009-05-07 14:03:42 $ + Version: $Revision: 1.80 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -196,6 +196,14 @@ public: * 0. */ itkGetConstReferenceMacro(Origin, PointType); + /** Allocate the image memory. The size of the image must + * already be set, e.g. by calling SetRegions(). + * + * This method should be pure virtual, if backwards compatibility + * was not required. + */ + virtual void Allocate() {}; + /** Set the region object that defines the size and starting index * for the largest possible region this image could represent. This * is used in determining how much memory would be needed to load an @@ -344,8 +352,10 @@ public: virtual void SetSpacing (const float spacing[VImageDimension]); - /** Get the index (discrete) from a physical point. - * Floating point index results are truncated to integers. + /** Get the index (discrete) of a voxel from a physical point. + * Floating point index results are rounded to integers + * if ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY is on + * and truncated otherwise. * Returns true if the resulting index is within the image, false otherwise * \sa Transform */ #ifdef ITK_USE_TEMPLATE_META_PROGRAMMING_LOOP_UNROLLING @@ -374,7 +384,11 @@ public: { sum += this->m_PhysicalPointToIndex[i][j] * (point[j] - this->m_Origin[j]); } +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + index[i] = static_cast< IndexValueType>( itk::Math::RoundHalfIntegerUp( sum ) ); +#else index[i] = static_cast< IndexValueType>( sum ); +#endif } // Now, check to see if the index is within allowed bounds diff --git a/Utilities/ITK/Code/Common/itkImageBase.txx b/Utilities/ITK/Code/Common/itkImageBase.txx index c77c9672e4..0b5bdc2da5 100644 --- a/Utilities/ITK/Code/Common/itkImageBase.txx +++ b/Utilities/ITK/Code/Common/itkImageBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageBase.txx,v $ Language: C++ - Date: $Date: 2009-02-18 17:40:55 $ - Version: $Revision: 1.55 $ + Date: $Date: 2009-04-05 17:10:16 $ + Version: $Revision: 1.56 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,6 +25,7 @@ #include "itkFastMutexLock.h" #include "itkProcessObject.h" #include "itkSpatialOrientation.h" +#include <string.h> namespace itk { diff --git a/Utilities/ITK/Code/Common/itkImageConstIterator.h b/Utilities/ITK/Code/Common/itkImageConstIterator.h index 431926431a..247a0e3c1d 100644 --- a/Utilities/ITK/Code/Common/itkImageConstIterator.h +++ b/Utilities/ITK/Code/Common/itkImageConstIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageConstIterator.h,v $ Language: C++ - Date: $Date: 2008-10-17 01:41:59 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-05-11 21:48:29 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,6 +21,7 @@ #include "itkIndex.h" #include "itkSize.h" #include "itkOffset.h" +#include "itkNumericTraits.h" namespace itk { @@ -173,6 +174,15 @@ public: m_Buffer = m_Image->GetBufferPointer(); m_Region = region; +#ifdef ITK_USE_REGION_VALIDATION_IN_ITERATORS + if( region.GetNumberOfPixels() > 0 ) // If region is non-empty + { + const RegionType & bufferedRegion = m_Image->GetBufferedRegion(); + itkAssertOrThrowMacro( (bufferedRegion.IsInside( m_Region )), + "Region " << m_Region << " is outside of buffered region " << bufferedRegion ); + } +#endif + // Compute the start offset m_Offset = m_Image->ComputeOffset( m_Region.GetIndex() ); m_BeginOffset = m_Offset; diff --git a/Utilities/ITK/Code/Common/itkImageConstIteratorWithIndex.txx b/Utilities/ITK/Code/Common/itkImageConstIteratorWithIndex.txx index 1647d4afe0..2cc94d0acd 100644 --- a/Utilities/ITK/Code/Common/itkImageConstIteratorWithIndex.txx +++ b/Utilities/ITK/Code/Common/itkImageConstIteratorWithIndex.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageConstIteratorWithIndex.txx,v $ Language: C++ - Date: $Date: 2008-10-17 01:41:59 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-05-11 21:48:29 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,6 +18,7 @@ #define __itkImageConstIteratorWithIndex_txx #include "itkImageConstIteratorWithIndex.h" +#include <string.h> namespace itk { @@ -81,6 +82,15 @@ ImageConstIteratorWithIndex<TImage> m_PositionIndex = m_BeginIndex; m_Region = region; +#ifdef ITK_USE_REGION_VALIDATION_IN_ITERATORS + if( region.GetNumberOfPixels() > 0 ) // If region is non-empty + { + const RegionType & bufferedRegion = m_Image->GetBufferedRegion(); + itkAssertOrThrowMacro( (bufferedRegion.IsInside( m_Region )), + "Region " << m_Region << " is outside of buffered region " << bufferedRegion ); + } +#endif + memcpy(m_OffsetTable, m_Image->GetOffsetTable(), (ImageDimension+1)*sizeof(unsigned long)); diff --git a/Utilities/ITK/Code/Common/itkImageFunction.h b/Utilities/ITK/Code/Common/itkImageFunction.h index 6999f39798..21167aa3f1 100644 --- a/Utilities/ITK/Code/Common/itkImageFunction.h +++ b/Utilities/ITK/Code/Common/itkImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageFunction.h,v $ Language: C++ - Date: $Date: 2008-10-17 13:35:26 $ - Version: $Revision: 1.47 $ + Date: $Date: 2009-05-07 14:03:42 $ + Version: $Revision: 1.48 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -127,6 +127,10 @@ public: const ContinuousIndexType & index ) const = 0; /** Check if an index is inside the image buffer. + * If ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY is on, + * we take into account the fact that each voxel has its + * center at the integer coordinate and extends half way + * to the next integer coordinate. * \warning For efficiency, no validity checking of * the input image is done. */ virtual bool IsInsideBuffer( const IndexType & index ) const @@ -234,7 +238,8 @@ private: }; -} // end namespace itk +}// end namespace itk + // Define instantiation macro for this template. #define ITK_TEMPLATE_ImageFunction(_, EXPORT, x, y) namespace itk { \ diff --git a/Utilities/ITK/Code/Common/itkImageFunction.txx b/Utilities/ITK/Code/Common/itkImageFunction.txx index 70432f11b5..a04a9ffcb5 100644 --- a/Utilities/ITK/Code/Common/itkImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageFunction.txx,v $ Language: C++ - Date: $Date: 2008-10-17 13:35:26 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-05-07 14:03:44 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -77,10 +77,14 @@ ImageFunction<TInputImage, TOutput, TCoordRep> for ( unsigned int j = 0; j < ImageDimension; j++ ) { m_EndIndex[j] = m_StartIndex[j] + static_cast<IndexValueType>( size[j] ) - 1; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + m_StartContinuousIndex[j] = static_cast<CoordRepType>( m_StartIndex[j] - 0.5 ); + m_EndContinuousIndex[j] = static_cast<CoordRepType>( m_EndIndex[j] + 0.5 ); +#else m_StartContinuousIndex[j] = static_cast<CoordRepType>( m_StartIndex[j] ); m_EndContinuousIndex[j] = static_cast<CoordRepType>( m_EndIndex[j] ); +#endif } - } } diff --git a/Utilities/ITK/Code/Common/itkImageRegion.h b/Utilities/ITK/Code/Common/itkImageRegion.h index 3d9147da32..f11932fed0 100644 --- a/Utilities/ITK/Code/Common/itkImageRegion.h +++ b/Utilities/ITK/Code/Common/itkImageRegion.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageRegion.h,v $ Language: C++ - Date: $Date: 2008-10-18 21:13:25 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-05-13 15:27:49 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,6 +25,7 @@ #include "itkIndex.h" #include "itkSize.h" #include "itkContinuousIndex.h" +#include "vnl/vnl_math.h" namespace itk { @@ -176,7 +177,7 @@ public: { return false; } - if( index[i] >= m_Index[i] + static_cast<long>(m_Size[i]) ) + if( index[i] >= (m_Index[i] + static_cast<long>(m_Size[i])) ) { return false; } @@ -184,20 +185,33 @@ public: return true; } - /** Test if an index is inside */ + /** Test if a continuous index is inside the region. + * If ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY is on, + * we take into account the fact that each voxel has its + * center at the integer coordinate and extends half way + * to the next integer coordinate. */ template <typename TCoordRepType> bool IsInside(const ContinuousIndex<TCoordRepType,VImageDimension> &index) const { for(unsigned int i=0; i<ImageDimension; i++) { +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + if( itk::Math::RoundHalfIntegerUp(index[i]) < static_cast<int>( m_Index[i] ) ) +#else if( index[i] < static_cast<TCoordRepType>( m_Index[i] ) ) +#endif { return false; } // bound is the last valid pixel location +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + const TCoordRepType bound = static_cast<TCoordRepType>( + m_Index[i] + m_Size[i] - 0.5); +#else const TCoordRepType bound = static_cast<TCoordRepType>( - m_Index[i] + static_cast<long>(m_Size[i]) - 1); + m_Index[i] + static_cast<long>(m_Size[i]) - 1); +#endif if( index[i] > bound ) { @@ -207,8 +221,7 @@ public: return true; } - - /** Test if a region (the argument) is completly inside of this region */ + /** Test if a region (the argument) is completely inside of this region */ bool IsInside(const Self ®ion) const { diff --git a/Utilities/ITK/Code/Common/itkImageRegionMultidimensionalSplitter.txx b/Utilities/ITK/Code/Common/itkImageRegionMultidimensionalSplitter.txx index 61e95170b5..87effec8aa 100644 --- a/Utilities/ITK/Code/Common/itkImageRegionMultidimensionalSplitter.txx +++ b/Utilities/ITK/Code/Common/itkImageRegionMultidimensionalSplitter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageRegionMultidimensionalSplitter.txx,v $ Language: C++ - Date: $Date: 2008-10-18 21:13:25 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-06 13:46:38 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,7 +34,7 @@ ImageRegionMultidimensionalSplitter<VImageDimension> // requested number of splits per dimension double splitsPerDimension = - ::ceil( vcl_pow((double) requestedNumber, 1.0/(double) VImageDimension)); + vcl_ceil( vcl_pow((double) requestedNumber, 1.0/(double) VImageDimension)); // if a given dimension has fewer pixels that splitsPerDimension, then // only split number of pixels times @@ -78,7 +78,7 @@ ImageRegionMultidimensionalSplitter<VImageDimension> // requested number of splits per dimension double splitsPerDimension = - ::ceil( vcl_pow((double) numberOfPieces, 1.0/(double) VImageDimension)); + vcl_ceil( vcl_pow((double) numberOfPieces, 1.0/(double) VImageDimension)); // if a given dimension has fewer pixels that splitsPerDimension, then // only split number of pixels times @@ -99,7 +99,7 @@ ImageRegionMultidimensionalSplitter<VImageDimension> else { splits[j] = (unsigned int) splitsPerDimension; - pixelsPerSplit[j] = (unsigned int) ::ceil(regionSize[j] + pixelsPerSplit[j] = (unsigned int) vcl_ceil(regionSize[j] / (double) splits[j]); numPieces *= (unsigned int) splitsPerDimension; } diff --git a/Utilities/ITK/Code/Common/itkImageRegionSplitter.txx b/Utilities/ITK/Code/Common/itkImageRegionSplitter.txx index b4dfa1f115..3014d623b8 100644 --- a/Utilities/ITK/Code/Common/itkImageRegionSplitter.txx +++ b/Utilities/ITK/Code/Common/itkImageRegionSplitter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageRegionSplitter.txx,v $ Language: C++ - Date: $Date: 2008-10-18 21:13:25 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-06 13:46:38 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,8 +48,8 @@ ImageRegionSplitter<VImageDimension> // determine the actual number of pieces that will be generated SizeValueType range = regionSize[splitAxis]; - int valuesPerPiece = (int)::ceil(range/(double)requestedNumber); - int maxPieceUsed = (int)::ceil(range/(double)valuesPerPiece) - 1; + int valuesPerPiece = (int)vcl_ceil(range/(double)requestedNumber); + int maxPieceUsed = (int)vcl_ceil(range/(double)valuesPerPiece) - 1; return maxPieceUsed + 1; } @@ -90,8 +90,8 @@ ImageRegionSplitter<VImageDimension> // determine the actual number of pieces that will be generated SizeValueType range = regionSize[splitAxis]; - int valuesPerPiece = (int)::ceil(range/(double)numberOfPieces); - int maxPieceUsed = (int)::ceil(range/(double)valuesPerPiece) - 1; + int valuesPerPiece = (int)vcl_ceil(range/(double)numberOfPieces); + int maxPieceUsed = (int)vcl_ceil(range/(double)valuesPerPiece) - 1; // Split the region if ((int) i < maxPieceUsed) diff --git a/Utilities/ITK/Code/Common/itkImageSliceIteratorWithIndex.h b/Utilities/ITK/Code/Common/itkImageSliceIteratorWithIndex.h index d3ac44696e..e13a2c7dc2 100644 --- a/Utilities/ITK/Code/Common/itkImageSliceIteratorWithIndex.h +++ b/Utilities/ITK/Code/Common/itkImageSliceIteratorWithIndex.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSliceIteratorWithIndex.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-05-19 13:47:44 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -105,7 +105,7 @@ public: /** Set the pixel value */ void Set( const PixelType & value) const - { this->m_PixelAccessor.Set(*(const_cast<InternalPixelType *>(this->m_Position)),value); } + { this->m_PixelAccessorFunctor.Set(*(const_cast<InternalPixelType *>(this->m_Position)),value); } /** Return a reference to the pixel * This method will provide the fastest access to pixel diff --git a/Utilities/ITK/Code/Common/itkImageSource.h b/Utilities/ITK/Code/Common/itkImageSource.h index 39f2eea401..e23881d698 100644 --- a/Utilities/ITK/Code/Common/itkImageSource.h +++ b/Utilities/ITK/Code/Common/itkImageSource.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSource.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.56 $ + Date: $Date: 2009-03-12 01:11:08 $ + Version: $Revision: 1.59 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -70,6 +70,10 @@ public: typedef typename OutputImageType::RegionType OutputImageRegionType; typedef typename OutputImageType::PixelType OutputImagePixelType; + /** ImageDimension constant */ + itkStaticConstMacro(OutputImageDimension, unsigned int, + TOutputImage::ImageDimension); + /** Get the output data of this process object. The output of this * function is not valid until an appropriate Update() method has * been called, either explicitly or implicitly. Both the filter @@ -109,6 +113,13 @@ public: * For an image, the data generated is for the requested * Region, which can be set using ImageBase::SetRequestedRegion(). * By default, the largest possible region is requested. + * + * For Filters which have multiple outputs of different types, the + * GetOutput() method assumes the output is of OutputImageType. For + * the GetOutput(unsigned int) method, a dynamic_cast is performed + * incase the filter has outputs of different types or image + * types. Derived classes should have names get methods for these + * outputs. */ OutputImageType * GetOutput(void); OutputImageType * GetOutput(unsigned int idx); diff --git a/Utilities/ITK/Code/Common/itkImageSource.txx b/Utilities/ITK/Code/Common/itkImageSource.txx index 0bcbe5f144..fe588b56b7 100644 --- a/Utilities/ITK/Code/Common/itkImageSource.txx +++ b/Utilities/ITK/Code/Common/itkImageSource.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSource.txx,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.63 $ + Date: $Date: 2009-04-05 10:56:39 $ + Version: $Revision: 1.67 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -69,7 +69,8 @@ ImageSource<TOutputImage> { return 0; } - + + // we assume that the first output is of the templated type return static_cast<TOutputImage*> (this->ProcessObject::GetOutput(0)); } @@ -83,7 +84,7 @@ typename ImageSource<TOutputImage>::OutputImageType * ImageSource<TOutputImage> ::GetOutput(unsigned int idx) { - return static_cast<TOutputImage*> + return dynamic_cast<TOutputImage*> (this->ProcessObject::GetOutput(idx)); } @@ -118,7 +119,9 @@ ImageSource<TOutputImage> itkExceptionMacro(<<"Requested to graft output that is a NULL pointer" ); } - DataObject * output = this->GetOutput(idx); + // we use the process object method since all out output may not be + // of the same type + DataObject * output = this->ProcessObject::GetOutput(idx); // Call GraftImage to copy meta-information, regions, and the pixel container output->Graft( graft ); @@ -158,8 +161,8 @@ ImageSource<TOutputImage> // determine the actual number of pieces that will be generated typename TOutputImage::SizeType::SizeValueType range = requestedRegionSize[splitAxis]; - int valuesPerThread = (int)::ceil(range/(double)num); - int maxThreadIdUsed = (int)::ceil(range/(double)valuesPerThread) - 1; + int valuesPerThread = (int)::vcl_ceil(range/(double)num); + int maxThreadIdUsed = (int)::vcl_ceil(range/(double)valuesPerThread) - 1; // Split the region if (i < maxThreadIdUsed) @@ -188,15 +191,26 @@ template <class TOutputImage> void ImageSource<TOutputImage> ::AllocateOutputs() -{ - OutputImagePointer outputPtr; +{ + typedef ImageBase<OutputImageDimension> ImageBaseType; + typename ImageBaseType::Pointer outputPtr; // Allocate the output memory for (unsigned int i=0; i < this->GetNumberOfOutputs(); i++) { - outputPtr = this->GetOutput(i); - outputPtr->SetBufferedRegion(outputPtr->GetRequestedRegion()); - outputPtr->Allocate(); + + // Check whether the output is an image of the appropriate + // dimension (use ProcessObject's version of the GetInput() + // method since it returns the input as a pointer to a + // DataObject as opposed to the subclass version which + // static_casts the input to an TInputImage). + outputPtr = dynamic_cast< ImageBaseType *>( this->ProcessObject::GetOutput(i) ); + + if ( outputPtr ) + { + outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() ); + outputPtr->Allocate(); + } } } diff --git a/Utilities/ITK/Code/Common/itkImageTransformHelper.h b/Utilities/ITK/Code/Common/itkImageTransformHelper.h index b0dfd75dcb..83900db2ea 100644 --- a/Utilities/ITK/Code/Common/itkImageTransformHelper.h +++ b/Utilities/ITK/Code/Common/itkImageTransformHelper.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageTransformHelper.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-05-07 14:03:45 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,6 +20,7 @@ #include "itkConceptChecking.h" #include "itkPoint.h" #include "itkMatrix.h" +#include "vnl/vnl_math.h" namespace itk { @@ -173,7 +174,11 @@ public: const DoublePoint &, DoublePoint &rindex, IndexType &index, const UniqueTypeBoolTrue& ) { - index[R] = static_cast<typename IndexType::IndexValueType>(rindex[R]); +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + index[R] = static_cast<typename IndexType::IndexValueType>( itk::Math::RoundHalfIntegerUp( rindex[R] ) ); +#else + index[R] = static_cast<typename IndexType::IndexValueType>(rindex[R]); +#endif } // @@ -308,7 +313,12 @@ public: const FloatPoint &, FloatPoint &rindex, IndexType &index, const UniqueTypeBoolTrue& ) { +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + index[R] = static_cast<typename IndexType::IndexValueType>( + itk::Math::RoundHalfIntegerUp(rindex[R]) ); +#else index[R] = static_cast<typename IndexType::IndexValueType>(rindex[R]); +#endif } }; diff --git a/Utilities/ITK/Code/Common/itkImportImageContainer.h b/Utilities/ITK/Code/Common/itkImportImageContainer.h index 8948ff2d33..4ca868cbc5 100644 --- a/Utilities/ITK/Code/Common/itkImportImageContainer.h +++ b/Utilities/ITK/Code/Common/itkImportImageContainer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImportImageContainer.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-25 12:24:09 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -101,6 +101,10 @@ public: * was passed in using "LetContainerManageMemory"=true. The new buffer's * memory management will be handled by the container from that point on. * + * In general, Reserve should not change the usable elements of the + * container. However, in this particular case, Reserve as a Resize + * semantics that is kept for backward compatibility reasons. + * * \sa SetImportPointer() */ void Reserve(ElementIdentifier num); @@ -126,7 +130,7 @@ public: * flag. This may override your setting if you call this methods prematurely. * \warning Improper use of these methods will result in memory leaks */ itkSetMacro(ContainerManageMemory,bool); - itkGetMacro(ContainerManageMemory,bool); + itkGetConstMacro(ContainerManageMemory,bool); itkBooleanMacro(ContainerManageMemory); @@ -140,6 +144,31 @@ protected: void PrintSelf(std::ostream& os, Indent indent) const; virtual TElement* AllocateElements(ElementIdentifier size) const; + virtual void DeallocateManagedMemory(); + + /* Set the m_Size member that represents the number of elements + * currently stored in the container. Use this function with great + * care since it only changes the m_Size member and not the actual size + * of the import pointer m_ImportPointer. It should typically + * be used only to override AllocateElements and + * DeallocateManagedMemory. */ + itkSetMacro(Size,TElementIdentifier); + + /* Set the m_Capacity member that represents the capacity of + * the current container. Use this function with great care + * since it only changes the m_Capacity member and not the actual + * capacity of the import pointer m_ImportPointer. It should typically + * be used only to override AllocateElements and + * DeallocateManagedMemory. */ + itkSetMacro(Capacity,TElementIdentifier); + + + /* Set the m_ImportPointer member. Use this function with great care + * since it only changes the m_ImportPointer member but not the m_Size + * and m_Capacity members. It should typically be used only to override + * AllocateElements and DeallocateManagedMemory. */ + void SetImportPointer(TElement *ptr){m_ImportPointer=ptr;} + private: ImportImageContainer(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented @@ -148,7 +177,6 @@ private: TElementIdentifier m_Size; TElementIdentifier m_Capacity; bool m_ContainerManageMemory; - }; } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkImportImageContainer.txx b/Utilities/ITK/Code/Common/itkImportImageContainer.txx index ebf580402e..78e91cfcde 100644 --- a/Utilities/ITK/Code/Common/itkImportImageContainer.txx +++ b/Utilities/ITK/Code/Common/itkImportImageContainer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImportImageContainer.txx,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-05 19:10:47 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,6 +22,8 @@ #include "itkImportImageContainer.h" #include <cstring> +#include <stdlib.h> +#include <string.h> namespace itk { @@ -36,15 +38,12 @@ ImportImageContainer<TElementIdentifier , TElement> m_Size = 0; } - + template <typename TElementIdentifier, typename TElement> ImportImageContainer< TElementIdentifier , TElement > ::~ImportImageContainer() { - if (m_ImportPointer && m_ContainerManageMemory) - { - delete [] m_ImportPointer; - } + DeallocateManagedMemory(); } @@ -57,6 +56,9 @@ void ImportImageContainer< TElementIdentifier , TElement > ::Reserve(ElementIdentifier size) { + // Reserve has a Resize semantics. We keep it that way for + // backwards compatibility . + // See http://www.itk.org/Bug/view.php?id=2893 for details if (m_ImportPointer) { if (size > m_Capacity) @@ -64,10 +66,9 @@ ImportImageContainer< TElementIdentifier , TElement > TElement* temp = this->AllocateElements(size); // only copy the portion of the data used in the old buffer memcpy(temp, m_ImportPointer, m_Size*sizeof(TElement)); - if (m_ImportPointer && m_ContainerManageMemory) - { - delete [] m_ImportPointer; - } + + DeallocateManagedMemory(); + m_ImportPointer = temp; m_ContainerManageMemory = true; m_Capacity = size; @@ -104,15 +105,16 @@ ImportImageContainer< TElementIdentifier , TElement > { if (m_Size < m_Capacity) { - TElement* temp = this->AllocateElements(m_Size); - memcpy(temp, m_ImportPointer, m_Size*sizeof(TElement)); - if (m_ContainerManageMemory) - { - delete [] m_ImportPointer; - } + const TElementIdentifier size = m_Size; + TElement* temp = this->AllocateElements(size); + memcpy(temp, m_ImportPointer, size*sizeof(TElement)); + + DeallocateManagedMemory(); + m_ImportPointer = temp; m_ContainerManageMemory = true; - m_Capacity = m_Size; + m_Capacity = size; + m_Size = size; this->Modified(); } @@ -131,14 +133,9 @@ ImportImageContainer< TElementIdentifier , TElement > { if (m_ImportPointer) { - if (m_ContainerManageMemory) - { - delete [] m_ImportPointer; - } - m_ImportPointer = 0; + DeallocateManagedMemory(); + m_ContainerManageMemory = true; - m_Capacity = 0; - m_Size = 0; this->Modified(); } @@ -159,10 +156,7 @@ ImportImageContainer< TElementIdentifier , TElement > ::SetImportPointer(TElement *ptr, TElementIdentifier num, bool LetContainerManageMemory) { - if (m_ImportPointer && m_ContainerManageMemory) - { - delete [] m_ImportPointer; - } + DeallocateManagedMemory(); m_ImportPointer = ptr; m_ContainerManageMemory = LetContainerManageMemory; m_Capacity = num; @@ -198,6 +192,20 @@ TElement* ImportImageContainer< TElementIdentifier , TElement > return data; } +template <typename TElementIdentifier, typename TElement> +void ImportImageContainer< TElementIdentifier , TElement > +::DeallocateManagedMemory() +{ + // Encapsulate all image memory deallocation here + if (m_ImportPointer && m_ContainerManageMemory) + { + delete [] m_ImportPointer; + } + m_ImportPointer = 0; + m_Capacity = 0; + m_Size = 0; +} + template <typename TElementIdentifier, typename TElement> void ImportImageContainer< TElementIdentifier , TElement > diff --git a/Utilities/ITK/Code/Common/itkInPlaceImageFilter.h b/Utilities/ITK/Code/Common/itkInPlaceImageFilter.h index 5b024d4325..c6da62a90d 100644 --- a/Utilities/ITK/Code/Common/itkInPlaceImageFilter.h +++ b/Utilities/ITK/Code/Common/itkInPlaceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkInPlaceImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-05-04 14:42:59 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -91,10 +91,13 @@ public: itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); - /** In place operation can be turned on and off. This only has an - * effect when the input and output image type match. */ + /** In place operation can be turned on and off. Asking for + * in-place operation, i.e. calling SetInplace(true) or InplaceOn(), + * will be effective only if CanRunInPlace also returns true. + * By default CanRunInPlace checks whether the input and output + * image type match. */ itkSetMacro(InPlace, bool); - itkGetMacro(InPlace, bool); + itkGetConstMacro(InPlace, bool); itkBooleanMacro(InPlace); /** Can the filter run in place? To do so, the filter's first input @@ -102,8 +105,10 @@ public: * method can be used in conjunction with the InPlace ivar to * determine whether a particular use of the filter is really * running in place. Some filters may be able to optimize their - * operation if the InPlace is true and CanRunInPlace is true. */ - bool CanRunInPlace() const + * operation if the InPlace is true and CanRunInPlace is true. + * CanRunInPlace may also be overridded by InPlaceImageFilter + * subclasses to fine tune its behavior. */ + virtual bool CanRunInPlace() const { return (typeid(TInputImage) == typeid(TOutputImage)); } diff --git a/Utilities/ITK/Code/Common/itkInPlaceImageFilter.txx b/Utilities/ITK/Code/Common/itkInPlaceImageFilter.txx index f93b115680..6f1e28d4a5 100644 --- a/Utilities/ITK/Code/Common/itkInPlaceImageFilter.txx +++ b/Utilities/ITK/Code/Common/itkInPlaceImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkInPlaceImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-05-04 14:43:01 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -69,7 +69,7 @@ InPlaceImageFilter<TInputImage, TOutputImage> ::AllocateOutputs() { // if told to run in place and the types support it, - if (m_InPlace && (typeid(TInputImage) == typeid(TOutputImage))) + if (this->GetInPlace() && this->CanRunInPlace()) { // Graft this first input to the output. Later, we'll need to // remove the input's hold on the bulk data. @@ -113,7 +113,7 @@ InPlaceImageFilter<TInputImage, TOutputImage> ::ReleaseInputs() { // if told to run in place and the types support it, - if (m_InPlace && (typeid(TInputImage) == typeid(TOutputImage))) + if (this->GetInPlace() && this->CanRunInPlace()) { // Release any input where the ReleaseData flag has been set ProcessObject::ReleaseInputs(); diff --git a/Utilities/ITK/Code/Common/itkIndex.h b/Utilities/ITK/Code/Common/itkIndex.h index 927d452c12..343279692d 100644 --- a/Utilities/ITK/Code/Common/itkIndex.h +++ b/Utilities/ITK/Code/Common/itkIndex.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIndex.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:58 $ - Version: $Revision: 1.59 $ + Date: $Date: 2009-05-17 02:31:26 $ + Version: $Revision: 1.62 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -260,6 +260,7 @@ public: * Index<3> index = {5, 2, 7}; */ IndexValueType m_Index[VIndexDimension]; +#ifndef ITK_USE_PORTABLE_ROUND // The Windows implementaton of vnl_math_rnd() does not round the // same way as other versions. It has an assembly "fast" implementation // but with the drawback of rounding to the closest even number. @@ -270,23 +271,30 @@ public: // produce consistent results. This can be removed once vnl_math_rnd is // fixed in VXL. #if (defined (VCL_VC) && !defined(__GCCXML__)) || (defined(_MSC_VER) && (_MSC_VER <= 1310)) -#define vnl_math_rnd(x) ((x>=0.0)?(int)(x + 0.5):(int)(x - 0.5)) +#define vnl_math_rnd_halfintup(x) ((x>=0.0)?(int)(x + 0.5):(int)(x - 0.5)) +#endif #endif /** Copy values from a FixedArray by rounding each one of the components */ template <class TCoordRep> inline void CopyWithRound( const FixedArray<TCoordRep,VIndexDimension> & point ) { #ifdef ITK_USE_TEMPLATE_META_PROGRAMMING_LOOP_UNROLLING - itkFoorLoopRoundingAndAssignmentMacro(IndexType,ContinuousIndexType,IndexValueType,m_Index,point,VIndexDimension); + itkForLoopRoundingAndAssignmentMacro(IndexType,ContinuousIndexType,IndexValueType,m_Index,point,VIndexDimension); #else for(unsigned int i=0;i < VIndexDimension; ++i) { - m_Index[i] = static_cast< IndexValueType>( vnl_math_rnd( point[i] ) ); +#ifdef ITK_USE_PORTABLE_ROUND + m_Index[i] = static_cast< IndexValueType>( itk::Math::Round( point[i] ) ); +#else + m_Index[i] = static_cast< IndexValueType>( vnl_math_rnd_halfintup( point[i] ) ); +#endif } #endif } +#ifndef ITK_USE_PORTABLE_ROUND #if (defined (VCL_VC) && !defined(__GCCXML__)) || (defined(_MSC_VER) && (_MSC_VER <= 1310)) -#undef vnl_math_rnd +#undef vnl_math_rnd_halfintup +#endif #endif /** Copy values from a FixedArray by casting each one of the components */ diff --git a/Utilities/ITK/Code/Common/itkKernelTransform.h b/Utilities/ITK/Code/Common/itkKernelTransform.h index 9fea1fec2f..483fbca015 100644 --- a/Utilities/ITK/Code/Common/itkKernelTransform.h +++ b/Utilities/ITK/Code/Common/itkKernelTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKernelTransform.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:58 $ - Version: $Revision: 1.47 $ + Date: $Date: 2009-05-17 14:27:01 $ + Version: $Revision: 1.49 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -99,16 +99,17 @@ public: /** PointList typedef. This type is used for maintaining lists of points, * specifically, the source and target landmark lists. */ - typedef DefaultStaticMeshTraits<TScalarType, - NDimensions, - NDimensions, - TScalarType, - TScalarType> PointSetTraitsType; - typedef PointSet<InputPointType, NDimensions, PointSetTraitsType> PointSetType; - typedef typename PointSetType::Pointer PointSetPointer; - typedef typename PointSetType::PointsContainer PointsContainer; - typedef typename PointSetType::PointsContainerIterator PointsIterator; - typedef typename PointSetType::PointsContainerConstIterator PointsConstIterator; + typedef DefaultStaticMeshTraits<TScalarType, NDimensions, + NDimensions, TScalarType, + TScalarType> PointSetTraitsType; + typedef PointSet<InputPointType, NDimensions, PointSetTraitsType> + PointSetType; + typedef typename PointSetType::Pointer PointSetPointer; + typedef typename PointSetType::PointsContainer PointsContainer; + typedef typename PointSetType::PointsContainerIterator + PointsIterator; + typedef typename PointSetType::PointsContainerConstIterator + PointsConstIterator; /** VectorSet typedef. */ typedef itk::VectorContainer<unsigned long,InputVectorType> VectorSetType; @@ -143,10 +144,10 @@ public: /** Compute the Jacobian Matrix of the transformation at one point */ virtual const JacobianType & GetJacobian(const InputPointType &point) const; - /** Set the Transformation Parameters and update the internal transformation. - * The parameters represent the source landmarks. Each landmark point is represented - * by NDimensions doubles. All the landmarks are concatenated to form one flat - * Array<double>. */ + /** Set the Transformation Parameters and update the internal transformation. + * The parameters represent the source landmarks. Each landmark point is + * represented by NDimensions doubles. All the landmarks are concatenated to + * form one flat Array<double>. */ virtual void SetParameters(const ParametersType &); /** Set Transform Fixed Parameters: @@ -181,7 +182,7 @@ public: * Biology Society. 1996. */ itkSetClampMacro(Stiffness, double, 0.0, NumericTraits<double>::max()); - itkGetMacro(Stiffness, double); + itkGetConstMacro(Stiffness, double); protected: @@ -231,11 +232,14 @@ protected: * Elastic body spline * Thin plate spline * Volume spline */ - virtual void ComputeG(const InputVectorType& landmarkVector, GMatrixType & gmatrix ) const; + virtual void ComputeG(const InputVectorType& landmarkVector, + GMatrixType & gmatrix ) const; /** * \deprecated in ITK 3.6, please use void ComputeG(vector,gmatrix) instead. */ - itkLegacyMacro( virtual const GMatrixType & ComputeG(const InputVectorType& landmarkVector) const ); + itkLegacyMacro( virtual const GMatrixType & ComputeG( + const InputVectorType & landmarkVector + ) const ); /** Compute a G(x) for a point to itself (i.e. for the block diagonal @@ -252,8 +256,9 @@ protected: /** Compute the contribution of the landmarks weighted by the kernel funcion to the global deformation of the space */ - virtual void ComputeDeformationContribution( const InputPointType & inputPoint, - OutputPointType & result ) const; + virtual void ComputeDeformationContribution( + const InputPointType & inputPoint, + OutputPointType & result ) const; /** Compute K matrix. */ void ComputeK(); diff --git a/Utilities/ITK/Code/Common/itkKernelTransform.txx b/Utilities/ITK/Code/Common/itkKernelTransform.txx index 57a2ab4896..6c4569a30a 100644 --- a/Utilities/ITK/Code/Common/itkKernelTransform.txx +++ b/Utilities/ITK/Code/Common/itkKernelTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKernelTransform.txx,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:58 $ - Version: $Revision: 1.48 $ + Date: $Date: 2009-05-17 14:27:02 $ + Version: $Revision: 1.49 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -94,7 +94,7 @@ SetTargetLandmarks(PointSetType * landmarks) /** * This method has been deprecated as of ITK 3.6. - * Please use the method: void ComputeG(vector,gmatrix) instead. + * Please use the method: void ComputeG( vector, gmatrix ) instead. */ #if !defined(ITK_LEGACY_REMOVE) template <class TScalarType, unsigned int NDimensions> @@ -102,7 +102,8 @@ const typename KernelTransform<TScalarType, NDimensions>::GMatrixType & KernelTransform<TScalarType, NDimensions>:: ComputeG( const InputVectorType & ) const { - itkLegacyReplaceBodyMacro(itkKernelTransform::ComputeG_vector, 3.6,itkKernelTransform::ComputeG_vector_gmatrix); + itkLegacyReplaceBodyMacro( itkKernelTransform::ComputeG_vector, 3.6, + itkKernelTransform::ComputeG_vector_gmatrix ); return m_GMatrix; } #endif @@ -115,7 +116,8 @@ void KernelTransform<TScalarType, NDimensions>:: ComputeG( const InputVectorType &, GMatrixType & itkNotUsed( gmatrix ) ) const { - itkExceptionMacro(<< "ComputeG(vector,gmatrix) must be reimplemented in subclasses of KernelTransform."); + itkExceptionMacro( << "ComputeG(vector,gmatrix) must be reimplemented" + << " in subclasses of KernelTransform." ); } /** @@ -144,7 +146,8 @@ ComputeDeformationContribution( const InputPointType & thisPoint, OutputPointType & result ) const { - unsigned long numberOfLandmarks = this->m_SourceLandmarks->GetNumberOfPoints(); + unsigned long numberOfLandmarks = this->m_SourceLandmarks + ->GetNumberOfPoints(); PointsIterator sp = this->m_SourceLandmarks->GetPoints()->Begin(); @@ -173,7 +176,8 @@ template <class TScalarType, unsigned int NDimensions> void KernelTransform<TScalarType, NDimensions> ::ComputeD(void) { - unsigned long numberOfLandmarks = this->m_SourceLandmarks->GetNumberOfPoints(); + unsigned long numberOfLandmarks = this->m_SourceLandmarks + ->GetNumberOfPoints(); PointsIterator sp = this->m_SourceLandmarks->GetPoints()->Begin(); PointsIterator tp = this->m_TargetLandmarks->GetPoints()->Begin(); @@ -217,7 +221,8 @@ template <class TScalarType, unsigned int NDimensions> void KernelTransform<TScalarType, NDimensions>:: ComputeL(void) { - unsigned long numberOfLandmarks = this->m_SourceLandmarks->GetNumberOfPoints(); + unsigned long numberOfLandmarks = this->m_SourceLandmarks + ->GetNumberOfPoints(); vnl_matrix<TScalarType> O2(NDimensions*(NDimensions+1), NDimensions*(NDimensions+1), 0); @@ -232,8 +237,10 @@ ComputeL(void) this->m_LMatrix.update( this->m_KMatrix, 0, 0 ); this->m_LMatrix.update( this->m_PMatrix, 0, this->m_KMatrix.columns() ); - this->m_LMatrix.update( this->m_PMatrix.transpose(), this->m_KMatrix.rows(), 0); - this->m_LMatrix.update( O2, this->m_KMatrix.rows(), this->m_KMatrix.columns()); + this->m_LMatrix.update( this->m_PMatrix.transpose(), + this->m_KMatrix.rows(), 0); + this->m_LMatrix.update( O2, this->m_KMatrix.rows(), + this->m_KMatrix.columns()); } @@ -245,7 +252,8 @@ template <class TScalarType, unsigned int NDimensions> void KernelTransform<TScalarType, NDimensions>:: ComputeK(void) { - unsigned long numberOfLandmarks = this->m_SourceLandmarks->GetNumberOfPoints(); + unsigned long numberOfLandmarks = this->m_SourceLandmarks + ->GetNumberOfPoints(); GMatrixType G; this->ComputeD(); @@ -276,7 +284,7 @@ ComputeK(void) while( p2 != end ) { const InputVectorType s = p1.Value() - p2.Value(); - this->ComputeG(s,G); + this->ComputeG(s, G); // write value in upper and lower triangle of matrix this->m_KMatrix.update(G, i*NDimensions, j*NDimensions); this->m_KMatrix.update(G, j*NDimensions, i*NDimensions); @@ -295,7 +303,8 @@ template <class TScalarType, unsigned int NDimensions> void KernelTransform<TScalarType, NDimensions>:: ComputeP() { - unsigned long numberOfLandmarks = this->m_SourceLandmarks->GetNumberOfPoints(); + unsigned long numberOfLandmarks = this->m_SourceLandmarks + ->GetNumberOfPoints(); IMatrixType I; IMatrixType temp; InputPointType p; @@ -323,7 +332,8 @@ template <class TScalarType, unsigned int NDimensions> void KernelTransform<TScalarType, NDimensions>:: ComputeY(void) { - unsigned long numberOfLandmarks = this->m_SourceLandmarks->GetNumberOfPoints(); + unsigned long numberOfLandmarks = this->m_SourceLandmarks + ->GetNumberOfPoints(); typename VectorSetType::ConstIterator displacement = this->m_Displacements->Begin(); @@ -356,7 +366,8 @@ void KernelTransform<TScalarType, NDimensions> ::ReorganizeW(void) { - unsigned long numberOfLandmarks = this->m_SourceLandmarks->GetNumberOfPoints(); + unsigned long numberOfLandmarks = this->m_SourceLandmarks + ->GetNumberOfPoints(); // The deformable (non-affine) part of the registration goes here this->m_DMatrix.set_size(NDimensions,numberOfLandmarks); @@ -440,7 +451,8 @@ GetJacobian( const InputPointType & ) const // FIXME: TODO // The Jacobian should be computable in terms of the matrices // used to Transform points... - itkExceptionMacro(<< "GetJacobian must be implemented in subclasses of KernelTransform."); + itkExceptionMacro(<< "GetJacobian must be implemented in subclasses" + << " of KernelTransform."); return this->m_Jacobian; @@ -530,7 +542,9 @@ void KernelTransform<TScalarType, NDimensions>:: UpdateParameters( void ) const { - this->m_Parameters = ParametersType( this->m_SourceLandmarks->GetNumberOfPoints() * NDimensions ); + this->m_Parameters = ParametersType( this->m_SourceLandmarks + ->GetNumberOfPoints() + * NDimensions ); PointsIterator itr = this->m_SourceLandmarks->GetPoints()->Begin(); PointsIterator end = this->m_SourceLandmarks->GetPoints()->End(); @@ -569,7 +583,9 @@ const typename KernelTransform<TScalarType, NDimensions>::ParametersType & KernelTransform<TScalarType, NDimensions>:: GetFixedParameters( void ) const { - this->m_FixedParameters = ParametersType( this->m_TargetLandmarks->GetNumberOfPoints() * NDimensions ); + this->m_FixedParameters = ParametersType( this->m_TargetLandmarks + ->GetNumberOfPoints() + * NDimensions ); PointsIterator itr = this->m_TargetLandmarks->GetPoints()->Begin(); PointsIterator end = this->m_TargetLandmarks->GetPoints()->End(); diff --git a/Utilities/ITK/Code/Common/itkLandmarkBasedTransformInitializer.txx b/Utilities/ITK/Code/Common/itkLandmarkBasedTransformInitializer.txx index b2c8d9b814..97d7fd0123 100644 --- a/Utilities/ITK/Code/Common/itkLandmarkBasedTransformInitializer.txx +++ b/Utilities/ITK/Code/Common/itkLandmarkBasedTransformInitializer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLandmarkBasedTransformInitializer.txx,v $ Language: C++ - Date: $Date: 2009-02-05 19:05:00 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-05 18:12:09 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -54,7 +54,7 @@ LandmarkBasedTransformInitializer<TTransform, TFixedImage, TMovingImage > return; } - const double PI = 4.0 * atan(1.0); + const double PI = 4.0 * vcl_atan(1.0); // We will do an explicit typeid check here (via dynamic_cast) to check // the transform type. The initialization scheme will generally be different diff --git a/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.h b/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.h index 6351ad27f0..432c9b39c9 100644 --- a/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLinearInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:05:01 $ - Version: $Revision: 1.35 $ + Date: $Date: 2009-03-20 10:25:36 $ + Version: $Revision: 1.36 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -71,6 +71,9 @@ public: /** InputImageType typedef support. */ typedef typename Superclass::InputImageType InputImageType; + /** InputPixelType typedef support. */ + typedef typename Superclass::InputPixelType InputPixelType; + /** RealType typedef support. */ typedef typename Superclass::RealType RealType; diff --git a/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.txx b/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.txx index 206a3a4465..62ced264fc 100644 --- a/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLinearInterpolateImageFunction.txx,v $ Language: C++ - Date: $Date: 2008-01-06 23:12:49 $ - Version: $Revision: 1.37 $ + Date: $Date: 2009-05-07 14:03:45 $ + Version: $Revision: 1.42 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -114,7 +114,9 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > * of the neighbor pixel with respect to a pixel centered on point. */ RealType value = NumericTraits<RealType>::Zero; - RealType totalOverlap = NumericTraits<RealType>::Zero; + + typedef typename NumericTraits<InputPixelType>::ScalarRealType ScalarRealType; + ScalarRealType totalOverlap = NumericTraits<ScalarRealType>::Zero; for( unsigned int counter = 0; counter < m_Neighbors; counter++ ) { @@ -130,11 +132,27 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > if ( upper & 1 ) { neighIndex[dim] = baseIndex[dim] + 1; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + // Take care of the case where the pixel is just + // in the outer upper boundary of the image grid. + if( neighIndex[dim] > this->m_EndIndex[dim] ) + { + neighIndex[dim] = this->m_EndIndex[dim]; + } +#endif overlap *= distance[dim]; } else { neighIndex[dim] = baseIndex[dim]; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + // Take care of the case where the pixel is just + // in the outer lower boundary of the image grid. + if( neighIndex[dim] < this->m_StartIndex[dim] ) + { + neighIndex[dim] = this->m_StartIndex[dim]; + } +#endif overlap *= 1.0 - distance[dim]; } @@ -145,7 +163,7 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > // get neighbor value only if overlap is not zero if( overlap ) { - value += overlap * static_cast<RealType>( this->GetInputImage()->GetPixel( neighIndex ) ); + value += static_cast<RealType>( this->GetInputImage()->GetPixel( neighIndex ) ) * overlap; totalOverlap += overlap; } diff --git a/Utilities/ITK/Code/Common/itkLoggerOutput.h b/Utilities/ITK/Code/Common/itkLoggerOutput.h index e4959ec4a3..db5f17f825 100644 --- a/Utilities/ITK/Code/Common/itkLoggerOutput.h +++ b/Utilities/ITK/Code/Common/itkLoggerOutput.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLoggerOutput.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:05:01 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-25 12:24:09 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,7 +81,7 @@ public: itkSetMacro(Logger, LoggerType); - itkGetMacro(Logger, LoggerType); + itkGetConstMacro(Logger, LoggerType); virtual void OverrideITKWindow() { diff --git a/Utilities/ITK/Code/Common/itkMacro.h b/Utilities/ITK/Code/Common/itkMacro.h index 772b2cf82d..28389a8ade 100644 --- a/Utilities/ITK/Code/Common/itkMacro.h +++ b/Utilities/ITK/Code/Common/itkMacro.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMacro.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:05:01 $ - Version: $Revision: 1.89 $ + Date: $Date: 2009-05-26 23:45:03 $ + Version: $Revision: 1.96 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,6 +35,11 @@ #include <string> #include <cstdlib> +#ifndef NDEBUG +#include <cassert> +#endif + +#include "vnl/vnl_math.h" // Determine type of string stream to use. #if !defined(CMAKE_NO_ANSI_STRING_STREAM) @@ -965,6 +970,20 @@ private: #endif +namespace itk +{ +namespace Math +{ +inline int RoundHalfIntegerUp(float x) { return vnl_math_rnd_halfintup(x); } +inline int RoundHalfIntegerUp(double x) { return vnl_math_rnd_halfintup(x); } +inline int RoundHalfIntegerToEven(float x) { return vnl_math_rnd_halfinttoeven(x); } +inline int RoundHalfIntegerToEven(double x) { return vnl_math_rnd_halfinttoeven(x); } +inline int Round(float x) { return RoundHalfIntegerUp(x); } +inline int Round(double x) { return RoundHalfIntegerUp(x); } +} // end namespace Math +} // end namespace itk + + #ifdef ITK_USE_TEMPLATE_META_PROGRAMMING_LOOP_UNROLLING //-------------------------------------------------------------------------------- // Helper macros for Template Meta-Programming techniques of for-loops unrolling @@ -977,7 +996,7 @@ private: // No verification of size is performed. Casting is perfomed as part of the // assignment, by using the DestinationElementType as the casting type. // Source and destination array types must have defined opearator[] in their API. -#define itkFoorLoopAssignmentMacro(DestinationType,SourceType,DestinationElementType,DestinationArray,SourceArray,NumberOfIterations) \ +#define itkForLoopAssignmentMacro(DestinationType,SourceType,DestinationElementType,DestinationArray,SourceArray,NumberOfIterations) \ for(unsigned int i=0;i < NumberOfIterations; ++i) \ { \ DestinationArray[i] = static_cast< DestinationElementType >( SourceArray[i] ); \ @@ -991,14 +1010,42 @@ private: // perfomed as part of the assignment, by using the DestinationElementType as // the casting type. // Source and destination array types must have defined opearator[] in their API. -#define itkFoorLoopRoundingAndAssignmentMacro(DestinationType,SourceType,DestinationElementType,DestinationArray,SourceArray,NumberOfIterations) \ +#ifdef ITK_USE_PORTABLE_ROUND +#define itkForLoopRoundingAndAssignmentMacro(DestinationType,Sourcrnd_halfintup,DestinationElementType,DestinationArray,SourceArray,NumberOfIterations) \ for(unsigned int i=0;i < NumberOfIterations; ++i) \ { \ - DestinationArray[i] = static_cast< DestinationElementType >( vnl_math_rnd( SourceArray[i] ) ); \ + DestinationArray[i] = static_cast< DestinationElementType >( itk::Math::Round( SourceArray[i] ) ); \ } +#else +#define itkForLoopRoundingAndAssignmentMacro(DestinationType,SourceType,DestinationElementType,DestinationArray,SourceArray,NumberOfIterations) \ + for(unsigned int i=0;i < NumberOfIterations; ++i) \ + { \ + DestinationArray[i] = static_cast< DestinationElementType >( itk::Math::RoundHalfIntegerUp( SourceArray[i] ) ); \ + } +#endif #endif // end of Template Meta Programming helper macros +#ifndef NDEBUG + +#ifdef _POSIX_SOURCE +#define itkAssertInDebugOrThrowInReleaseMacro(msg) __assert_fail (msg, __FILE__, __LINE__, __ASSERT_FUNCTION); +#else +#define itkAssertInDebugOrThrowInReleaseMacro(msg) itkGenericExceptionMacro( << msg ); +#endif + +#else +#define itkAssertInDebugOrThrowInReleaseMacro(msg) itkGenericExceptionMacro( << msg); +#endif + +#define itkAssertOrThrowMacro(test, message) \ + if( !(test) ) \ + { \ + ::itk::OStringStream msgstr; \ + msgstr << message; \ + itkAssertInDebugOrThrowInReleaseMacro( msgstr.str().c_str() ); \ + } + #endif //end of itkMacro.h diff --git a/Utilities/ITK/Code/Common/itkMatrixOffsetTransformBase.h b/Utilities/ITK/Code/Common/itkMatrixOffsetTransformBase.h index 75f860c9b6..f018d4e92c 100755 --- a/Utilities/ITK/Code/Common/itkMatrixOffsetTransformBase.h +++ b/Utilities/ITK/Code/Common/itkMatrixOffsetTransformBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMatrixOffsetTransformBase.h,v $ Language: C++ - Date: $Date: 2009-02-05 22:04:02 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -156,6 +156,11 @@ public: typedef OutputVectorType TranslationType; + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; + /** Set the transformation to an Identity * * This sets the matrix to identity and the Offset to null. */ @@ -340,6 +345,8 @@ public: */ bool GetInverse(Self * inverse) const; + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; /** \deprecated Use GetInverse instead. * diff --git a/Utilities/ITK/Code/Common/itkMatrixOffsetTransformBase.txx b/Utilities/ITK/Code/Common/itkMatrixOffsetTransformBase.txx index 600037c666..950b1b20b1 100755 --- a/Utilities/ITK/Code/Common/itkMatrixOffsetTransformBase.txx +++ b/Utilities/ITK/Code/Common/itkMatrixOffsetTransformBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMatrixOffsetTransformBase.txx,v $ Language: C++ - Date: $Date: 2009-02-05 22:04:03 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -291,6 +291,18 @@ MatrixOffsetTransformBase<TScalarType, NInputDimensions, NOutputDimensions> return true; } +// Return an inverse of this transform +template<class TScalarType, unsigned int NInputDimensions, + unsigned int NOutputDimensions> +typename MatrixOffsetTransformBase<TScalarType, NInputDimensions, + NOutputDimensions>::InverseTransformBasePointer +MatrixOffsetTransformBase<TScalarType, NInputDimensions, NOutputDimensions> +::GetInverseTransform() const +{ + Pointer inv = New(); + return GetInverse(inv) ? inv.GetPointer() : NULL; +} + // Get fixed parameters template<class TScalarType, unsigned int NInputDimensions, diff --git a/Utilities/ITK/Code/Common/itkMetaDataObject.h b/Utilities/ITK/Code/Common/itkMetaDataObject.h index bdc961f950..3fb6effb86 100644 --- a/Utilities/ITK/Code/Common/itkMetaDataObject.h +++ b/Utilities/ITK/Code/Common/itkMetaDataObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaDataObject.h,v $ Language: C++ - Date: $Date: 2009-02-17 08:35:34 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-04-05 10:56:41 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ #include "itkCommand.h" #include "itkFastMutexLock.h" -#include <string> +#include <string.h> #include <cstring> namespace itk diff --git a/Utilities/ITK/Code/Common/itkMultiThreader.cxx b/Utilities/ITK/Code/Common/itkMultiThreader.cxx index 2d8d084aa8..b13b53a12c 100644 --- a/Utilities/ITK/Code/Common/itkMultiThreader.cxx +++ b/Utilities/ITK/Code/Common/itkMultiThreader.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiThreader.cxx,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:07 $ - Version: $Revision: 1.46 $ + Date: $Date: 2009-04-05 10:56:44 $ + Version: $Revision: 1.47 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,7 +21,7 @@ #include "itkMultiThreader.h" #include "itkObjectFactory.h" #include "itksys/SystemTools.hxx" -#include <vcl_cstdlib.h> +#include <stdlib.h> #ifndef _WIN32 #include <unistd.h> diff --git a/Utilities/ITK/Code/Common/itkMultiThreader.h b/Utilities/ITK/Code/Common/itkMultiThreader.h index 7a39f50fd2..83296f9f98 100644 --- a/Utilities/ITK/Code/Common/itkMultiThreader.h +++ b/Utilities/ITK/Code/Common/itkMultiThreader.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiThreader.h,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:10 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-04-25 12:24:09 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -152,7 +152,7 @@ public: * [ 1, m_GlobalMaximumNumberOfThreads ], so the caller of this method should * check that the requested number of threads was accepted. */ void SetNumberOfThreads( int numberOfThreads ); - itkGetMacro( NumberOfThreads, int ); + itkGetConstMacro( NumberOfThreads, int ); /** Set/Get the maximum number of threads to use when multithreading. It * will be clamped to the range [ 1, ITK_MAX_THREADS ] because several arrays diff --git a/Utilities/ITK/Code/Common/itkNearestNeighborExtrapolateImageFunction.h b/Utilities/ITK/Code/Common/itkNearestNeighborExtrapolateImageFunction.h index c6ee92b761..c908fba95d 100644 --- a/Utilities/ITK/Code/Common/itkNearestNeighborExtrapolateImageFunction.h +++ b/Utilities/ITK/Code/Common/itkNearestNeighborExtrapolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNearestNeighborExtrapolateImageFunction.h,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:10 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-16 16:05:13 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -92,7 +92,11 @@ public: } else { - nindex[j] = static_cast<ValueType>( vnl_math_rnd( index[j] ) ); +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + nindex[j] = static_cast<ValueType>( itk::Math::RoundHalfIntegerUp( index[j] ) ); +#else + nindex[j] = static_cast<ValueType>( vnl_math_rnd_halfintup( index[j] ) ); +#endif } } return static_cast<OutputType>( this->GetInputImage()->GetPixel( nindex ) ); diff --git a/Utilities/ITK/Code/Common/itkNeighborhood.h b/Utilities/ITK/Code/Common/itkNeighborhood.h index f11c422656..9f4bee0193 100644 --- a/Utilities/ITK/Code/Common/itkNeighborhood.h +++ b/Utilities/ITK/Code/Common/itkNeighborhood.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNeighborhood.h,v $ Language: C++ - Date: $Date: 2009-02-07 23:09:24 $ - Version: $Revision: 1.46 $ + Date: $Date: 2009-04-05 10:56:46 $ + Version: $Revision: 1.48 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,6 +25,8 @@ #include "vnl/vnl_vector.h" #include "itkOffset.h" #include <vector> +#include <stdlib.h> +#include <string.h> namespace itk { @@ -86,7 +88,15 @@ public: typedef SliceIterator<TPixel, Self> SliceIteratorType; /** Default constructor. */ - Neighborhood() { m_Radius.Fill(0); m_Size.Fill(0); } + Neighborhood() + { + m_Radius.Fill(0); + m_Size.Fill(0); + for (unsigned int i = 0; i < VDimension; i++) + { + m_StrideTable[i] = 0; + } + } /** Default destructor. */ virtual ~Neighborhood() {} diff --git a/Utilities/ITK/Code/Common/itkNeighborhoodAccessorFunctor.h b/Utilities/ITK/Code/Common/itkNeighborhoodAccessorFunctor.h index 9fb8a41772..4f7a6d02d1 100644 --- a/Utilities/ITK/Code/Common/itkNeighborhoodAccessorFunctor.h +++ b/Utilities/ITK/Code/Common/itkNeighborhoodAccessorFunctor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNeighborhoodAccessorFunctor.h,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:11 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-21 15:46:16 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -84,7 +84,13 @@ public: void SetVectorLength( VectorLengthType length ) {} VectorLengthType SetVectorLength() { return 0; } + + /** Constructor */ + NeighborhoodAccessorFunctor() {} + /** Destructor */ + virtual ~NeighborhoodAccessorFunctor() {} + }; } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkNeighborhoodAllocator.h b/Utilities/ITK/Code/Common/itkNeighborhoodAllocator.h index fdbf4fd7a2..56001aa594 100644 --- a/Utilities/ITK/Code/Common/itkNeighborhoodAllocator.h +++ b/Utilities/ITK/Code/Common/itkNeighborhoodAllocator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNeighborhoodAllocator.h,v $ Language: C++ - Date: $Date: 2009-02-19 19:41:22 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-03 15:07:52 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -140,7 +140,6 @@ inline std::ostream& operator<<( << static_cast<const void *>(a.begin()) << ", size=" << a.size() << " }"; - o << " } }"; return o; } diff --git a/Utilities/ITK/Code/Common/itkNumericTraitsVectorPixel.h b/Utilities/ITK/Code/Common/itkNumericTraitsVectorPixel.h index f3974dfd3a..7e290be722 100644 --- a/Utilities/ITK/Code/Common/itkNumericTraitsVectorPixel.h +++ b/Utilities/ITK/Code/Common/itkNumericTraitsVectorPixel.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNumericTraitsVectorPixel.h,v $ Language: C++ - Date: $Date: 2009-02-19 19:41:22 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-03 15:07:54 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -1547,4 +1547,3 @@ public: } // end namespace itk #endif // __itkNumericTraitsVectorPixel_h - diff --git a/Utilities/ITK/Code/Common/itkObjectFactoryBase.cxx b/Utilities/ITK/Code/Common/itkObjectFactoryBase.cxx index 43ff3e8db5..a8c0a25a32 100644 --- a/Utilities/ITK/Code/Common/itkObjectFactoryBase.cxx +++ b/Utilities/ITK/Code/Common/itkObjectFactoryBase.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkObjectFactoryBase.cxx,v $ Language: C++ - Date: $Date: 2008-05-26 00:24:36 $ - Version: $Revision: 1.57 $ + Date: $Date: 2009-04-05 10:56:46 $ + Version: $Revision: 1.58 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,7 +27,7 @@ #include "itkVersion.h" #include <stdlib.h> #include <ctype.h> -#include <cstring> +#include <string.h> #include <algorithm> #include <map> diff --git a/Utilities/ITK/Code/Common/itkObjectStore.h b/Utilities/ITK/Code/Common/itkObjectStore.h index e720b8855f..11c585cd5e 100644 --- a/Utilities/ITK/Code/Common/itkObjectStore.h +++ b/Utilities/ITK/Code/Common/itkObjectStore.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkObjectStore.h,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:14 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -91,7 +91,7 @@ public: /** Returns the size of the container. This is not the number of objects * available, but the total number of objects allocated. */ - itkGetMacro(Size, ::size_t); + itkGetConstMacro(Size, ::size_t); /** Ensures that there are at least n elements allocated in the storage * container. Will not shrink the container, but may enlarge the @@ -107,11 +107,11 @@ public: /** Set/Get the linear growth size */ itkSetMacro(LinearGrowthSize, ::size_t); - itkGetMacro(LinearGrowthSize, ::size_t); + itkGetConstMacro(LinearGrowthSize, ::size_t); /** Set/Get the growth strategy. */ itkSetMacro(GrowthStrategy, GrowthStrategyType); - itkGetMacro(GrowthStrategy, GrowthStrategyType); + itkGetConstMacro(GrowthStrategy, GrowthStrategyType); /** Set growth strategy to exponential */ void SetGrowthStrategyToExponential() diff --git a/Utilities/ITK/Code/Common/itkOutputWindow.h b/Utilities/ITK/Code/Common/itkOutputWindow.h index c672a9a8f6..790e87445e 100644 --- a/Utilities/ITK/Code/Common/itkOutputWindow.h +++ b/Utilities/ITK/Code/Common/itkOutputWindow.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOutputWindow.h,v $ Language: C++ - Date: $Date: 2009-02-19 19:41:22 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,7 +85,7 @@ public: * is displayed, the user is asked if they want to keep getting * messages. */ itkSetMacro(PromptUser,bool); - itkGetMacro(PromptUser,bool); + itkGetConstMacro(PromptUser,bool); itkBooleanMacro(PromptUser); protected: diff --git a/Utilities/ITK/Code/Common/itkPCAShapeSignedDistanceFunction.h b/Utilities/ITK/Code/Common/itkPCAShapeSignedDistanceFunction.h index 7dcb238f62..48a525fde3 100644 --- a/Utilities/ITK/Code/Common/itkPCAShapeSignedDistanceFunction.h +++ b/Utilities/ITK/Code/Common/itkPCAShapeSignedDistanceFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPCAShapeSignedDistanceFunction.h,v $ Language: C++ - Date: $Date: 2009-02-19 19:41:22 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -132,7 +132,7 @@ public: /** Set/Get the number of principal components * SetNumberOfPrincipalComponents must be called before SetParameters */ void SetNumberOfPrincipalComponents(unsigned int n); - itkGetMacro(NumberOfPrincipalComponents, unsigned int); + itkGetConstMacro(NumberOfPrincipalComponents, unsigned int); /** Set/Get the mean image. */ itkSetObjectMacro(MeanImage, ImageType); @@ -147,7 +147,7 @@ public: /** Set/Get the principal component standard deviations. These values corresponds * to the square root of the eigenvalues of the principal components. */ itkSetMacro(PrincipalComponentStandardDeviations, ParametersType); - itkGetMacro(PrincipalComponentStandardDeviations, ParametersType); + itkGetConstMacro(PrincipalComponentStandardDeviations, ParametersType); /** Set/Get transform. */ itkSetObjectMacro(Transform, TransformType); diff --git a/Utilities/ITK/Code/Common/itkPathFunctions.h b/Utilities/ITK/Code/Common/itkPathFunctions.h index fdb116fe40..ff1c61d2ff 100644 --- a/Utilities/ITK/Code/Common/itkPathFunctions.h +++ b/Utilities/ITK/Code/Common/itkPathFunctions.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPathFunctions.h,v $ Language: C++ - Date: $Date: 2009-02-19 19:41:23 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-06 00:08:10 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,7 +100,7 @@ void MakeFourierSeriesPathTraceChainCode( TFourierSeriesPath & FSPath, int dimension = OffsetType::GetOffsetDimension(); unsigned numSteps = chainPath.NumberOfSteps(); - const double PI = 4.0 * atan( 1.0 ); + const double PI = 4.0 * vcl_atan( 1.0 ); FSPath.Clear(); @@ -126,8 +126,8 @@ void MakeFourierSeriesPathTraceChainCode( TFourierSeriesPath & FSPath, { indexVector[d] = index[d]; } - cosCoefficient += indexVector * (cos(theta)/numSteps); - sinCoefficient += indexVector * (sin(theta)/numSteps); + cosCoefficient += indexVector * (vcl_cos(theta)/numSteps); + sinCoefficient += indexVector * (vcl_sin(theta)/numSteps); } FSPath.AddHarmonic( cosCoefficient, sinCoefficient ); diff --git a/Utilities/ITK/Code/Common/itkPixelTraits.h b/Utilities/ITK/Code/Common/itkPixelTraits.h index 841f3f420b..ea2b57af1f 100644 --- a/Utilities/ITK/Code/Common/itkPixelTraits.h +++ b/Utilities/ITK/Code/Common/itkPixelTraits.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPixelTraits.h,v $ Language: C++ - Date: $Date: 2009-02-19 19:41:23 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-03-03 15:07:54 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,8 @@ public: typedef typename TPixelType::ValueType ValueType; }; -/** Specialization of PixelTraitss for scalar images. */ +/** \class PixelTraits<bool> + * Specialization of PixelTraits for scalar images. */ template <> class PixelTraits<bool> { public: @@ -153,7 +154,8 @@ public: typedef TValueType1 ValueType; }; -/** Specializations for bool. */ +/** \class JoinTraits + * Specializations for bool. */ template<> class JoinTraits<bool, bool> { @@ -231,7 +233,8 @@ public: typedef double ValueType; }; -/** Specializations for char. */ +/** \class PixelTraits<char> + * Specializations for char. */ template<> class JoinTraits<char, bool> { @@ -310,7 +313,8 @@ public: typedef double ValueType; }; -/** Specializations for unsigned char. */ +/** \class PixelTraits<unsigned char> + * Specializations for unsigned char. */ template<> class JoinTraits<unsigned char, bool> { @@ -388,7 +392,8 @@ public: typedef double ValueType; }; -/** Specializations for short. */ +/** \class PixelTraits<short> + * Specializations for short. */ template<> class JoinTraits<short, bool> { @@ -467,7 +472,8 @@ public: typedef double ValueType; }; -/** Specializations for unsigned short. */ +/** \class PixelTraits<unsigned short> + * Specializations for unsigned short. */ template<> class JoinTraits<unsigned short, bool> { @@ -545,7 +551,8 @@ public: typedef double ValueType; }; -/** Specializations for int. */ +/** \class PixelTraits<int> + * Specializations for int. */ template<> class JoinTraits<int, bool> { @@ -624,7 +631,8 @@ public: typedef double ValueType; }; -/** Specializations for unsigned int. */ +/** \class PixelTraits<unsigned int> + * Specializations for unsigned int. */ template<> class JoinTraits<unsigned int, bool> { @@ -705,7 +713,8 @@ public: typedef double ValueType; }; -/** Specializations for long. */ +/** \class PixelTraits<long> + * Specializations for long. */ template<> class JoinTraits<long, bool> { @@ -783,7 +792,8 @@ public: typedef double ValueType; }; -/** Specializations for unsigned long. */ +/** \class PixelTraits<unsigned long> + * Specializations for unsigned long. */ template<> class JoinTraits<unsigned long, bool> { @@ -861,7 +871,8 @@ public: typedef double ValueType; }; -/** Specializations for float. */ +/** \class PixelTraits<float> + * Specializations for float. */ template<> class JoinTraits<float, bool> { @@ -939,7 +950,8 @@ public: typedef double ValueType; }; -/** Specializations for double. */ +/** \class PixelTraits<double> + * Specializations for double. */ template<> class JoinTraits<double, bool> { diff --git a/Utilities/ITK/Code/Common/itkPoint.h b/Utilities/ITK/Code/Common/itkPoint.h index 7900812c60..fc3c818943 100644 --- a/Utilities/ITK/Code/Common/itkPoint.h +++ b/Utilities/ITK/Code/Common/itkPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPoint.h,v $ Language: C++ - Date: $Date: 2008-11-14 05:09:25 $ - Version: $Revision: 1.67 $ + Date: $Date: 2009-03-03 15:07:54 $ + Version: $Revision: 1.68 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,7 +46,7 @@ class Point : public FixedArray< TCoordRep, NPointDimension > { public: /** Standard class typedefs. */ - typedef Point Self; + typedef Point Self; typedef FixedArray<TCoordRep,NPointDimension> Superclass; /** ValueType can be used to declare a variable that is the same type @@ -211,20 +211,20 @@ public: * Casting is done with C-Like rules */ template < typename TCoordRepB > void CastFrom( const Point<TCoordRepB,NPointDimension> & pa ) - { + { for(unsigned int i=0; i<NPointDimension; i++ ) { (*this)[i] = static_cast<TCoordRep>( pa[i] ); } - } - + } /** Compute the Squared Euclidean Distance from this point to another point - * with a different representation type. Casting is done with C-Like rules */ + * with a different representation type. Casting is done with + * C-Like rules */ template < typename TCoordRepB > RealType SquaredEuclideanDistanceTo( const Point<TCoordRepB,NPointDimension> & pa ) const - { + { RealType sum = NumericTraits< RealType >::Zero; for(unsigned int i=0; i<NPointDimension; i++ ) { @@ -232,21 +232,19 @@ public: const ValueType difference = (*this)[i] - component; sum += difference * difference; } - return sum; - } - - + return sum; + } /** Compute the Euclidean Distance from this point to another point - * with a different representation type. Casting is done with C-Like rules */ + * with a different representation type. Casting is done with + * C-Like rules */ template < typename TCoordRepB > RealType EuclideanDistanceTo( const Point<TCoordRepB,NPointDimension> & pa ) const - { - const double distance = vcl_sqrt( - static_cast<double>( this->SquaredEuclideanDistanceTo( pa ) ) ) ; - return static_cast<RealType>( distance ); - } - + { + const double distance = vcl_sqrt( + static_cast<double>( this->SquaredEuclideanDistanceTo( pa ) ) ); + return static_cast<RealType>( distance ); + } }; @@ -258,7 +256,8 @@ template< class T, unsigned int NPointDimension > ITK_EXPORT std::istream& operator>>(std::istream& is, Point<T,NPointDimension> & v); -/** Class that computes the barycentric combination of an array of N points +/** \class BarycentricCombination + * Class that computes the barycentric combination of an array of N points * * An array of (N-1) values is expected to weight the contribution of the * first (N-1) points, the weight of the Nth point is computed to ensure that @@ -284,10 +283,10 @@ ITK_EXPORT class BarycentricCombination { public: /** Convenient typedefs. */ - typedef TPointContainer PointContainerType; + typedef TPointContainer PointContainerType; typedef typename PointContainerType::Pointer PointContainerPointer; typedef typename PointContainerType::Element PointType; - typedef TWeightContainer WeightContainerType; + typedef TWeightContainer WeightContainerType; BarycentricCombination() {}; ~BarycentricCombination() {}; diff --git a/Utilities/ITK/Code/Common/itkPointLocator.h b/Utilities/ITK/Code/Common/itkPointLocator.h index d3df174cd2..e06c95d921 100644 --- a/Utilities/ITK/Code/Common/itkPointLocator.h +++ b/Utilities/ITK/Code/Common/itkPointLocator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointLocator.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:23 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -60,9 +60,9 @@ class ITK_EXPORT PointLocator : public Object { public: /** Standard class typedefs. */ - typedef PointLocator Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; + typedef PointLocator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ @@ -76,10 +76,10 @@ public: /** Hold on to the type information specified by the template parameters. * PointIdentifier is the type that the point handles are represented by. */ - typedef TPointIdentifier PointIdentifier; - typedef TCoordRep CoordRepType; - typedef TPointsContainer PointsContainer; - typedef typename PointsContainer::Pointer PointsContainerPointer; + typedef TPointIdentifier PointIdentifier; + typedef TCoordRep CoordRepType; + typedef TPointsContainer PointsContainer; + typedef typename PointsContainer::Pointer PointsContainerPointer; typedef Point< CoordRepType, VPointDimension > PointType; /** Some convenience typedefs. */ @@ -94,7 +94,7 @@ public: /** Specify the average number of points in each bucket. */ itkSetClampMacro(NumberOfPointsPerBucket, unsigned long,1,NumericTraits<unsigned long>::max()); - itkGetMacro(NumberOfPointsPerBucket,unsigned long); + itkGetConstMacro(NumberOfPointsPerBucket,unsigned long); /** Insert all the points contained in the PointsContainer newPts * into the locator. Also supply a bounding box in which the points lie. @@ -179,14 +179,14 @@ protected: float Distance2ToBounds(float x[3], float bounds[6]); - float Bounds[6]; // bounds of points - itkIdList **HashTable; // lists of point ids in buckets - int NumberOfBuckets; // total size of hash table - float H[3]; // width of each bucket in x-y-z directions - itkNeighborPoints *Buckets; + float m_Bounds[6]; // bounds of points + itkIdList **m_HashTable; // lists of point ids in buckets + int m_NumberOfBuckets; // total size of hash table + float m_H[3]; // width of each bucket in x-y-z directions + itkNeighborPoints *m_Buckets; - float InsertionTol2; - float InsertionLevel; + float m_InsertionTol2; + float m_InsertionLevel; #endif private: @@ -194,7 +194,7 @@ private: void operator=(const Self&); //purposely not implemented unsigned long *m_Divisions; - unsigned long m_NumberOfPointsPerBucket; + unsigned long m_NumberOfPointsPerBucket; PointsContainerPointer m_Points; @@ -207,5 +207,3 @@ private: #endif #endif - - diff --git a/Utilities/ITK/Code/Common/itkPointLocator.txx b/Utilities/ITK/Code/Common/itkPointLocator.txx index 522805864c..d34239c9c3 100644 --- a/Utilities/ITK/Code/Common/itkPointLocator.txx +++ b/Utilities/ITK/Code/Common/itkPointLocator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointLocator.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:36:59 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-06 13:46:38 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,8 +17,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkPointLocator_txx -#define _itkPointLocator_txx +#ifndef __itkPointLocator_txx +#define __itkPointLocator_txx #include "itkPointLocator.h" namespace itk @@ -74,7 +74,7 @@ float hmin; int ndivs[3]; float level; -if ( this->HashTable ) +if ( this->m_HashTable ) { this->FreeSearchStructure(); } @@ -92,18 +92,18 @@ this->Points->Register(this); for (i=0; i<3; i++) { - this->Bounds[2*i] = bounds[2*i]; - this->Bounds[2*i+1] = bounds[2*i+1]; - if ( this->Bounds[2*i+1] <= this->Bounds[2*i] ) + this->m_Bounds[2*i] = bounds[2*i]; + this->m_Bounds[2*i+1] = bounds[2*i+1]; + if ( this->m_Bounds[2*i+1] <= this->m_Bounds[2*i] ) { - this->Bounds[2*i+1] = this->Bounds[2*i] + 1.0; + this->m_Bounds[2*i+1] = this->m_Bounds[2*i] + 1.0; } } if ( this->Automatic && (estNumPts > 0) ) { level = (float) estNumPts / this->NumberOfPointsPerBucket; - level = ::ceil( vcl_pow((double)level,(double)0.33333333) ); + level = vcl_ceil( vcl_pow((double)level,(double)0.33333333) ); for (i=0; i<3; i++) { ndivs[i] = (int) level; @@ -123,34 +123,35 @@ for (i=0; i<3; i++) this->Divisions[i] = ndivs[i]; } -this->NumberOfBuckets = ndivs[0]*ndivs[1]*ndivs[2]; -this->HashTable = new vtkIdListPtr[this->NumberOfBuckets]; -memset (this->HashTable, 0, this->NumberOfBuckets* +this->m_NumberOfBuckets = ndivs[0]*ndivs[1]*ndivs[2]; +this->m_HashTable = new vtkIdListPtr[this->m_NumberOfBuckets]; +memset (this->m_HashTable, 0, this->m_NumberOfBuckets* sizeof(vtkIdListPtr)); // // Compute width of bucket in three directions // for (i=0; i<3; i++) { - this->H[i] = (this->Bounds[2*i+1] - this->Bounds[2*i]) / ndivs[i] ; + this->m_H[i] = (this->m_Bounds[2*i+1] - this->m_Bounds[2*i]) / ndivs[i]; } -this->InsertionTol2 = this->Tolerance * this->Tolerance; +this->m_InsertionTol2 = this->Tolerance * this->Tolerance; for (maxDivs=0, hmin=VTK_LARGE_FLOAT, i=0; i<3; i++) { - hmin = (this->H[i] < hmin ? this->H[i] : hmin); + hmin = (this->m_H[i] < hmin ? this->m_H[i] : hmin); maxDivs = (maxDivs > this->Divisions[i] ? maxDivs : this->Divisions[i]); } -this->InsertionLevel = ::ceil ((double) this->Tolerance / hmin); -this->InsertionLevel = (this->InsertionLevel > maxDivs ? maxDivs : this->InsertionLevel); +this->m_InsertionLevel = vcl_ceil ((double) this->Tolerance / hmin); +this->m_InsertionLevel = (this->m_InsertionLevel > maxDivs ? maxDivs : this->m_InsertionLevel); return 1; #endif /****************************************************************************** * PROTECTED METHOD DEFINITIONS - *****************************************************************************/ + ****************************************************************************** + */ template <typename TPointIdentifier, int VPointDimension, typename TCoordRep, typename TPointsContainer> diff --git a/Utilities/ITK/Code/Common/itkPointSet.h b/Utilities/ITK/Code/Common/itkPointSet.h index b83913ea5e..c4f39f1bbc 100644 --- a/Utilities/ITK/Code/Common/itkPointSet.h +++ b/Utilities/ITK/Code/Common/itkPointSet.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointSet.h,v $ Language: C++ - Date: $Date: 2007-02-07 13:52:47 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,7 +41,7 @@ namespace itk template <typename TPointSet> struct GetPointSetDimension { -itkStaticConstMacro(PointDimension, unsigned int, TPointSet::PointDimension); + itkStaticConstMacro(PointDimension, unsigned int, TPointSet::PointDimension); }; /** \class PointSet @@ -92,9 +92,9 @@ class ITK_EXPORT PointSet: public DataObject { public: /** Standard class typedefs. */ - typedef PointSet Self; - typedef DataObject Superclass; - typedef SmartPointer<Self> Pointer; + typedef PointSet Self; + typedef DataObject Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ @@ -104,7 +104,7 @@ public: itkTypeMacro(PointSet, Object); /** Hold on to the type information specified by the template parameters. */ - typedef TMeshTraits MeshTraits; + typedef TMeshTraits MeshTraits; typedef typename MeshTraits::PixelType PixelType; /** Convenient typedefs obtained from TMeshTraits template parameter. */ @@ -218,11 +218,11 @@ public: /** Set/Get the Requested region */ virtual void SetRequestedRegion( const RegionType & region ); - itkGetMacro( RequestedRegion, RegionType ); + itkGetConstMacro( RequestedRegion, RegionType ); /** Set/Get the Buffered region */ virtual void SetBufferedRegion( const RegionType & region ); - itkGetMacro( BufferedRegion, RegionType ); + itkGetConstMacro( BufferedRegion, RegionType ); protected: diff --git a/Utilities/ITK/Code/Common/itkPointSet.txx b/Utilities/ITK/Code/Common/itkPointSet.txx index 7b62c8fdd0..66b967f36c 100644 --- a/Utilities/ITK/Code/Common/itkPointSet.txx +++ b/Utilities/ITK/Code/Common/itkPointSet.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointSet.txx,v $ Language: C++ - Date: $Date: 2008-05-08 15:41:46 $ - Version: $Revision: 1.33 $ + Date: $Date: 2009-03-03 15:07:57 $ + Version: $Revision: 1.34 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -62,8 +62,6 @@ PointSet<TPixelType, VDimension, TMeshTraits> } } - - /** * Access routine to get the points container. */ @@ -125,8 +123,6 @@ PointSet<TPixelType, VDimension, TMeshTraits> return m_PointDataContainer; } - - /** * Access routine to get the point data container. */ @@ -234,8 +230,10 @@ PointSet<TPixelType, VDimension, TMeshTraits> * either. */ if( !m_PointDataContainer ) + { return false; - + } + /** * Ask the container if the point identifier exists. */ diff --git a/Utilities/ITK/Code/Common/itkPolyLineParametricPath.h b/Utilities/ITK/Code/Common/itkPolyLineParametricPath.h index d63c8523b0..16d5c50862 100644 --- a/Utilities/ITK/Code/Common/itkPolyLineParametricPath.h +++ b/Utilities/ITK/Code/Common/itkPolyLineParametricPath.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPolyLineParametricPath.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-03 15:07:57 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkPolyLineParametricPathPath_h -#define __itkPolyLineParametricPathPath_h +#ifndef __itkPolyLineParametricPath_h +#define __itkPolyLineParametricPath_h #include "itkParametricPath.h" #include "itkVectorContainer.h" @@ -73,12 +73,12 @@ public: /** Basic data-structure types used */ - typedef ContinuousIndex<double,VDimension> ContinuousIndexType; - typedef Index< VDimension > IndexType; - typedef Offset< VDimension > OffsetType; - typedef Point<double,VDimension> PointType; - typedef Vector<double,VDimension> VectorType; - typedef ContinuousIndexType VertexType; + typedef ContinuousIndex<double,VDimension> ContinuousIndexType; + typedef Index< VDimension > IndexType; + typedef Offset< VDimension > OffsetType; + typedef Point<double,VDimension> PointType; + typedef Vector<double,VDimension> VectorType; + typedef ContinuousIndexType VertexType; typedef VectorContainer<unsigned, VertexType> VertexListType; typedef typename VertexListType::Pointer VertexListPointer; diff --git a/Utilities/ITK/Code/Common/itkPolyLineParametricPath.txx b/Utilities/ITK/Code/Common/itkPolyLineParametricPath.txx index 155bd0ada9..4362bde3cb 100644 --- a/Utilities/ITK/Code/Common/itkPolyLineParametricPath.txx +++ b/Utilities/ITK/Code/Common/itkPolyLineParametricPath.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPolyLineParametricPath.txx,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:07:57 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -55,8 +55,6 @@ PolyLineParametricPath<VDimension> return output; } - - //template<unsigned int VDimension> //typename PolyLineParametricPath<VDimension>::VectorType //PolyLineParametricPath<VDimension> @@ -64,8 +62,6 @@ PolyLineParametricPath<VDimension> //{ //} - - /** * Constructor */ @@ -77,8 +73,6 @@ PolyLineParametricPath<VDimension> m_VertexList = VertexListType::New(); } - - /** * Standard "PrintSelf" method */ @@ -91,8 +85,6 @@ PolyLineParametricPath<VDimension> os << indent << "Verticies: " << m_VertexList << std::endl; } - - } // end namespace itk #endif diff --git a/Utilities/ITK/Code/Common/itkPolygonCell.h b/Utilities/ITK/Code/Common/itkPolygonCell.h index 1dc2d0d975..c85b72d8f8 100644 --- a/Utilities/ITK/Code/Common/itkPolygonCell.h +++ b/Utilities/ITK/Code/Common/itkPolygonCell.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPolygonCell.h,v $ Language: C++ - Date: $Date: 2007-05-19 12:50:04 $ - Version: $Revision: 1.34 $ + Date: $Date: 2009-03-03 15:07:57 $ + Version: $Revision: 1.35 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -65,7 +65,7 @@ public: typedef LineCell< TCellInterface > EdgeType; typedef typename EdgeType::SelfAutoPointer EdgeAutoPointer; - typedef FixedArray<int,2> EdgeInfo; + typedef FixedArray<int,2> EdgeInfo; typedef std::deque<EdgeInfo> EdgeInfoDQ; /** Need to add POLYGON_CELL into CellInterface. */ @@ -116,7 +116,7 @@ public: ~PolygonCell() {} protected: - std::vector<EdgeInfo> m_Edges; + std::vector<EdgeInfo> m_Edges; std::vector<PointIdentifier> m_PointIds; private: @@ -132,5 +132,3 @@ private: #endif #endif - - diff --git a/Utilities/ITK/Code/Common/itkPolygonCell.txx b/Utilities/ITK/Code/Common/itkPolygonCell.txx index 99889f8e58..fca1cf36b4 100644 --- a/Utilities/ITK/Code/Common/itkPolygonCell.txx +++ b/Utilities/ITK/Code/Common/itkPolygonCell.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPolygonCell.txx,v $ Language: C++ - Date: $Date: 2008-01-17 15:30:17 $ - Version: $Revision: 1.35 $ + Date: $Date: 2009-03-03 15:07:57 $ + Version: $Revision: 1.36 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,8 +17,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkPolygonCell_txx -#define _itkPolygonCell_txx +#ifndef __itkPolygonCell_txx +#define __itkPolygonCell_txx #include "itkPolygonCell.h" @@ -108,47 +108,45 @@ PolygonCell< TCellInterface > switch (dimension) { case 0: - { - VertexAutoPointer vertexPointer; - if( this->GetVertex(featureId,vertexPointer) ) - { - TransferAutoPointer(cellPointer,vertexPointer); - return true; - } - else { - cellPointer.Reset(); - return false; + VertexAutoPointer vertexPointer; + if( this->GetVertex(featureId,vertexPointer) ) + { + TransferAutoPointer(cellPointer,vertexPointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - break; - } case 1: - { - EdgeAutoPointer edgePointer; - if( this->GetEdge(featureId,edgePointer) ) { - TransferAutoPointer(cellPointer,edgePointer); - return true; + EdgeAutoPointer edgePointer; + if( this->GetEdge(featureId,edgePointer) ) + { + TransferAutoPointer(cellPointer,edgePointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - else + + default: { cellPointer.Reset(); return false; } - break; - } - - default: - { - cellPointer.Reset(); - return false; - } } return false; } - - /** * Standard CellInterface: * Set the point id list used by the cell. It is assumed that the given @@ -162,7 +160,7 @@ PolygonCell< TCellInterface > { PointIdConstIterator ii(first); m_PointIds.clear(); - for(int i=0; i < num ; ++i) + for(int i=0; i < num; ++i) { m_PointIds.push_back(*ii++); } @@ -207,7 +205,7 @@ PolygonCell< TCellInterface > ::SetPointIds(PointIdConstIterator first) { PointIdConstIterator ii(first); - for(unsigned int i=0; i < m_PointIds.size() ; ++i) + for(unsigned int i=0; i < m_PointIds.size(); ++i) { m_PointIds[i] = *ii++; } @@ -426,14 +424,16 @@ PolygonCell< TCellInterface > { EdgeType * edge = new EdgeType; unsigned int max_pointId = this->GetNumberOfPoints() - 1; - if( edgeId < max_pointId ){ - edge->SetPointId(0, m_PointIds[edgeId]); - edge->SetPointId(1, m_PointIds[edgeId+1]); - } - else if( edgeId == max_pointId ) { - edge->SetPointId(0, m_PointIds[max_pointId] ); - edge->SetPointId(1, m_PointIds[0] ); - } + if( edgeId < max_pointId ) + { + edge->SetPointId(0, m_PointIds[edgeId]); + edge->SetPointId(1, m_PointIds[edgeId+1]); + } + else if( edgeId == max_pointId ) + { + edge->SetPointId(0, m_PointIds[max_pointId] ); + edge->SetPointId(1, m_PointIds[0] ); + } edgePointer.TakeOwnership( edge ); return true; } diff --git a/Utilities/ITK/Code/Common/itkPostOrderTreeIterator.h b/Utilities/ITK/Code/Common/itkPostOrderTreeIterator.h index 9fbf7fd4da..9627421756 100644 --- a/Utilities/ITK/Code/Common/itkPostOrderTreeIterator.h +++ b/Utilities/ITK/Code/Common/itkPostOrderTreeIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPostOrderTreeIterator.h,v $ Language: C++ - Date: $Date: 2008-01-29 15:27:42 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:07:57 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,7 +19,7 @@ #include <itkTreeIteratorBase.h> -namespace itk{ +namespace itk { template <class TTreeType> class PostOrderTreeIterator : public TreeIteratorBase<TTreeType> @@ -63,17 +63,16 @@ PostOrderTreeIterator<TTreeType>::PostOrderTreeIterator( TTreeType* tree) this->m_Position = const_cast<TreeNode<ValueType>*>(tree->GetRoot()); if ( this->m_Position == NULL ) - { + { this->m_Begin = NULL; - } + } else - { + { this->m_Position =const_cast<TreeNodeType* >(FindMostRightLeaf(this->m_Position)); this->m_Begin = this->m_Position; - } + } } - /** Return the type of the iterator */ template <class TTreeType> int @@ -156,24 +155,25 @@ template <class TTreeType> const typename PostOrderTreeIterator<TTreeType>::TreeNodeType* PostOrderTreeIterator<TTreeType>::FindMostRightLeaf(TreeNodeType* node) const { - while ( node->HasChildren() ) - { - TreeNodeType* helpNode; - int childCount = node->CountChildren(); - int i = 0; - - do - { - helpNode = node->GetChild( i ); - i++; - } while ( helpNode == NULL && i < childCount ); - - if ( helpNode == NULL ) - { - return node; - } - node = helpNode; - } + while ( node->HasChildren() ) + { + TreeNodeType* helpNode; + int childCount = node->CountChildren(); + int i = 0; + + do + { + helpNode = node->GetChild( i ); + i++; + } + while ( helpNode == NULL && i < childCount ); + + if ( helpNode == NULL ) + { + return node; + } + node = helpNode; + } return node; } @@ -189,4 +189,3 @@ TreeIteratorBase<TTreeType>* PostOrderTreeIterator<TTreeType>::Clone() } // end namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkPreOrderTreeIterator.h b/Utilities/ITK/Code/Common/itkPreOrderTreeIterator.h index 93376a4647..6516f9948b 100644 --- a/Utilities/ITK/Code/Common/itkPreOrderTreeIterator.h +++ b/Utilities/ITK/Code/Common/itkPreOrderTreeIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPreOrderTreeIterator.h,v $ Language: C++ - Date: $Date: 2008-06-20 20:28:42 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:08:00 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,7 +19,7 @@ #include <itkTreeIteratorBase.h> -namespace itk{ +namespace itk { template <class TTreeType> class PreOrderTreeIterator : public TreeIteratorBase<TTreeType> @@ -27,8 +27,8 @@ class PreOrderTreeIterator : public TreeIteratorBase<TTreeType> public: /** Typedefs */ - typedef typename TTreeType::ValueType ValueType; - typedef TreeIteratorBase<TTreeType> Superclass; + typedef typename TTreeType::ValueType ValueType; + typedef TreeIteratorBase<TTreeType> Superclass; typedef typename Superclass::TreeNodeType TreeNodeType; /** Constructor */ @@ -114,9 +114,9 @@ PreOrderTreeIterator<TTreeType>::FindNextNode() const // Are we a subtree? Then we are done. if( parent && parent->ChildPosition( this->m_Root ) >= 0 ) - { + { return NULL; - } + } int childPosition = parent->ChildPosition( child ); int lastChildPosition = parent->CountChildren() - 1; diff --git a/Utilities/ITK/Code/Common/itkProcessObject.cxx b/Utilities/ITK/Code/Common/itkProcessObject.cxx index 2c3e7a3e85..ce2d724a72 100644 --- a/Utilities/ITK/Code/Common/itkProcessObject.cxx +++ b/Utilities/ITK/Code/Common/itkProcessObject.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkProcessObject.cxx,v $ Language: C++ - Date: $Date: 2007-12-23 17:59:29 $ - Version: $Revision: 1.74 $ + Date: $Date: 2009-03-03 15:08:01 $ + Version: $Revision: 1.75 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -289,8 +289,6 @@ ProcessObject } } - - void ProcessObject ::RemoveOutput(DataObject *output) @@ -599,8 +597,6 @@ ProcessObject m_Threader->PrintSelf(os, indent.GetNextIndent()); } - - /** * The following methods are used to coordinate the execution of the * data processing pipeline. @@ -1132,7 +1128,4 @@ ProcessObject } } - - - } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkProcessObject.h b/Utilities/ITK/Code/Common/itkProcessObject.h index 420d6e7153..dad74496ca 100644 --- a/Utilities/ITK/Code/Common/itkProcessObject.h +++ b/Utilities/ITK/Code/Common/itkProcessObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkProcessObject.h,v $ Language: C++ - Date: $Date: 2007-08-17 20:16:10 $ - Version: $Revision: 1.77 $ + Date: $Date: 2009-03-03 15:08:02 $ + Version: $Revision: 1.78 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -82,15 +82,15 @@ namespace itk * * \ingroup ITKSystemObjects * \ingroup DataProcessing - * + * */ class ITKCommon_EXPORT ProcessObject : public Object { public: /** Standard class typedefs. */ - typedef ProcessObject Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; + typedef ProcessObject Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ @@ -426,14 +426,14 @@ private: /** An array of the inputs to the filter. */ DataObjectPointerArray m_Inputs; - unsigned int m_NumberOfRequiredInputs; + unsigned int m_NumberOfRequiredInputs; /** An array that caches the ReleaseDataFlags of the inputs */ std::vector<bool> m_CachedInputReleaseDataFlags; /** An array of the outputs to the filter. */ DataObjectPointerArray m_Outputs; - unsigned int m_NumberOfRequiredOutputs; + unsigned int m_NumberOfRequiredOutputs; /** These support the progress method and aborting filter execution. */ bool m_AbortGenerateData; @@ -442,7 +442,7 @@ private: /** Support processing data in multiple threads. Used by subclasses * (e.g., ImageSource). */ MultiThreader::Pointer m_Threader; - int m_NumberOfThreads; + int m_NumberOfThreads; /** Memory management ivars */ bool m_ReleaseDataBeforeUpdateFlag; @@ -454,4 +454,3 @@ private: } // end namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkProgressAccumulator.h b/Utilities/ITK/Code/Common/itkProgressAccumulator.h index c3e8eec860..5d505aff67 100644 --- a/Utilities/ITK/Code/Common/itkProgressAccumulator.h +++ b/Utilities/ITK/Code/Common/itkProgressAccumulator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkProgressAccumulator.h,v $ Language: C++ - Date: $Date: 2007-12-21 15:32:36 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -56,7 +56,7 @@ public: itkTypeMacro(ProgressAccumulator,Object); /** Get the total progress accumulated by this object */ - itkGetMacro(AccumulatedProgress,float); + itkGetConstMacro(AccumulatedProgress,float); /** Set the mini-pipeline filter */ itkSetObjectMacro(MiniPipelineFilter,ProcessObject); diff --git a/Utilities/ITK/Code/Common/itkProgressReporter.h b/Utilities/ITK/Code/Common/itkProgressReporter.h index 257bdac4d4..ddcb508dd6 100644 --- a/Utilities/ITK/Code/Common/itkProgressReporter.h +++ b/Utilities/ITK/Code/Common/itkProgressReporter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkProgressReporter.h,v $ Language: C++ - Date: $Date: 2006-07-24 11:41:15 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-03 15:08:02 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,14 +95,14 @@ public: } protected: - ProcessObject* m_Filter; - int m_ThreadId; - float m_InverseNumberOfPixels; - unsigned long m_CurrentPixel; - unsigned long m_PixelsPerUpdate; - unsigned long m_PixelsBeforeUpdate; - float m_InitialProgress; - float m_ProgressWeight; + ProcessObject* m_Filter; + int m_ThreadId; + float m_InverseNumberOfPixels; + unsigned long m_CurrentPixel; + unsigned long m_PixelsPerUpdate; + unsigned long m_PixelsBeforeUpdate; + float m_InitialProgress; + float m_ProgressWeight; private: ProgressReporter(); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkQuadraticEdgeCell.txx b/Utilities/ITK/Code/Common/itkQuadraticEdgeCell.txx index 29e80a5ae5..133423b439 100644 --- a/Utilities/ITK/Code/Common/itkQuadraticEdgeCell.txx +++ b/Utilities/ITK/Code/Common/itkQuadraticEdgeCell.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadraticEdgeCell.txx,v $ Language: C++ - Date: $Date: 2007-05-17 21:00:08 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-03 15:08:02 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkQuadraticEdgeCell_txx -#define _itkQuadraticEdgeCell_txx +#ifndef __itkQuadraticEdgeCell_txx +#define __itkQuadraticEdgeCell_txx #include "itkQuadraticEdgeCell.h" namespace itk @@ -92,25 +92,25 @@ QuadraticEdgeCell< TCellInterface > switch (dimension) { case 0: - { - VertexAutoPointer vertexPointer; - if( this->GetVertex(featureId,vertexPointer) ) { - TransferAutoPointer(cellPointer,vertexPointer); - return true; + VertexAutoPointer vertexPointer; + if( this->GetVertex(featureId,vertexPointer) ) + { + TransferAutoPointer(cellPointer,vertexPointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - else + default: { cellPointer.Reset(); return false; } - break; - } - default: - { - cellPointer.Reset(); - return false; - } } return false; } @@ -128,8 +128,10 @@ QuadraticEdgeCell< TCellInterface > ::SetPointIds(PointIdConstIterator first) { PointIdConstIterator ii(first); - for(unsigned int i=0; i < Self::NumberOfPoints ; ++i) + for(unsigned int i=0; i < Self::NumberOfPoints; ++i) + { m_PointIds[i] = *ii++; + } } @@ -277,4 +279,3 @@ QuadraticEdgeCell< TCellInterface > } // end namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkQuadraticTriangleCell.h b/Utilities/ITK/Code/Common/itkQuadraticTriangleCell.h index 617894de82..0875025b40 100644 --- a/Utilities/ITK/Code/Common/itkQuadraticTriangleCell.h +++ b/Utilities/ITK/Code/Common/itkQuadraticTriangleCell.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadraticTriangleCell.h,v $ Language: C++ - Date: $Date: 2007-05-18 14:31:12 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-03 15:08:02 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -97,10 +97,7 @@ public: virtual void EvaluateShapeFunctions( const ParametricCoordArrayType & parametricCoordinates, ShapeFunctionsArrayType & weights) const; - - - - public: +public: QuadraticTriangleCell() { for (unsigned int i = 0; i < itkGetStaticConstMacro(NumberOfPoints); i++) @@ -110,11 +107,11 @@ public: } ~QuadraticTriangleCell() {} - protected: +protected: /** Store the number of points needed for a triangle. */ PointIdentifier m_PointIds[NumberOfPoints]; - private: +private: QuadraticTriangleCell(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; diff --git a/Utilities/ITK/Code/Common/itkQuadraticTriangleCell.txx b/Utilities/ITK/Code/Common/itkQuadraticTriangleCell.txx index 568051f20b..d784ed2f2b 100644 --- a/Utilities/ITK/Code/Common/itkQuadraticTriangleCell.txx +++ b/Utilities/ITK/Code/Common/itkQuadraticTriangleCell.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadraticTriangleCell.txx,v $ Language: C++ - Date: $Date: 2007-05-17 21:00:08 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-03 15:08:02 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkQuadraticTriangleCell_txx -#define _itkQuadraticTriangleCell_txx +#ifndef __itkQuadraticTriangleCell_txx +#define __itkQuadraticTriangleCell_txx #include "itkQuadraticTriangleCell.h" namespace itk @@ -93,46 +93,45 @@ QuadraticTriangleCell< TCellInterface > switch (dimension) { case 0: - { - VertexAutoPointer vertexPointer; - if( this->GetVertex(featureId,vertexPointer) ) - { - TransferAutoPointer(cellPointer,vertexPointer); - return true; - } - else { - cellPointer.Reset(); - return false; + VertexAutoPointer vertexPointer; + if( this->GetVertex(featureId,vertexPointer) ) + { + TransferAutoPointer(cellPointer,vertexPointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - break; - } case 1: - { - EdgeAutoPointer edgePointer; - if( this->GetEdge(featureId,edgePointer) ) { - TransferAutoPointer(cellPointer,edgePointer); - return true; + EdgeAutoPointer edgePointer; + if( this->GetEdge(featureId,edgePointer) ) + { + TransferAutoPointer(cellPointer,edgePointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - else + + default: { cellPointer.Reset(); return false; } - break; - } - - default: - { - cellPointer.Reset(); - return false; - } } return false; } - /** * Standard CellInterface: * Set the point id list used by the cell. It is assumed that the given @@ -145,7 +144,7 @@ QuadraticTriangleCell< TCellInterface > ::SetPointIds(PointIdConstIterator first) { PointIdConstIterator ii(first); - for(unsigned int i=0; i < Self::NumberOfPoints ; ++i) + for(unsigned int i=0; i < Self::NumberOfPoints; ++i) { m_PointIds[i] = *ii++; } @@ -333,10 +332,6 @@ QuadraticTriangleCell< TCellInterface > } - - - - } // end namespace itk #endif diff --git a/Utilities/ITK/Code/Common/itkQuadraticTriangleCellTopology.cxx b/Utilities/ITK/Code/Common/itkQuadraticTriangleCellTopology.cxx index c384bb9928..1c35e3d123 100644 --- a/Utilities/ITK/Code/Common/itkQuadraticTriangleCellTopology.cxx +++ b/Utilities/ITK/Code/Common/itkQuadraticTriangleCellTopology.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadraticTriangleCellTopology.cxx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:23 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:08:03 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,4 +40,3 @@ QuadraticTriangleCellTopology } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkQuadraticTriangleCellTopology.h b/Utilities/ITK/Code/Common/itkQuadraticTriangleCellTopology.h index 5adeeb7ee0..3c5b335aad 100644 --- a/Utilities/ITK/Code/Common/itkQuadraticTriangleCellTopology.h +++ b/Utilities/ITK/Code/Common/itkQuadraticTriangleCellTopology.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadraticTriangleCellTopology.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:23 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:08:05 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,16 +34,14 @@ namespace itk class ITKCommon_EXPORT QuadraticTriangleCellTopology { -protected: - - /** Triangle topology data. */ - static const int m_Edges[3][3]; - - public: QuadraticTriangleCellTopology(); ~QuadraticTriangleCellTopology(); +protected: + /** Triangle topology data. */ + static const int m_Edges[3][3]; + }; } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkQuadrilateralCell.txx b/Utilities/ITK/Code/Common/itkQuadrilateralCell.txx index 343b70f146..d94438bb79 100644 --- a/Utilities/ITK/Code/Common/itkQuadrilateralCell.txx +++ b/Utilities/ITK/Code/Common/itkQuadrilateralCell.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadrilateralCell.txx,v $ Language: C++ - Date: $Date: 2007-05-17 21:00:09 $ - Version: $Revision: 1.33 $ + Date: $Date: 2009-03-03 15:08:08 $ + Version: $Revision: 1.34 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkQuadrilateralCell_txx -#define _itkQuadrilateralCell_txx +#ifndef __itkQuadrilateralCell_txx +#define __itkQuadrilateralCell_txx #include "itkQuadrilateralCell.h" namespace itk @@ -92,46 +92,45 @@ QuadrilateralCell< TCellInterface > switch (dimension) { case 0: - { - VertexAutoPointer vertexPointer; - if( this->GetVertex(featureId,vertexPointer) ) - { - TransferAutoPointer(cellPointer,vertexPointer); - return true; - } - else { - cellPointer.Reset(); - return false; + VertexAutoPointer vertexPointer; + if( this->GetVertex(featureId,vertexPointer) ) + { + TransferAutoPointer(cellPointer,vertexPointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - break; - } case 1: - { - EdgeAutoPointer edgePointer; - if( this->GetEdge(featureId,edgePointer) ) { - TransferAutoPointer(cellPointer,edgePointer); - return true; + EdgeAutoPointer edgePointer; + if( this->GetEdge(featureId,edgePointer) ) + { + TransferAutoPointer(cellPointer,edgePointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - else + + default: { cellPointer.Reset(); return false; } - break; - } - - default: - { - cellPointer.Reset(); - return false; - } } return false; } - /** * Standard CellInterface: * Set the point id list used by the cell. It is assumed that the given @@ -144,7 +143,7 @@ QuadrilateralCell< TCellInterface > ::SetPointIds(PointIdConstIterator first) { PointIdConstIterator ii(first); - for(unsigned int i=0; i < Self::NumberOfPoints ; ++i) + for(unsigned int i=0; i < Self::NumberOfPoints; ++i) { m_PointIds[i] = *ii++; } diff --git a/Utilities/ITK/Code/Common/itkQuadrilateralCellTopology.cxx b/Utilities/ITK/Code/Common/itkQuadrilateralCellTopology.cxx index 27a53002bb..f0856778c2 100644 --- a/Utilities/ITK/Code/Common/itkQuadrilateralCellTopology.cxx +++ b/Utilities/ITK/Code/Common/itkQuadrilateralCellTopology.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadrilateralCellTopology.cxx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:24 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:08:12 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -28,9 +28,6 @@ const int QuadrilateralCellTopology ::m_Edges[4][2] = { {0,1}, {1,2}, {2,3}, {3,0} }; - - - QuadrilateralCellTopology ::QuadrilateralCellTopology() { @@ -41,6 +38,4 @@ QuadrilateralCellTopology { } - } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkQuadrilateralCellTopology.h b/Utilities/ITK/Code/Common/itkQuadrilateralCellTopology.h index 2a12a91ad5..b3af69da80 100644 --- a/Utilities/ITK/Code/Common/itkQuadrilateralCellTopology.h +++ b/Utilities/ITK/Code/Common/itkQuadrilateralCellTopology.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadrilateralCellTopology.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:24 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:08:20 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -33,15 +33,14 @@ namespace itk class ITKCommon_EXPORT QuadrilateralCellTopology { -protected: - - /** Quadrilateral topology data. */ - static const int m_Edges[4][2]; - public: QuadrilateralCellTopology(); ~QuadrilateralCellTopology(); +protected: + /** Quadrilateral topology data. */ + static const int m_Edges[4][2]; + }; } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkQuaternionOrientationAdapter.h b/Utilities/ITK/Code/Common/itkQuaternionOrientationAdapter.h index e90be51e16..2910ded9db 100644 --- a/Utilities/ITK/Code/Common/itkQuaternionOrientationAdapter.h +++ b/Utilities/ITK/Code/Common/itkQuaternionOrientationAdapter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuaternionOrientationAdapter.h,v $ Language: C++ - Date: $Date: 2005-10-31 17:52:09 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:08:22 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -28,45 +28,44 @@ namespace itk /** \class QuaternionOrientationAdapter * \brief converts QuaternionOrientation flags to/from direction cosines */ -namespace QuaternionOrientationAdapterClasses - { - typedef QuaternionRigidTransform<double> TransformType; - typedef TransformType::Pointer TransformPointerType; - } -template <int Dimension> +namespace QuaternionOrientationAdapterClasses { +typedef QuaternionRigidTransform<double> TransformType; +typedef TransformType::Pointer TransformPointerType; +} +template <int VDimension> class QuaternionOrientationAdapter : - public OrientationAdapterBase<QuaternionOrientationAdapterClasses::TransformPointerType,Dimension> + public OrientationAdapterBase<QuaternionOrientationAdapterClasses::TransformPointerType,VDimension> { public: /** typedef for superclass */ typedef QuaternionOrientationAdapter Self; - typedef OrientationAdapterBase<QuaternionOrientationAdapterClasses::TransformPointerType,Dimension> - SuperClass; + typedef OrientationAdapterBase<QuaternionOrientationAdapterClasses::TransformPointerType,VDimension> + SuperClass; typedef QuaternionRigidTransform<double> OrientationRootType; - typedef QuaternionOrientationAdapterClasses::TransformPointerType OrientationType; + typedef QuaternionOrientationAdapterClasses::TransformPointerType + OrientationType; /** The dimension of the input image must be 3. */ itkConceptMacro(DimensionShouldBe3, - (Concept::SameDimension<Dimension,3>)); + (Concept::SameDimension<VDimension,3>)); /** typedef for direction cosines */ typedef typename SuperClass::DirectionType DirectionType; /** convert from direction cosines. */ virtual OrientationType FromDirectionCosines(const DirectionType &Dir) - { + { OrientationType q = OrientationRootType::New(); q->SetMatrix(Dir); return q; - } + } /** convert to direction cosines. */ virtual DirectionType ToDirectionCosines(const OrientationType &Or) - { + { return Or->GetMatrix(); - } - + } }; } // namespace itk diff --git a/Utilities/ITK/Code/Common/itkQuaternionRigidTransform.h b/Utilities/ITK/Code/Common/itkQuaternionRigidTransform.h index 68ffb27800..d30c343982 100644 --- a/Utilities/ITK/Code/Common/itkQuaternionRigidTransform.h +++ b/Utilities/ITK/Code/Common/itkQuaternionRigidTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuaternionRigidTransform.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-03-03 15:08:23 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,8 @@ namespace itk { -/** \brief QuaternionRigidTransform of a vector space (e.g. space coordinates). +/** \class QuaternionRigidTransform + * \brief QuaternionRigidTransform of a vector space (e.g. space coordinates). * * This transform applies a rotation and translation to the space given * a quaternion and a 3D translation. Rotation is about a user specified center. @@ -78,7 +79,7 @@ public: typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; - typedef typename Superclass::OutputCovariantVectorType + typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType; typedef typename Superclass::MatrixType MatrixType; typedef typename Superclass::InverseMatrixType InverseMatrixType; @@ -98,7 +99,7 @@ public: /** Get the rotation from an QuaternionRigidTransform. * This method returns the value of the rotation of the - * QuaternionRigidTransform. **/ + * QuaternionRigidTransform. */ const VnlQuaternionType & GetRotation(void) const { return m_Rotation; } @@ -133,7 +134,7 @@ protected: void ComputeMatrixParameters(); void SetVarRotation(const VnlQuaternionType & rotation) - { m_Rotation = rotation; }; + { m_Rotation = rotation; } const InverseMatrixType & GetInverseMatrix( void ) const; diff --git a/Utilities/ITK/Code/Common/itkQuaternionRigidTransform.txx b/Utilities/ITK/Code/Common/itkQuaternionRigidTransform.txx index f6cb753602..e2d9af67b0 100644 --- a/Utilities/ITK/Code/Common/itkQuaternionRigidTransform.txx +++ b/Utilities/ITK/Code/Common/itkQuaternionRigidTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuaternionRigidTransform.txx,v $ Language: C++ - Date: $Date: 2006-08-09 04:35:31 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-03-03 15:08:28 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkQuaternionRigidTransform_txx -#define _itkQuaternionRigidTransform_txx +#ifndef __itkQuaternionRigidTransform_txx +#define __itkQuaternionRigidTransform_txx #include "itkQuaternionRigidTransform.h" @@ -42,8 +42,6 @@ QuaternionRigidTransform( unsigned int outputSpaceDimension, m_Rotation = VnlQuaternionType(0,0,0,1); // axis * vcl_sin(t/2), vcl_cos(t/2) } - - // Constructor with explicit arguments template<class TScalarType> QuaternionRigidTransform<TScalarType>:: @@ -124,8 +122,6 @@ QuaternionRigidTransform<TScalarType> } - - // Set Parameters template <class TScalarType> const diff --git a/Utilities/ITK/Code/Common/itkRGBAPixel.h b/Utilities/ITK/Code/Common/itkRGBAPixel.h index c7a56e1d8e..e167cb30f7 100644 --- a/Utilities/ITK/Code/Common/itkRGBAPixel.h +++ b/Utilities/ITK/Code/Common/itkRGBAPixel.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBAPixel.h,v $ Language: C++ - Date: $Date: 2008-07-02 22:09:47 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-03-12 01:11:14 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -53,14 +53,22 @@ class RGBAPixel: public FixedArray<TComponent,4> { public: /** Standard class typedefs. */ - typedef RGBAPixel Self; + typedef RGBAPixel Self; typedef FixedArray<TComponent, 4> Superclass; /** Dimension of the vector space. */ +#if defined(__BORLANDC__) + enum {Dimension = 4}; +#else itkStaticConstMacro(Dimension, unsigned int, 4); +#endif /** Length of the pixel. */ +#if defined(__BORLANDC__) + enum {Length = 4}; +#else itkStaticConstMacro(Length, unsigned int, 4); +#endif /** Convenience typedefs. */ typedef FixedArray<TComponent, 4> BaseArray; @@ -71,7 +79,7 @@ public: /** Default constructor has nothing to do. */ RGBAPixel() {this->Fill(0);} RGBAPixel (const ComponentType& r) - { this->Fill(r) ;} + { this->Fill(r);} /** Pass-through constructor for the Array base class. */ RGBAPixel(const Self& r): BaseArray(r) {} @@ -91,12 +99,12 @@ public: /** Return the value for the Nth component. */ ComponentType GetScalarValue() const { - return static_cast<ComponentType> (vcl_sqrt( - static_cast<double>(this->operator[](0)) * static_cast<double>(this->operator[](0)) + - static_cast<double>(this->operator[](1)) * static_cast<double>(this->operator[](1)) + - static_cast<double>(this->operator[](2)) * static_cast<double>(this->operator[](2)))); + return static_cast<ComponentType> (vcl_sqrt( + static_cast<double>(this->operator[](0)) * static_cast<double>(this->operator[](0)) + + static_cast<double>(this->operator[](1)) * static_cast<double>(this->operator[](1)) + + static_cast<double>(this->operator[](2)) * static_cast<double>(this->operator[](2)))); } - + /** Set the Nth component to v. */ void SetNthComponent(int c, const ComponentType& v) { this->operator[](c) = v; } diff --git a/Utilities/ITK/Code/Common/itkRGBAPixel.txx b/Utilities/ITK/Code/Common/itkRGBAPixel.txx index cd4b7444e6..ac5340eb5a 100644 --- a/Utilities/ITK/Code/Common/itkRGBAPixel.txx +++ b/Utilities/ITK/Code/Common/itkRGBAPixel.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBAPixel.txx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:24 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-03 15:08:36 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,15 +14,15 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkRGBAPixel_txx -#define _itkRGBAPixel_txx +#ifndef __itkRGBAPixel_txx +#define __itkRGBAPixel_txx #include "itkRGBAPixel.h" #include "itkNumericTraits.h" namespace itk { -/* +/** * Assignment Operator */ template<class T> @@ -74,7 +74,7 @@ operator<<(std::ostream& os,const RGBAPixel<TComponent> & c ) os << c[0] << " "; os << c[1] << " "; os << c[2] << " "; - os << c[3] ; + os << c[3]; return os; } diff --git a/Utilities/ITK/Code/Common/itkRGBPixel.h b/Utilities/ITK/Code/Common/itkRGBPixel.h index 4b5208c1be..094d12e882 100644 --- a/Utilities/ITK/Code/Common/itkRGBPixel.h +++ b/Utilities/ITK/Code/Common/itkRGBPixel.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBPixel.h,v $ Language: C++ - Date: $Date: 2008-07-02 22:00:57 $ - Version: $Revision: 1.41 $ + Date: $Date: 2009-03-12 01:11:16 $ + Version: $Revision: 1.43 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,18 +52,28 @@ class RGBPixel: public FixedArray<TComponent,3> { public: /** Standard class typedefs. */ - typedef RGBPixel Self; + typedef RGBPixel Self; typedef FixedArray<TComponent, 3> Superclass; + /** Convenience typedefs. */ + typedef FixedArray<TComponent, 3> BaseArray; + /** Dimension of the vector space. */ +#if defined(__BORLANDC__) + enum {Dimension = 3}; +#else itkStaticConstMacro(Dimension, unsigned int, 3); +#endif + + /** Length of the pixel. */ +#if defined(__BORLANDC__) + enum {Length = 3}; +#else itkStaticConstMacro(Length, unsigned int, 3); +#endif - /** Convenience typedefs. */ - typedef FixedArray<TComponent, 3> BaseArray; - /** Define the component type. */ - typedef TComponent ComponentType; + typedef TComponent ComponentType; typedef typename Superclass::ValueType ValueType; /** Default constructor has nothing to do */ @@ -106,10 +116,10 @@ public: /** Return the value for the Nth component. */ ComponentType GetScalarValue() const { - return static_cast<ComponentType> (vcl_sqrt( - static_cast<double>(this->operator[](0)) * static_cast<double>(this->operator[](0)) + - static_cast<double>(this->operator[](1)) * static_cast<double>(this->operator[](1)) + - static_cast<double>(this->operator[](2)) * static_cast<double>(this->operator[](2)))); + return static_cast<ComponentType> (vcl_sqrt( + static_cast<double>(this->operator[](0)) * static_cast<double>(this->operator[](0)) + + static_cast<double>(this->operator[](1)) * static_cast<double>(this->operator[](1)) + + static_cast<double>(this->operator[](2)) * static_cast<double>(this->operator[](2)))); } /** Set the Nth component to v. */ diff --git a/Utilities/ITK/Code/Common/itkRGBPixel.txx b/Utilities/ITK/Code/Common/itkRGBPixel.txx index d0141b5bb4..594a62a614 100644 --- a/Utilities/ITK/Code/Common/itkRGBPixel.txx +++ b/Utilities/ITK/Code/Common/itkRGBPixel.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBPixel.txx,v $ Language: C++ - Date: $Date: 2008-01-25 14:48:22 $ - Version: $Revision: 1.28 $ + Date: $Date: 2009-03-03 15:08:40 $ + Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,15 +14,15 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkRGBPixel_txx -#define _itkRGBPixel_txx +#ifndef __itkRGBPixel_txx +#define __itkRGBPixel_txx #include "itkRGBPixel.h" #include "itkNumericTraits.h" namespace itk { -/* +/** * Assigment from a plain array */ template<class T> @@ -52,9 +52,6 @@ RGBPixel<T> return result; } - - - /** * Returns a temporary copy of a vector */ @@ -87,9 +84,6 @@ RGBPixel<T> } return *this; } - - - /** * Returns a temporary copy of a vector @@ -106,10 +100,6 @@ RGBPixel<T> return *this; } - - - - /** * Returns a temporary copy of a vector */ @@ -163,9 +153,7 @@ RGBPixel<T> return true; } - - -/* +/** * Compute luminance */ template<class T> @@ -180,9 +168,6 @@ RGBPixel<T> return static_cast<ComponentType>( luminance ); } - - - /** * Print content to an ostream */ @@ -192,7 +177,7 @@ operator<<(std::ostream& os,const RGBPixel<TComponent> & c ) { os << static_cast<typename NumericTraits<TComponent>::PrintType>(c[0]) << " "; os << static_cast<typename NumericTraits<TComponent>::PrintType>(c[1]) << " "; - os << static_cast<typename NumericTraits<TComponent>::PrintType>(c[2]) ; + os << static_cast<typename NumericTraits<TComponent>::PrintType>(c[2]); return os; } diff --git a/Utilities/ITK/Code/Common/itkRGBToLuminanceImageAdaptor.h b/Utilities/ITK/Code/Common/itkRGBToLuminanceImageAdaptor.h index e254f48333..c0deda4992 100755 --- a/Utilities/ITK/Code/Common/itkRGBToLuminanceImageAdaptor.h +++ b/Utilities/ITK/Code/Common/itkRGBToLuminanceImageAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBToLuminanceImageAdaptor.h,v $ Language: C++ - Date: $Date: 2004-05-10 00:16:11 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-03-03 15:08:44 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -74,12 +74,12 @@ class ITK_EXPORT RGBToLuminanceImageAdaptor : public { public: /** Standard class typedefs. */ - typedef RGBToLuminanceImageAdaptor Self; + typedef RGBToLuminanceImageAdaptor Self; typedef ImageAdaptor<TImage, Accessor::RGBToLuminancePixelAccessor< typename TImage::PixelType, TOutputPixelType> > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -87,11 +87,11 @@ public: /** Run-time type information (and related methods). */ itkTypeMacro( RGBToLuminanceImageAdaptor, ImageAdaptor ); - protected: +protected: RGBToLuminanceImageAdaptor() {} virtual ~RGBToLuminanceImageAdaptor() {} - private: +private: RGBToLuminanceImageAdaptor(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkRGBToVectorImageAdaptor.h b/Utilities/ITK/Code/Common/itkRGBToVectorImageAdaptor.h index 45d7e08d27..f5a9eba1cf 100644 --- a/Utilities/ITK/Code/Common/itkRGBToVectorImageAdaptor.h +++ b/Utilities/ITK/Code/Common/itkRGBToVectorImageAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBToVectorImageAdaptor.h,v $ Language: C++ - Date: $Date: 2003-12-08 14:08:20 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:08:45 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,13 +40,13 @@ class ITK_EXPORT RGBToVectorImageAdaptor : public { public: /** Standard class typedefs. */ - typedef RGBToVectorImageAdaptor Self; + typedef RGBToVectorImageAdaptor Self; typedef ImageAdaptor<TImage, Accessor::RGBToVectorPixelAccessor< typename TImage::PixelType::ComponentType > > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -56,15 +56,15 @@ public: /** PixelContainer typedef support. Used to construct a container for * the pixel data. */ - typedef typename Superclass::PixelContainer PixelContainer; - typedef typename Superclass::PixelContainerPointer PixelContainerPointer; + typedef typename Superclass::PixelContainer PixelContainer; + typedef typename Superclass::PixelContainerPointer PixelContainerPointer; typedef typename Superclass::PixelContainerConstPointer PixelContainerConstPointer; - protected: +protected: RGBToVectorImageAdaptor() {} virtual ~RGBToVectorImageAdaptor() {} - private: +private: RGBToVectorImageAdaptor(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkRGBToVectorPixelAccessor.h b/Utilities/ITK/Code/Common/itkRGBToVectorPixelAccessor.h index ede8b0308e..0142f9d30c 100644 --- a/Utilities/ITK/Code/Common/itkRGBToVectorPixelAccessor.h +++ b/Utilities/ITK/Code/Common/itkRGBToVectorPixelAccessor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBToVectorPixelAccessor.h,v $ Language: C++ - Date: $Date: 2003-12-12 14:20:58 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:08:46 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -76,4 +76,3 @@ private: } // end namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkRealTimeClock.cxx b/Utilities/ITK/Code/Common/itkRealTimeClock.cxx index a4e384d39e..c9e38097a4 100644 --- a/Utilities/ITK/Code/Common/itkRealTimeClock.cxx +++ b/Utilities/ITK/Code/Common/itkRealTimeClock.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRealTimeClock.cxx,v $ Language: C++ - Date: $Date: 2005-11-29 14:51:11 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:08:47 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -89,12 +89,12 @@ RealTimeClock::RealTimeClock():m_Frequency(1) static_cast< TimeStampType >( (__int64)tick.QuadPart ) / this->m_Frequency; - this->m_Origin += this->m_Difference; + this->m_Origin += this->m_Difference; #else - this->m_Frequency = 1e6;; + this->m_Frequency = 1e6; #endif // defined(WIN32) || defined(_WIN32) } diff --git a/Utilities/ITK/Code/Common/itkRealTimeClock.h b/Utilities/ITK/Code/Common/itkRealTimeClock.h index 2ec220ac83..2d6b1c79db 100644 --- a/Utilities/ITK/Code/Common/itkRealTimeClock.h +++ b/Utilities/ITK/Code/Common/itkRealTimeClock.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRealTimeClock.h,v $ Language: C++ - Date: $Date: 2006-05-10 20:27:16 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:08:48 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,21 +26,21 @@ namespace itk { /** \class RealTimeClock -* \brief The RealTimeClock provides a timestamp from a real-time clock -* -* This class represents a real-time clock object -* and provides a timestamp in platform-independent format. -* -* \author Hee-Su Kim, Compute Science Dept. Kyungpook National University, -* ISIS Center, Georgetown University. -*/ + * \brief The RealTimeClock provides a timestamp from a real-time clock + * + * This class represents a real-time clock object + * and provides a timestamp in platform-independent format. + * + * \author Hee-Su Kim, Compute Science Dept. Kyungpook National University, + * ISIS Center, Georgetown University. + */ class ITKCommon_EXPORT RealTimeClock : public Object { public: - typedef RealTimeClock Self; - typedef Object Superclass; - typedef SmartPointer< Self > Pointer; + typedef RealTimeClock Self; + typedef Object Superclass; + typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** Method for defining the name of the class */ diff --git a/Utilities/ITK/Code/Common/itkRedPixelAccessor.h b/Utilities/ITK/Code/Common/itkRedPixelAccessor.h index 0bda373e18..816908512d 100644 --- a/Utilities/ITK/Code/Common/itkRedPixelAccessor.h +++ b/Utilities/ITK/Code/Common/itkRedPixelAccessor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRedPixelAccessor.h,v $ Language: C++ - Date: $Date: 2007-04-16 23:35:10 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-03 15:08:48 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,20 +59,16 @@ public: { return input.GetRed(); } bool operator!=( const Self &) const - { + { return false; - } + } bool operator==( const Self & other ) const - { + { return !(*this != other); - } + } }; - - } // end namespace itk - #endif - diff --git a/Utilities/ITK/Code/Common/itkRegion.cxx b/Utilities/ITK/Code/Common/itkRegion.cxx index f274677fcc..0f497b8537 100644 --- a/Utilities/ITK/Code/Common/itkRegion.cxx +++ b/Utilities/ITK/Code/Common/itkRegion.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegion.cxx,v $ Language: C++ - Date: $Date: 2004-04-03 13:05:43 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-03 15:08:49 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,4 +51,3 @@ Region } } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkRegion.h b/Utilities/ITK/Code/Common/itkRegion.h index 1fbe41c6df..6f912975d2 100644 --- a/Utilities/ITK/Code/Common/itkRegion.h +++ b/Utilities/ITK/Code/Common/itkRegion.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegion.h,v $ Language: C++ - Date: $Date: 2007-03-19 12:33:47 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-03-03 15:08:51 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -91,4 +91,3 @@ private: } // end namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkResourceProbesCollectorBase.txx b/Utilities/ITK/Code/Common/itkResourceProbesCollectorBase.txx index b2f1a2f2e9..74b0611992 100644 --- a/Utilities/ITK/Code/Common/itkResourceProbesCollectorBase.txx +++ b/Utilities/ITK/Code/Common/itkResourceProbesCollectorBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkResourceProbesCollectorBase.txx,v $ Language: C++ - Date: $Date: 2008-11-10 13:54:35 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:08:55 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,8 +95,6 @@ ResourceProbesCollectorBase<TProbe> } - - template <class TProbe> void ResourceProbesCollectorBase<TProbe> diff --git a/Utilities/ITK/Code/Common/itkRigid2DTransform.h b/Utilities/ITK/Code/Common/itkRigid2DTransform.h index 10265e4303..49a23cde30 100644 --- a/Utilities/ITK/Code/Common/itkRigid2DTransform.h +++ b/Utilities/ITK/Code/Common/itkRigid2DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRigid2DTransform.h,v $ Language: C++ - Date: $Date: 2009-01-14 18:39:05 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -107,6 +107,11 @@ public: typedef typename Superclass::InputPointType InputPointType; typedef typename Superclass::OutputPointType OutputPointType; + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; + /** * Set the rotation Matrix of a Rigid2D Transform * @@ -203,6 +208,12 @@ public: */ void CloneInverseTo( Pointer & newinverse ) const; + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + /** * This method creates and returns a new Rigid2DTransform object * which has the same parameters. diff --git a/Utilities/ITK/Code/Common/itkRigid2DTransform.txx b/Utilities/ITK/Code/Common/itkRigid2DTransform.txx index cef09b2f02..6b333bc936 100644 --- a/Utilities/ITK/Code/Common/itkRigid2DTransform.txx +++ b/Utilities/ITK/Code/Common/itkRigid2DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRigid2DTransform.txx,v $ Language: C++ - Date: $Date: 2008-12-19 16:34:40 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -112,7 +112,7 @@ Rigid2DTransform<TScalarType> m_Angle = -m_Angle; } - if(r[1][0]-sin(m_Angle) > 0.000001) + if(r[1][0]-vcl_sin(m_Angle) > 0.000001) { itkWarningMacro("Bad Rotation Matrix " << this->GetMatrix() ); } @@ -139,9 +139,35 @@ Rigid2DTransform<TScalarType>:: CloneInverseTo( Pointer & result ) const { result = New(); - result->SetCenter( this->GetCenter() ); // inverse have the same center - result->SetAngle( -this->GetAngle() ); - result->SetTranslation( -( this->GetInverseMatrix() * this->GetTranslation() ) ); + this->GetInverse(result.GetPointer()); +} + +// return an inverse transformation +template<class TScalarType> +bool +Rigid2DTransform<TScalarType>:: +GetInverse( Self* inverse) const +{ + if(!inverse) + { + return false; + } + + inverse->SetCenter( this->GetCenter() ); // inverse have the same center + inverse->SetAngle( -this->GetAngle() ); + inverse->SetTranslation( -( this->GetInverseMatrix() * this->GetTranslation() ) ); + + return true; +} + +// Return an inverse of this transform +template<class TScalarType> +typename Rigid2DTransform<TScalarType>::InverseTransformBasePointer +Rigid2DTransform<TScalarType> +::GetInverseTransform() const +{ + Pointer inv = New(); + return GetInverse(inv) ? inv.GetPointer() : NULL; } // Create and return a clone of the transformation diff --git a/Utilities/ITK/Code/Common/itkRigid3DPerspectiveTransform.h b/Utilities/ITK/Code/Common/itkRigid3DPerspectiveTransform.h index f262b23b63..713733cad5 100644 --- a/Utilities/ITK/Code/Common/itkRigid3DPerspectiveTransform.h +++ b/Utilities/ITK/Code/Common/itkRigid3DPerspectiveTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRigid3DPerspectiveTransform.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-03-03 15:08:57 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -91,7 +91,7 @@ public: typedef vnl_quaternion<TScalarType> VnlQuaternionType; /** Versor type. */ - typedef Versor<TScalarType> VersorType; + typedef Versor<TScalarType> VersorType; typedef typename VersorType::VectorType AxisType; typedef typename VersorType::ValueType AngleType; @@ -182,19 +182,15 @@ private: /** Matrix representation of the rotation. */ MatrixType m_RotationMatrix; - - /** Fixed offset*/ + /** Fixed offset */ OffsetType m_FixedOffset; /** Center of rotation */ InputPointType m_CenterOfRotation; - }; //class Rigid3DPerspectiveTransform: - - } // namespace itk // Define instantiation macro for this template. diff --git a/Utilities/ITK/Code/Common/itkRigid3DPerspectiveTransform.txx b/Utilities/ITK/Code/Common/itkRigid3DPerspectiveTransform.txx index 7954bbae12..c49e7d1a0a 100644 --- a/Utilities/ITK/Code/Common/itkRigid3DPerspectiveTransform.txx +++ b/Utilities/ITK/Code/Common/itkRigid3DPerspectiveTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRigid3DPerspectiveTransform.txx,v $ Language: C++ - Date: $Date: 2007-12-23 17:59:29 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-03-03 15:08:59 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkRigid3DPerspectiveTransform_txx -#define _itkRigid3DPerspectiveTransform_txx +#ifndef __itkRigid3DPerspectiveTransform_txx +#define __itkRigid3DPerspectiveTransform_txx #include "itkRigid3DPerspectiveTransform.h" @@ -116,9 +116,6 @@ Rigid3DPerspectiveTransform<TScalarType> } - - - // Set Parameters template <class TScalarType> const typename Rigid3DPerspectiveTransform<TScalarType>::ParametersType & @@ -141,8 +138,6 @@ Rigid3DPerspectiveTransform<TScalarType> return this->m_Parameters; } - - // Set rotation template<class TScalarType> void @@ -213,8 +208,6 @@ TransformPoint(const InputPointType &point) const return result; } - - // Transform a point template<class TScalarType> void diff --git a/Utilities/ITK/Code/Common/itkRigid3DTransform.h b/Utilities/ITK/Code/Common/itkRigid3DTransform.h index c8e48ca05f..a6e6ceecad 100644 --- a/Utilities/ITK/Code/Common/itkRigid3DTransform.h +++ b/Utilities/ITK/Code/Common/itkRigid3DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRigid3DTransform.h,v $ Language: C++ - Date: $Date: 2007-02-13 21:46:04 $ - Version: $Revision: 1.38 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.40 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,8 @@ namespace itk { -/** \brief Rigid3DTransform of a vector space (e.g. space coordinates) +/** \class Rigid3DTransform + * \brief Rigid3DTransform of a vector space (e.g. space coordinates) * * This transform applies a rotation and translation in 3D space. * The transform is specified as a rotation matrix around a arbitrary center @@ -74,9 +75,9 @@ public: typedef typename Superclass::InputVectorType InputVectorType; typedef typename Superclass::OutputVectorType OutputVectorType; typedef typename Superclass::InputCovariantVectorType - InputCovariantVectorType; + InputCovariantVectorType; typedef typename Superclass::OutputCovariantVectorType - OutputCovariantVectorType; + OutputCovariantVectorType; typedef typename Superclass::InputVnlVectorType InputVnlVectorType; typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; typedef typename Superclass::InputPointType InputPointType; @@ -87,6 +88,11 @@ public: typedef typename Superclass::TranslationType TranslationType; typedef typename Superclass::OffsetType OffsetType; + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; + /** Set the transformation from a container of parameters * This is typically used by optimizers. * There are 12 parameters. The first 9 represents the rotation @@ -113,9 +119,9 @@ public: * Rigid3DTransform. * * \deprecated Use GetMatrix instead - **/ - const MatrixType & GetRotationMatrix() - { return this->GetMatrix(); } + */ + const MatrixType & GetRotationMatrix() + { return this->GetMatrix(); } /** * Set the rotation Matrix of a Rigid3D Transform @@ -126,7 +132,7 @@ public: * * \deprecated Use SetMatrix instead * - **/ + */ virtual void SetRotationMatrix(const MatrixType & matrix) { this->SetMatrix(matrix); } @@ -136,9 +142,15 @@ public: * This method modifies self to include a translation of the * origin. The translation is precomposed with self if pre is * true, and postcomposed otherwise. - **/ + */ void Translate(const OffsetType & offset, bool pre=false); + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + /** * Back transform by an affine transformation * @@ -149,7 +161,7 @@ public: * \deprecated Please use GetInverseTransform and then call the forward * transform using the result. * - **/ + */ InputPointType BackTransform(const OutputPointType &point ) const; InputVectorType BackTransform(const OutputVectorType @@ -159,10 +171,10 @@ public: InputCovariantVectorType BackTransform(const OutputCovariantVectorType &vector) const; - /** - * Utility function to test if a matrix is orthogonal within a specified - * tolerance - */ + /** + * Utility function to test if a matrix is orthogonal within a specified + * tolerance + */ bool MatrixIsOrthogonal( const MatrixType & matrix, double tol = 1e-10 ); protected: @@ -175,7 +187,7 @@ protected: /** * Print contents of an Rigid3DTransform - **/ + */ void PrintSelf(std::ostream &os, Indent indent) const; private: diff --git a/Utilities/ITK/Code/Common/itkRigid3DTransform.txx b/Utilities/ITK/Code/Common/itkRigid3DTransform.txx index 8cf99c3ce5..1c627227d6 100644 --- a/Utilities/ITK/Code/Common/itkRigid3DTransform.txx +++ b/Utilities/ITK/Code/Common/itkRigid3DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRigid3DTransform.txx,v $ Language: C++ - Date: $Date: 2008-12-19 16:34:40 $ - Version: $Revision: 1.36 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.38 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkRigid3DTransform_txx -#define _itkRigid3DTransform_txx +#ifndef __itkRigid3DTransform_txx +#define __itkRigid3DTransform_txx #include "itkRigid3DTransform.h" @@ -79,7 +79,7 @@ Rigid3DTransform<TScalarType> matrix.GetVnlMatrix() * matrix.GetTranspose(); if( !test.is_identity( tolerance ) ) - { + { return false; } @@ -95,7 +95,7 @@ Rigid3DTransform<TScalarType> { const double tolerance = 1e-10; if( !this->MatrixIsOrthogonal( matrix, tolerance ) ) - { + { itkExceptionMacro( << "Attempting to set a non-orthogonal rotation matrix" ); } @@ -132,7 +132,7 @@ Rigid3DTransform<TScalarType> const double tolerance = 1e-10; if( !this->MatrixIsOrthogonal( matrix, tolerance ) ) - { + { itkExceptionMacro( << "Attempting to set a non-orthogonal rotation matrix" ); } @@ -161,6 +161,24 @@ Translate(const OffsetType &offset, bool) this->ComputeTranslation(); } +// Get an inverse of this transform +template<class TScalarType> +bool +Rigid3DTransform<TScalarType> +::GetInverse(Self* inverse) const +{ + return this->Superclass::GetInverse(inverse); +} + +// Return an inverse of this transform +template<class TScalarType> +typename Rigid3DTransform<TScalarType>::InverseTransformBasePointer +Rigid3DTransform<TScalarType> +::GetInverseTransform() const +{ + Pointer inv = New(); + return this->GetInverse(inv) ? inv.GetPointer() : NULL; +} // Back transform a point template<class TScalarType> @@ -168,7 +186,8 @@ typename Rigid3DTransform<TScalarType>::InputPointType Rigid3DTransform<TScalarType>:: BackTransform(const OutputPointType &point) const { - itkWarningMacro(<<"BackTransform(): This method is slated to be removed from ITK. Instead, please use GetInverse() to generate an inverse transform and then perform the transform using that inverted transform."); + itkWarningMacro(<< "BackTransform(): This method is slated to be removed from ITK." + << "Instead, please use GetInverse() to generate an inverse transform and then perform the transform using that inverted transform."); return this->GetInverseMatrix() * (point - this->GetOffset()); } @@ -178,7 +197,8 @@ typename Rigid3DTransform<TScalarType>::InputVectorType Rigid3DTransform<TScalarType>:: BackTransform(const OutputVectorType &vect ) const { - itkWarningMacro(<<"BackTransform(): This method is slated to be removed from ITK. Instead, please use GetInverse() to generate an inverse transform and then perform the transform using that inverted transform."); + itkWarningMacro(<<"BackTransform(): This method is slated to be removed from ITK." + << "Instead, please use GetInverse() to generate an inverse transform and then perform the transform using that inverted transform."); return this->GetInverseMatrix() * vect; } @@ -188,7 +208,8 @@ typename Rigid3DTransform<TScalarType>::InputVnlVectorType Rigid3DTransform<TScalarType>:: BackTransform(const OutputVnlVectorType &vect ) const { - itkWarningMacro(<<"BackTransform(): This method is slated to be removed from ITK. Instead, please use GetInverse() to generate an inverse transform and then perform the transform using that inverted transform."); + itkWarningMacro(<<"BackTransform(): This method is slated to be removed from ITK." + << " Instead, please use GetInverse() to generate an inverse transform and then perform the transform using that inverted transform."); return this->GetInverseMatrix() * vect; } @@ -199,7 +220,8 @@ typename Rigid3DTransform<TScalarType>::InputCovariantVectorType Rigid3DTransform<TScalarType>:: BackTransform(const OutputCovariantVectorType &vect) const { - itkWarningMacro(<<"BackTransform(): This method is slated to be removed from ITK. Instead, please use GetInverse() to generate an inverse transform and then perform the transform using that inverted transform."); + itkWarningMacro(<<"BackTransform(): This method is slated to be removed from ITK." + << " Instead, please use GetInverse() to generate an inverse transform and then perform the transform using that inverted transform."); return this->GetMatrix() * vect; } diff --git a/Utilities/ITK/Code/Common/itkRootTreeIterator.h b/Utilities/ITK/Code/Common/itkRootTreeIterator.h index b2b880220e..724b3c83f2 100644 --- a/Utilities/ITK/Code/Common/itkRootTreeIterator.h +++ b/Utilities/ITK/Code/Common/itkRootTreeIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRootTreeIterator.h,v $ Language: C++ - Date: $Date: 2004-12-11 20:29:19 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:09:06 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,7 +19,7 @@ #include <itkTreeIteratorBase.h> -namespace itk{ +namespace itk { template <class TTreeType> class RootTreeIterator : public TreeIteratorBase<TTreeType> @@ -27,9 +27,9 @@ class RootTreeIterator : public TreeIteratorBase<TTreeType> public: /** Typedefs */ - typedef TreeIteratorBase<TTreeType> Superclass; - typedef TTreeType TreeType; - typedef typename TTreeType::ValueType ValueType; + typedef TreeIteratorBase<TTreeType> Superclass; + typedef TTreeType TreeType; + typedef typename TTreeType::ValueType ValueType; typedef typename Superclass::TreeNodeType TreeNodeType; /** Constructor */ diff --git a/Utilities/ITK/Code/Common/itkSTLConstContainerAdaptor.h b/Utilities/ITK/Code/Common/itkSTLConstContainerAdaptor.h index 735cd6164a..aa11416acb 100644 --- a/Utilities/ITK/Code/Common/itkSTLConstContainerAdaptor.h +++ b/Utilities/ITK/Code/Common/itkSTLConstContainerAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSTLConstContainerAdaptor.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:24 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:09:06 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,22 +58,17 @@ private: public: - STLConstContainerAdaptor(AdapteeType & adaptee) - : m_AdapteeRef(adaptee) - {} + STLConstContainerAdaptor(AdapteeType & adaptee) : m_AdapteeRef(adaptee) {} - STLConstContainerAdaptor(AdapteeType * adaptee) - : m_AdapteeRef(*adaptee) - {} + STLConstContainerAdaptor(AdapteeType * adaptee) : m_AdapteeRef(*adaptee) {} TargetType & GetSTLConstContainerRef() - { + { return m_AdapteeRef.CastToSTLConstContainer(); - } + } }; - } // end namespace itk #endif diff --git a/Utilities/ITK/Code/Common/itkSTLContainerAdaptor.h b/Utilities/ITK/Code/Common/itkSTLContainerAdaptor.h index 57e3784452..083a4c12ae 100644 --- a/Utilities/ITK/Code/Common/itkSTLContainerAdaptor.h +++ b/Utilities/ITK/Code/Common/itkSTLContainerAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSTLContainerAdaptor.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:24 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:09:06 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,15 +22,15 @@ namespace itk { /** \class STLContainerAdaptor -* An adapter object that casts a itk::XxxContainer into std::xxx -* and enables access to the underlying data structure. When the STLContainerAdaptor -* is destroyed, it automatically calls XxxContainer::Modified(). -* Here's a usage example of STLContainerAdaptor -* itk::STLContainerAdaptor<itk::VectorContainer<unsigned long, ElementType>> vecAdaptor(aContainer); -* std::vector<ElementType> & vec = vecAdaptor.GetSTLContainerRef(); -* // do things with vec ... -* // upon return from function, vecAdaptor is destroyed and aContainer is Modified() -*/ + * An adapter object that casts a itk::XxxContainer into std::xxx + * and enables access to the underlying data structure. When the STLContainerAdaptor + * is destroyed, it automatically calls XxxContainer::Modified(). + * Here's a usage example of STLContainerAdaptor + * itk::STLContainerAdaptor<itk::VectorContainer<unsigned long, ElementType>> vecAdaptor(aContainer); + * std::vector<ElementType> & vec = vecAdaptor.GetSTLContainerRef(); + * // do things with vec ... + * // upon return from function, vecAdaptor is destroyed and aContainer is Modified() + */ template<typename TContainer> class STLContainerAdaptor @@ -54,23 +54,19 @@ private: public: - STLContainerAdaptor(AdapteeType & adaptee) - : m_AdapteeRef(adaptee) - {} + STLContainerAdaptor(AdapteeType & adaptee) : m_AdapteeRef(adaptee) {} - STLContainerAdaptor(AdapteeType * adaptee) - : m_AdapteeRef(*adaptee) - {} + STLContainerAdaptor(AdapteeType * adaptee) : m_AdapteeRef(*adaptee) {} ~STLContainerAdaptor() - { + { m_AdapteeRef.Modified(); - } + } TargetType & GetSTLContainerRef() - { + { return m_AdapteeRef.CastToSTLContainer(); - } + } }; diff --git a/Utilities/ITK/Code/Common/itkScalableAffineTransform.h b/Utilities/ITK/Code/Common/itkScalableAffineTransform.h index 986d037bec..c17c17d813 100755 --- a/Utilities/ITK/Code/Common/itkScalableAffineTransform.h +++ b/Utilities/ITK/Code/Common/itkScalableAffineTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalableAffineTransform.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -67,10 +67,8 @@ public: typedef typename Superclass::ScalarType ScalarType; typedef typename Superclass::InputVectorType InputVectorType; typedef typename Superclass::OutputVectorType OutputVectorType; - typedef typename Superclass::InputCovariantVectorType - InputCovariantVectorType; - typedef typename Superclass::OutputCovariantVectorType - OutputCovariantVectorType; + typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; + typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType; typedef typename Superclass::InputVnlVectorType InputVnlVectorType; typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; typedef typename Superclass::InputPointType InputPointType; @@ -80,6 +78,11 @@ public: typedef typename Superclass::CenterType CenterType; typedef typename Superclass::OffsetType OffsetType; typedef typename Superclass::TranslationType TranslationType; + + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; /** Set the transformation to an Identity * @@ -89,25 +92,25 @@ public: /** Set the scale of the transform */ virtual void SetScale( const InputVectorType & scale ); virtual void SetScaleComponent( const InputVectorType & scale ) - { this->SetScale(scale); }; + { this->SetScale(scale); } /** Set the scale of the transform */ virtual void SetScale( const double scale[NDimensions] ); virtual void SetScaleComponent( const double scale[NDimensions] ) - { this->SetScale(scale); }; + { this->SetScale(scale); } - /** Get the scale of the transform*/ - virtual const double * GetScale() const - { return m_Scale; }; + /** Get the scale of the transform */ + virtual const double * GetScale() const + { return m_Scale; } virtual const double * GetScaleComponent() const - { return m_Scale; }; + { return m_Scale; } /** Set the matrix of the transform. The matrix should not include * scale. * * \deprecated use SetMatrix instead */ void SetMatrixComponent(const MatrixType &matrix) - { this->SetMatrix( matrix ); }; + { this->SetMatrix( matrix ); } /** Get matrix of the transform. * * \deprecated use GetMatrix instead */ @@ -118,7 +121,7 @@ public: * * \deprecated use SetTranslation instead. */ void SetOffsetComponent(const OffsetType &offset) - { this->SetTranslation( offset ); }; + { this->SetTranslation( offset ); } /** Get offset of the transform * @@ -126,6 +129,12 @@ public: const OffsetType & GetOffsetComponent(void) const { return this->GetTranslation(); } + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + protected: /** Construct an ScalableAffineTransform object @@ -134,12 +143,12 @@ protected: * initializes the matrix and offset parts of the transformation * to values specified by the caller. If the arguments are * omitted, then the AffineTransform is initialized to an identity - * transformation in the appropriate number of dimensions. **/ + * transformation in the appropriate number of dimensions. */ ScalableAffineTransform(const MatrixType &matrix, const OutputVectorType &offset); ScalableAffineTransform(unsigned int outputSpaceDimension, unsigned int parametersDimension); - ScalableAffineTransform(); + ScalableAffineTransform(); void ComputeMatrix(); @@ -150,7 +159,7 @@ protected: void PrintSelf(std::ostream &s, Indent indent) const; void SetVarScale(const double * scale) - { for(int i=0; i<InputSpaceDimension; i++) { m_Scale[i] = scale[i]; } }; + { for(int i=0; i<InputSpaceDimension; i++) { m_Scale[i] = scale[i]; } } private: @@ -180,4 +189,3 @@ private: #endif #endif /* __itkScalableAffineTransform_h */ - diff --git a/Utilities/ITK/Code/Common/itkScalableAffineTransform.txx b/Utilities/ITK/Code/Common/itkScalableAffineTransform.txx index 228463e56e..df09d2c83c 100755 --- a/Utilities/ITK/Code/Common/itkScalableAffineTransform.txx +++ b/Utilities/ITK/Code/Common/itkScalableAffineTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalableAffineTransform.txx,v $ Language: C++ - Date: $Date: 2005-05-03 14:19:23 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkScalableAffineTransform_txx -#define _itkScalableAffineTransform_txx +#ifndef __itkScalableAffineTransform_txx +#define __itkScalableAffineTransform_txx #include "itkNumericTraits.h" #include "itkScalableAffineTransform.h" @@ -144,6 +144,25 @@ ScalableAffineTransform<TScalarType, NDimensions> this->Modified(); } +// Get an inverse of this transform +template<class TScalarType, unsigned int NDimensions> +bool +ScalableAffineTransform<TScalarType, NDimensions> +::GetInverse(Self* inverse) const +{ + return this->Superclass::GetInverse(inverse); +} + +// Return an inverse of this transform +template<class TScalarType, unsigned int NDimensions> +typename ScalableAffineTransform<TScalarType, NDimensions> +::InverseTransformBasePointer +ScalableAffineTransform<TScalarType, NDimensions> +::GetInverseTransform() const +{ + Pointer inv = New(); + return this->GetInverse(inv) ? inv.GetPointer() : NULL; +} /** Set the scale of the transformation */ template<class TScalarType, unsigned int NDimensions> diff --git a/Utilities/ITK/Code/Common/itkScalarToRGBPixelFunctor.h b/Utilities/ITK/Code/Common/itkScalarToRGBPixelFunctor.h index d88c29e5ac..5d0e5865f3 100644 --- a/Utilities/ITK/Code/Common/itkScalarToRGBPixelFunctor.h +++ b/Utilities/ITK/Code/Common/itkScalarToRGBPixelFunctor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarToRGBPixelFunctor.h,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:09:07 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,13 +52,13 @@ public: RGBPixelType operator()( const TScalar &) const; void SetLittleEndian() - { + { m_IsBigEndian = false; - } + } void SetBigEndian() - { + { m_IsBigEndian = true; - } + } private: bool m_IsBigEndian; diff --git a/Utilities/ITK/Code/Common/itkScalarToRGBPixelFunctor.txx b/Utilities/ITK/Code/Common/itkScalarToRGBPixelFunctor.txx index 5a9addf2c5..b15d1e46e0 100644 --- a/Utilities/ITK/Code/Common/itkScalarToRGBPixelFunctor.txx +++ b/Utilities/ITK/Code/Common/itkScalarToRGBPixelFunctor.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarToRGBPixelFunctor.txx,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:09:07 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -55,8 +55,10 @@ ScalarToRGBPixelFunctor<TScalar> if (this->m_IsBigEndian == true) { // swap bytes TScalar tmp; - for (j = sizeof(TScalar) - 1, i = 0; j >=0 ; j--, i++) - { ((unsigned char *)(&tmp))[i] = bytes[j]; } + for (j = sizeof(TScalar) - 1, i = 0; j >=0; j--, i++) + { + ((unsigned char *)(&tmp))[i] = bytes[j]; + } buf = tmp; } diff --git a/Utilities/ITK/Code/Common/itkScalarVector.h b/Utilities/ITK/Code/Common/itkScalarVector.h index 1da490ad33..3ead8dfeeb 100644 --- a/Utilities/ITK/Code/Common/itkScalarVector.h +++ b/Utilities/ITK/Code/Common/itkScalarVector.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarVector.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:25 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-03-03 15:09:07 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -104,7 +104,7 @@ public: { m_Vector = vec; } private: - TScalar m_Scalar; + TScalar m_Scalar; VectorType m_Vector; }; diff --git a/Utilities/ITK/Code/Common/itkScaleLogarithmicTransform.h b/Utilities/ITK/Code/Common/itkScaleLogarithmicTransform.h index c1814ac4bc..fa128a7b08 100644 --- a/Utilities/ITK/Code/Common/itkScaleLogarithmicTransform.h +++ b/Utilities/ITK/Code/Common/itkScaleLogarithmicTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScaleLogarithmicTransform.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:09:07 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,7 +23,8 @@ namespace itk { -/** \brief Logarithmic Scale transformation of a vector space (e.g. space coordinates) +/** \class ScaleLogarithmicTransform + * \brief Logarithmic Scale transformation of a vector space (e.g. space coordinates) * * The only difference between this class and its superclass the ScaleTransform * is that here the parameters of the transformation are the logarithms of the @@ -40,10 +41,10 @@ class ITK_EXPORT ScaleLogarithmicTransform : { public: /** Standard class typedefs. */ - typedef ScaleLogarithmicTransform Self; + typedef ScaleLogarithmicTransform Self; typedef ScaleTransform< TScalarType, NDimensions > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** New macro for creation of through a smart pointer. */ itkNewMacro( Self ); diff --git a/Utilities/ITK/Code/Common/itkScaleLogarithmicTransform.txx b/Utilities/ITK/Code/Common/itkScaleLogarithmicTransform.txx index 604f0ff2c0..2027b3b570 100644 --- a/Utilities/ITK/Code/Common/itkScaleLogarithmicTransform.txx +++ b/Utilities/ITK/Code/Common/itkScaleLogarithmicTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScaleLogarithmicTransform.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:36:59 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:09:08 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkScaleLogarithmicTransform_txx -#define _itkScaleLogarithmicTransform_txx +#ifndef __itkScaleLogarithmicTransform_txx +#define __itkScaleLogarithmicTransform_txx #include "itkScaleLogarithmicTransform.h" @@ -83,8 +83,6 @@ ScaleLogarithmicTransform<TScalarType,NDimensions> return this->m_Parameters; } - - // Print self template<class ScalarType, unsigned int NDimensions> void diff --git a/Utilities/ITK/Code/Common/itkScaleSkewVersor3DTransform.h b/Utilities/ITK/Code/Common/itkScaleSkewVersor3DTransform.h index 587f56ffdc..0db6519710 100644 --- a/Utilities/ITK/Code/Common/itkScaleSkewVersor3DTransform.h +++ b/Utilities/ITK/Code/Common/itkScaleSkewVersor3DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScaleSkewVersor3DTransform.h,v $ Language: C++ - Date: $Date: 2007-06-10 12:02:30 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-03-03 15:09:08 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,8 @@ namespace itk { -/** \brief ScaleSkewVersor3DTransform of a vector space (e.g. space coordinates) +/** \class ScaleSkewVersor3DTransform + * \brief ScaleSkewVersor3DTransform of a vector space (e.g. space coordinates) * * This transform applies a versor rotation and translation & scale/skew * to the space @@ -78,7 +79,7 @@ public: typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; - typedef typename Superclass::OutputCovariantVectorType + typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType; typedef typename Superclass::MatrixType MatrixType; typedef typename Superclass::InverseMatrixType InverseMatrixType; @@ -131,15 +132,15 @@ protected: const OutputVectorType &offset); ScaleSkewVersor3DTransform(unsigned int outputDims, unsigned int paramDims); - ~ScaleSkewVersor3DTransform(){}; + ~ScaleSkewVersor3DTransform(){} void PrintSelf(std::ostream &os, Indent indent) const; void SetVarScale(const ScaleVectorType & scale) - { m_Scale = scale; }; + { m_Scale = scale; } void SetVarSkew(const SkewVectorType & skew) - { m_Skew = skew; }; + { m_Skew = skew; } /** Compute the components of the rotation matrix in the superclass. */ void ComputeMatrix(void); diff --git a/Utilities/ITK/Code/Common/itkScaleSkewVersor3DTransform.txx b/Utilities/ITK/Code/Common/itkScaleSkewVersor3DTransform.txx index 2b9dc29226..6058e59aee 100644 --- a/Utilities/ITK/Code/Common/itkScaleSkewVersor3DTransform.txx +++ b/Utilities/ITK/Code/Common/itkScaleSkewVersor3DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScaleSkewVersor3DTransform.txx,v $ Language: C++ - Date: $Date: 2007-04-30 14:51:12 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-03-03 15:09:08 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,14 +14,14 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkScaleSkewVersor3DTransform_txx -#define _itkScaleSkewVersor3DTransform_txx +#ifndef __itkScaleSkewVersor3DTransform_txx +#define __itkScaleSkewVersor3DTransform_txx #include "itkScaleSkewVersor3DTransform.h" namespace itk - { +{ // Constructor with default arguments template <class TScalarType> @@ -129,9 +129,7 @@ ScaleSkewVersor3DTransform<TScalarType> this->Modified(); itkDebugMacro(<<"After setting parameters "); - } - - +} // // Get Parameters @@ -148,7 +146,7 @@ template <class TScalarType> const typename ScaleSkewVersor3DTransform<TScalarType>::ParametersType & ScaleSkewVersor3DTransform<TScalarType> ::GetParameters( void ) const - { +{ itkDebugMacro( << "Getting parameters "); this->m_Parameters[0] = this->GetVersor().GetX(); @@ -173,18 +171,17 @@ ScaleSkewVersor3DTransform<TScalarType> itkDebugMacro(<<"After getting parameters " << this->m_Parameters ); return this->m_Parameters; - } +} template <class TScalarType> void ScaleSkewVersor3DTransform<TScalarType> ::SetIdentity() - { +{ m_Scale.Fill( 1.0 ); m_Skew.Fill( 0.0 ); Superclass::SetIdentity(); - } - +} template <class TScalarType> void @@ -339,8 +336,6 @@ GetJacobian( const InputPointType & p ) const } - - } // namespace #endif diff --git a/Utilities/ITK/Code/Common/itkScaleTransform.h b/Utilities/ITK/Code/Common/itkScaleTransform.h index 280f9ff89c..0da12e145e 100644 --- a/Utilities/ITK/Code/Common/itkScaleTransform.h +++ b/Utilities/ITK/Code/Common/itkScaleTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScaleTransform.h,v $ Language: C++ - Date: $Date: 2006-11-03 20:09:08 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,8 @@ namespace itk { -/** \brief Scale transformation of a vector space (e.g. space coordinates) +/** \class ScaleTransform + * \brief Scale transformation of a vector space (e.g. space coordinates) * * The same functionality could be obtained by using the Affine tranform, * but with a large difference in performace since the affine transform will @@ -43,10 +44,10 @@ class ITK_EXPORT ScaleTransform : public Transform< TScalarType, { public: /** Standard class typedefs. */ - typedef ScaleTransform Self; + typedef ScaleTransform Self; typedef Transform< TScalarType, NDimensions, NDimensions > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** New macro for creation of through a smart pointer. */ itkNewMacro( Self ); @@ -85,6 +86,11 @@ public: /** Standard coordinate point type for this class. */ typedef Point<TScalarType, itkGetStaticConstMacro(SpaceDimension)> InputPointType; typedef Point<TScalarType, itkGetStaticConstMacro(SpaceDimension)> OutputPointType; + + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; /** Set parameters. This method sets the parameters for the transform value * specified by the user. The parameters are organized as scale[i] = @@ -108,7 +114,7 @@ public: * operator== defined. The array of scales correspond in order to the factors * to be applied to each one of the coordinaates. For example, in 3D, * scale[0] corresponds to X, scale[1] corresponds to Y and scale[2] - * corresponds to Z.*/ + * corresponds to Z. */ void SetScale( const ScaleType & scale ) { this->Modified(); m_Scale = scale; } @@ -146,6 +152,9 @@ public: * false is returned. */ bool GetInverse(Self* inverse) const; + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + /** Set the transformation to an Identity * * This sets all the scales to 1.0 */ @@ -203,9 +212,6 @@ BackTransform(const OutputPointType &point) const { return result; } - - - // Back transform a vector template<class ScalarType, unsigned int NDimensions> inline @@ -221,9 +227,6 @@ BackTransform(const OutputVectorType &vect ) const return result; } - - - // Back transform a vnl_vector template<class ScalarType, unsigned int NDimensions> inline diff --git a/Utilities/ITK/Code/Common/itkScaleTransform.txx b/Utilities/ITK/Code/Common/itkScaleTransform.txx index 450f8b1582..abae0d1a53 100644 --- a/Utilities/ITK/Code/Common/itkScaleTransform.txx +++ b/Utilities/ITK/Code/Common/itkScaleTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScaleTransform.txx,v $ Language: C++ - Date: $Date: 2007-12-23 17:59:29 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkScaleTransform_txx -#define _itkScaleTransform_txx +#ifndef __itkScaleTransform_txx +#define __itkScaleTransform_txx #include "itkScaleTransform.h" @@ -80,8 +80,6 @@ ScaleTransform<TScalarType,NDimensions> return this->m_Parameters; } - - // Print self template<class ScalarType, unsigned int NDimensions> void @@ -122,8 +120,6 @@ Scale(const ScaleType & scale, bool ) return; } - - // Transform a point template<class ScalarType, unsigned int NDimensions> typename ScaleTransform<ScalarType, NDimensions>::OutputPointType @@ -184,8 +180,6 @@ TransformCovariantVector(const InputCovariantVectorType &vect) const return result; } - - // Create and return an inverse transformation template<class ScalarType, unsigned int NDimensions> bool @@ -205,6 +199,16 @@ GetInverse(Self* inverse) const return true; } +// Return an inverse of this transform +template<class ScalarType, unsigned int NDimensions> +typename ScaleTransform<ScalarType, NDimensions>::InverseTransformBasePointer +ScaleTransform<ScalarType, NDimensions> +::GetInverseTransform() const +{ + Pointer inv = New(); + return GetInverse(inv) ? inv.GetPointer() : NULL; +} + // Compute the Jacobian of the transformation // It follows the same order of Parameters vector diff --git a/Utilities/ITK/Code/Common/itkScatterMatrixImageFunction.h b/Utilities/ITK/Code/Common/itkScatterMatrixImageFunction.h index a43e5d25b4..8ac3a7a48c 100755 --- a/Utilities/ITK/Code/Common/itkScatterMatrixImageFunction.h +++ b/Utilities/ITK/Code/Common/itkScatterMatrixImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScatterMatrixImageFunction.h,v $ Language: C++ - Date: $Date: 2007-02-05 13:35:53 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:09:09 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -53,9 +53,9 @@ public: typedef ImageFunction<TInputImage, vnl_matrix< ITK_TYPENAME NumericTraits<typename TInputImage::PixelType::ValueType>::RealType >, - TCoordRep > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + TCoordRep > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(ScatterMatrixImageFunction, ImageFunction); @@ -93,16 +93,16 @@ public: /** Evaluate the function at non-integer positions */ virtual RealType Evaluate( const PointType& point ) const { - IndexType index; - this->ConvertPointToNearestIndex( point, index ); - return this->EvaluateAtIndex( index ); + IndexType index; + this->ConvertPointToNearestIndex( point, index ); + return this->EvaluateAtIndex( index ); } virtual RealType EvaluateAtContinuousIndex( const ContinuousIndexType& cindex ) const { - IndexType index; - this->ConvertContinuousIndexToNearestIndex( cindex, index ); - return this->EvaluateAtIndex( index ) ; + IndexType index; + this->ConvertContinuousIndexToNearestIndex( cindex, index ); + return this->EvaluateAtIndex( index ); } /** Get/Set the radius of the neighborhood over which the @@ -141,4 +141,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Common/itkScatterMatrixImageFunction.txx b/Utilities/ITK/Code/Common/itkScatterMatrixImageFunction.txx index 8b901eddd3..2dbea52757 100755 --- a/Utilities/ITK/Code/Common/itkScatterMatrixImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkScatterMatrixImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScatterMatrixImageFunction.txx,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:09:09 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,8 +25,8 @@ namespace itk { /** - * Constructor - */ + * Constructor + */ template <class TInputImage, class TCoordRep> ScatterMatrixImageFunction<TInputImage,TCoordRep> ::ScatterMatrixImageFunction() @@ -34,10 +34,9 @@ ScatterMatrixImageFunction<TInputImage,TCoordRep> m_NeighborhoodRadius = 1; } - /** - * - */ + * + */ template <class TInputImage, class TCoordRep> void ScatterMatrixImageFunction<TInputImage,TCoordRep> diff --git a/Utilities/ITK/Code/Common/itkSegmentationBorder.cxx b/Utilities/ITK/Code/Common/itkSegmentationBorder.cxx index 3ffc1ebcc0..3ea6c41f94 100644 --- a/Utilities/ITK/Code/Common/itkSegmentationBorder.cxx +++ b/Utilities/ITK/Code/Common/itkSegmentationBorder.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSegmentationBorder.cxx,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:09:09 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,4 +46,3 @@ SegmentationBorder } } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkSegmentationBorder.h b/Utilities/ITK/Code/Common/itkSegmentationBorder.h index 9d763ff089..a104bf1b39 100644 --- a/Utilities/ITK/Code/Common/itkSegmentationBorder.h +++ b/Utilities/ITK/Code/Common/itkSegmentationBorder.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSegmentationBorder.h,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-03 15:09:09 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -45,9 +45,9 @@ class ITKCommon_EXPORT SegmentationBorder : public Object { public: /** Standard class typedefs. */ - typedef SegmentationBorder Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; + typedef SegmentationBorder Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ diff --git a/Utilities/ITK/Code/Common/itkSegmentationLevelSetFunction.h b/Utilities/ITK/Code/Common/itkSegmentationLevelSetFunction.h index d9df5a4455..3a97cac90c 100644 --- a/Utilities/ITK/Code/Common/itkSegmentationLevelSetFunction.h +++ b/Utilities/ITK/Code/Common/itkSegmentationLevelSetFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSegmentationLevelSetFunction.h,v $ Language: C++ - Date: $Date: 2008-03-03 13:58:52 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-03-03 15:09:09 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkSegmentationLevelSetFunction_h_ -#define __itkSegmentationLevelSetFunction_h_ +#ifndef __itkSegmentationLevelSetFunction_h +#define __itkSegmentationLevelSetFunction_h #include "itkLevelSetFunction.h" #include "itkLinearInterpolateImageFunction.h" @@ -39,7 +39,7 @@ namespace itk { \sa SegmentationLevelSetImageFilter \sa LevelSetFunction -*/ + */ template <class TImageType, class TFeatureImageType = TImageType> class ITK_EXPORT SegmentationLevelSetFunction @@ -49,23 +49,23 @@ public: /** Standard class typedefs. */ typedef SegmentationLevelSetFunction Self; typedef LevelSetFunction<TImageType> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods) */ itkTypeMacro( SegmentationLevelSetFunction, LevelSetFunction ); /** Extract some parameters from the superclass. */ - typedef typename Superclass::ImageType ImageType; - typedef typename Superclass::RadiusType RadiusType; - typedef typename Superclass::PixelRealType PixelRealType; - typedef TFeatureImageType FeatureImageType; - typedef typename Superclass::FloatOffsetType FloatOffsetType; - typedef typename Superclass::ScalarValueType ScalarValueType; + typedef typename Superclass::ImageType ImageType; + typedef typename Superclass::RadiusType RadiusType; + typedef typename Superclass::PixelRealType PixelRealType; + typedef TFeatureImageType FeatureImageType; + typedef typename Superclass::FloatOffsetType FloatOffsetType; + typedef typename Superclass::ScalarValueType ScalarValueType; typedef typename Superclass::NeighborhoodType NeighborhoodType; - typedef typename FeatureImageType::PixelType FeatureScalarType; - typedef typename ImageType::IndexType IndexType; - typedef typename Superclass::VectorType VectorType; + typedef typename FeatureImageType::PixelType FeatureScalarType; + typedef typename ImageType::IndexType IndexType; + typedef typename Superclass::VectorType VectorType; typedef typename Superclass::GlobalDataStruct GlobalDataStruct; /** Extract some parameters from the superclass. */ @@ -92,7 +92,7 @@ public: /** Get/Set the image used as the speed function in the level set equation */ virtual ImageType *GetSpeedImage() - { return m_SpeedImage.GetPointer(); } + { return m_SpeedImage.GetPointer(); } void SetSpeedImage( ImageType *s ); /** Get/Set the image used as the advection field in the level set equation */ @@ -163,14 +163,14 @@ protected: virtual ~SegmentationLevelSetFunction() {} SegmentationLevelSetFunction() - { + { m_SpeedImage = ImageType::New(); m_AdvectionImage = VectorImageType::New(); m_Interpolator = InterpolatorType::New(); m_VectorInterpolator = VectorInterpolatorType::New(); - } + } - typename InterpolatorType::Pointer m_Interpolator; + typename InterpolatorType::Pointer m_Interpolator; typename VectorInterpolatorType::Pointer m_VectorInterpolator; diff --git a/Utilities/ITK/Code/Common/itkSegmentationLevelSetFunction.txx b/Utilities/ITK/Code/Common/itkSegmentationLevelSetFunction.txx index dce54e83f4..f5c6289145 100644 --- a/Utilities/ITK/Code/Common/itkSegmentationLevelSetFunction.txx +++ b/Utilities/ITK/Code/Common/itkSegmentationLevelSetFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSegmentationLevelSetFunction.txx,v $ Language: C++ - Date: $Date: 2008-03-03 13:58:53 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-03-03 15:09:09 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkSegmentationLevelSetFunction_txx_ -#define __itkSegmentationLevelSetFunction_txx_ +#ifndef __itkSegmentationLevelSetFunction_txx +#define __itkSegmentationLevelSetFunction_txx #include "itkSegmentationLevelSetFunction.h" @@ -113,7 +113,7 @@ SegmentationLevelSetFunction<TImageType, TFeatureImageType> return ( m_VectorCast(m_VectorInterpolator->EvaluateAtContinuousIndex(cdx))); } //Just return the default else - return ( m_AdvectionImage->GetPixel(idx) ); + return ( m_AdvectionImage->GetPixel(idx) ); } diff --git a/Utilities/ITK/Code/Common/itkSegmentationRegion.cxx b/Utilities/ITK/Code/Common/itkSegmentationRegion.cxx index f14b0da1bc..5946fba89a 100644 --- a/Utilities/ITK/Code/Common/itkSegmentationRegion.cxx +++ b/Utilities/ITK/Code/Common/itkSegmentationRegion.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSegmentationRegion.cxx,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-03 15:09:09 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -50,4 +50,3 @@ SegmentationRegion } } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkSemaphore.cxx b/Utilities/ITK/Code/Common/itkSemaphore.cxx index 514fe7f39b..8d235b3f59 100644 --- a/Utilities/ITK/Code/Common/itkSemaphore.cxx +++ b/Utilities/ITK/Code/Common/itkSemaphore.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSemaphore.cxx,v $ Language: C++ - Date: $Date: 2006-02-06 22:08:11 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-03-03 15:09:12 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -111,7 +111,7 @@ void Semaphore::Initialize(unsigned int value) m_Sema = usnewsema(MultiThreader::GetThreadArena(), static_cast<int>(value)); if ( ! m_Sema ) { - itkExceptionMacro( << " sem_init call failed with code " << m_Sema ); + itkExceptionMacro( << " sem_init call failed with code " << m_Sema ); } #endif @@ -313,14 +313,14 @@ m_PThreadsSemaphoreRemoved = true; #else //Still need to close semaphore and delete the file descriptor on MacOSX, otherwise the shared memory space is eventually exhosted. //Eventually (i.e. after several days of ITK regresssion testing) the semaphore creation process was failing with errno=ENOSPC //This implementation detail was taken from http://developer.apple.com/macosx/multithreadedprogramming.html - if ( sem_close(this->m_Sema) !=0 ) - { - itkExceptionMacro( << "sem_close call failed. " ); - } - if ( sem_unlink(this->m_SemaphoreName.c_str()) !=0 ) - { - itkExceptionMacro( << "sem_unlink call failed. " ); - } + if ( sem_close(this->m_Sema) != 0 ) + { + itkExceptionMacro( << "sem_close call failed. " ); + } + if ( sem_unlink(this->m_SemaphoreName.c_str()) != 0 ) + { + itkExceptionMacro( << "sem_unlink call failed. " ); + } #endif #endif @@ -358,10 +358,10 @@ int Semaphore::UnixIpcSemaphoreCreate(int unix_semaphore_key) s += "Semaphore already exists. - "; break; case ENOSPC: - s+= "System imposed limit on the number of semaphores is exceeded - "; + s += "System imposed limit on the number of semaphores is exceeded - "; break; case EACCES: - s+= "Permission is denied - "; + s += "Permission is denied - "; break; } itkExceptionMacro( << s.c_str() ); @@ -399,13 +399,13 @@ void Semaphore::UnixIpcSemaphoreRemove(int sid) switch (errno) { case EINVAL: - s += "Semaphore id# is not valid. - "; + s += "Semaphore id# is not valid. - "; break; case EACCES: - s+= "Permission is denied - "; + s += "Permission is denied - "; break; case EPERM: - s+= "Permission is denied - "; + s += "Permission is denied - "; break; } itkExceptionMacro ( << s.c_str() ); @@ -436,10 +436,10 @@ void Semaphore::UnixIpcSemaphoreCall (int sid, int op) switch (errno) { case EINVAL: - s += "Semaphore id# is not valid. -"; + s += "Semaphore id# is not valid. -"; break; case EFBIG: - s += "Invalid sem_num for semaphore - "; + s += "Invalid sem_num for semaphore - "; break; case EACCES: s += "Permission denied for semaphore - "; @@ -458,4 +458,3 @@ void Semaphore::UnixIpcSemaphoreCall (int sid, int op) #endif }//end if namespace itk - diff --git a/Utilities/ITK/Code/Common/itkSemaphore.h b/Utilities/ITK/Code/Common/itkSemaphore.h index 9d4601a867..b4384ff007 100755 --- a/Utilities/ITK/Code/Common/itkSemaphore.h +++ b/Utilities/ITK/Code/Common/itkSemaphore.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSemaphore.h,v $ Language: C++ - Date: $Date: 2004-03-12 21:41:50 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-03 15:09:14 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkSemaphore_h_ -#define __itkSemaphore_h_ +#ifndef __itkSemaphore_h +#define __itkSemaphore_h #include "itkObjectFactory.h" #include "itkLightObject.h" @@ -52,7 +52,7 @@ namespace itk { #ifdef ITK_USE_UNIX_IPC_SEMAPHORES - typedef int SemaphoreType; +typedef int SemaphoreType; #endif #ifndef ITK_USE_UNIX_IPC_SEMAPHORES @@ -108,14 +108,14 @@ typedef int SemaphoreType; * IPC semaphores, and IRIX semaphores from the SGI Sproc library. On Windows * systems, POSIX semaphores and WIN32 thread library semaphores are supported. * -*/ + */ class ITKCommon_EXPORT Semaphore : public LightObject { public: /** Standard class typedefs. */ - typedef Semaphore Self; - typedef LightObject Superclass; - typedef SmartPointer<Self> Pointer; + typedef Semaphore Self; + typedef LightObject Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ @@ -135,7 +135,7 @@ public: blocked until another thread calls the up() method. The order in which threads will be unblocked is not defined, but implementors should give preference to those threads that have waited the longest. - */ + */ void Down(); /** Remove the semaphore from the system. */ @@ -167,7 +167,7 @@ private: #ifdef __APPLE__ std::string GetUniqueName(); - static int m_SemaphoreCount; + static int m_SemaphoreCount; std::string m_SemaphoreName; #endif diff --git a/Utilities/ITK/Code/Common/itkShapeSignedDistanceFunction.h b/Utilities/ITK/Code/Common/itkShapeSignedDistanceFunction.h index 8e46867809..a0037742db 100644 --- a/Utilities/ITK/Code/Common/itkShapeSignedDistanceFunction.h +++ b/Utilities/ITK/Code/Common/itkShapeSignedDistanceFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShapeSignedDistanceFunction.h,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:09:15 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -54,9 +54,9 @@ public: /** Standard class typedefs. */ typedef ShapeSignedDistanceFunction Self; typedef SpatialFunction< double, VSpaceDimension, - Point<TCoordRep,VSpaceDimension> > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + Point<TCoordRep,VSpaceDimension> > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(ShapeSignedDistanceFunction, SpatialFunction); diff --git a/Utilities/ITK/Code/Common/itkShapedNeighborhoodIterator.h b/Utilities/ITK/Code/Common/itkShapedNeighborhoodIterator.h index 3c5ffc939b..4601eeea31 100644 --- a/Utilities/ITK/Code/Common/itkShapedNeighborhoodIterator.h +++ b/Utilities/ITK/Code/Common/itkShapedNeighborhoodIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShapedNeighborhoodIterator.h,v $ Language: C++ - Date: $Date: 2005-10-20 13:25:26 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-03 15:09:16 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -109,7 +109,7 @@ namespace itk { * determine whether bounds checking must take place. * * \sa Neighborhood - * + * * \par MORE INFORMATION * For a complete description of the ITK Image Iterators and their API, please * see the Iterators chapter in the ITK Software Guide. The ITK Software Guide @@ -147,57 +147,59 @@ class ITK_EXPORT ShapedNeighborhoodIterator public: /** Extract image type information. */ typedef typename TImage::InternalPixelType InternalPixelType; - typedef typename TImage::PixelType PixelType; + typedef typename TImage::PixelType PixelType; /** Save the image dimension. */ itkStaticConstMacro(Dimension, unsigned int, TImage::ImageDimension); /** Standard class typedefs. */ typedef ShapedNeighborhoodIterator Self; - typedef ConstShapedNeighborhoodIterator<TImage, TBoundaryCondition> Superclass; + typedef ConstShapedNeighborhoodIterator<TImage, TBoundaryCondition> + Superclass; /** Inherit typedefs from superclass */ - typedef typename Superclass::OffsetType OffsetType; - typedef typename OffsetType::OffsetValueType OffsetValueType; - typedef typename Superclass::RadiusType RadiusType; - typedef typename Superclass::SizeType SizeType; - typedef typename Superclass::SizeValueType SizeValueType; - typedef typename Superclass::ConstIterator ConstIterator; - typedef typename Superclass::IndexListType IndexListType; + typedef typename Superclass::OffsetType OffsetType; + typedef typename OffsetType::OffsetValueType OffsetValueType; + typedef typename Superclass::RadiusType RadiusType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::SizeValueType SizeValueType; + typedef typename Superclass::ConstIterator ConstIterator; + typedef typename Superclass::IndexListType IndexListType; typedef typename Superclass::BoundaryConditionType BoundaryConditionType; - typedef typename Superclass::ImageBoundaryConditionPointerType ImageBoundaryConditionPointerType; - typedef typename Superclass::NeighborhoodType NeighborhoodType; - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::ImageType ImageType; - typedef typename Superclass::RegionType RegionType; - typedef typename Superclass::IndexValueType IndexValueType; - - /** An iterator for the ShapedNeighborhood classes.*/ + typedef typename Superclass::ImageBoundaryConditionPointerType + ImageBoundaryConditionPointerType; + typedef typename Superclass::NeighborhoodType NeighborhoodType; + typedef typename Superclass::IndexType IndexType; + typedef typename Superclass::ImageType ImageType; + typedef typename Superclass::RegionType RegionType; + typedef typename Superclass::IndexValueType IndexValueType; + + /** An iterator for the ShapedNeighborhood classes. */ struct Iterator : public ConstIterator - { + { Iterator() {} Iterator(Self *s) : ConstIterator(s) {} ~Iterator() {} const Iterator &operator=(const Iterator &o) - { + { ConstIterator::operator=(o); return *this; - } + } // Promote to public void Set(const PixelType &v) const - { ConstIterator::ProtectedSet(v); } + { ConstIterator::ProtectedSet(v); } }; /** Default constructor */ ShapedNeighborhoodIterator() - { + { m_BeginIterator = Iterator(this); m_EndIterator = Iterator(this); m_EndIterator.GoToEnd(); - } + } /** Virtual destructor */ virtual ~ShapedNeighborhoodIterator() {} @@ -209,11 +211,11 @@ public: const RegionType ®ion ) : Superclass(radius, const_cast<ImageType*>(ptr), region) - { + { m_BeginIterator = Iterator(this); m_EndIterator = Iterator(this); m_EndIterator.GoToEnd(); - } + } // Expose the following methods from the superclass. This is a restricted // subset of the methods available for NeighborhoodIterator. @@ -222,14 +224,14 @@ public: /** Assignment operator */ Self &operator=(const Self& orig) - { + { Superclass::operator=(orig); // Reset begin and end pointer locations m_BeginIterator.GoToBegin(); m_EndIterator.GoToEnd(); return *this; - } + } /** Standard itk print method */ virtual void PrintSelf(std::ostream &, Indent) const; @@ -242,14 +244,14 @@ public: /** Returns a const iterator for the neighborhood which points to the last * pixel in the neighborhood. */ const ConstIterator &End() const - { return this->m_ConstEndIterator; } + { return this->m_ConstEndIterator; } void ClearActiveList() - { + { Superclass::ClearActiveList(); m_EndIterator.GoToEnd(); m_BeginIterator.GoToBegin(); - } + } protected: @@ -259,20 +261,18 @@ protected: void ActivateIndex(const unsigned int n) - { + { Superclass::ActivateIndex(n); m_EndIterator.GoToEnd(); m_BeginIterator.GoToBegin(); - } + } void DeactivateIndex(const unsigned int n) - { + { Superclass::DeactivateIndex(n); m_EndIterator.GoToEnd(); m_BeginIterator.GoToBegin(); - } - - + } Iterator m_EndIterator; Iterator m_BeginIterator; }; @@ -285,4 +285,3 @@ protected: #endif #endif - diff --git a/Utilities/ITK/Code/Common/itkShapedNeighborhoodIterator.txx b/Utilities/ITK/Code/Common/itkShapedNeighborhoodIterator.txx index 1a8d4be808..c9f5780fc5 100644 --- a/Utilities/ITK/Code/Common/itkShapedNeighborhoodIterator.txx +++ b/Utilities/ITK/Code/Common/itkShapedNeighborhoodIterator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShapedNeighborhoodIterator.txx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:25 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:09:17 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkShapedNeighborhoodIterator_txx -#define _itkShapedNeighborhoodIterator_txx +#ifndef __itkShapedNeighborhoodIterator_txx +#define __itkShapedNeighborhoodIterator_txx #include "itkShapedNeighborhoodIterator.h" namespace itk { @@ -33,4 +33,3 @@ ShapedNeighborhoodIterator<TImage, TBoundaryCondition> } // namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkSimilarity2DTransform.h b/Utilities/ITK/Code/Common/itkSimilarity2DTransform.h index d7416ec68a..319863bb2b 100644 --- a/Utilities/ITK/Code/Common/itkSimilarity2DTransform.h +++ b/Utilities/ITK/Code/Common/itkSimilarity2DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimilarity2DTransform.h,v $ Language: C++ - Date: $Date: 2006-06-07 16:06:32 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,8 @@ namespace itk { -/** \brief Similarity2DTransform of a vector space (e.g. space coordinates) +/** \class Similarity2DTransform + * \brief Similarity2DTransform of a vector space (e.g. space coordinates) * * This transform applies a homogenous scale and rigid transform in * 2D space. The transform is specified as a scale and rotation around @@ -64,10 +65,10 @@ class ITK_EXPORT Similarity2DTransform : { public: /** Standard class typedefs. */ - typedef Similarity2DTransform Self; + typedef Similarity2DTransform Self; typedef Rigid2DTransform< TScalarType > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** New macro for creation of through a Smart Pointer. */ itkNewMacro( Self ); @@ -113,6 +114,11 @@ public: typedef typename Superclass::InputVnlVectorType InputVnlVectorType; typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; + /** Set the Scale part of the transform. */ void SetScale( ScaleType scale ); itkGetConstReferenceMacro( Scale, ScaleType ); @@ -151,13 +157,19 @@ public: /** * This method creates and returns a new Similarity2DTransform object * which is the inverse of self. - **/ + */ void CloneInverseTo( Pointer & newinverse ) const; + /** Get an inverse of this transform. */ + bool GetInverse(Self* inverse) const; + + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + /** * This method creates and returns a new Similarity2DTransform object * which has the same parameters. - **/ + */ void CloneTo( Pointer & clone ) const; /** @@ -172,7 +184,7 @@ public: * * \sa MatrixOffsetTransformBase::SetMatrix() * - **/ + */ virtual void SetMatrix( const MatrixType & matrix ); protected: diff --git a/Utilities/ITK/Code/Common/itkSimilarity2DTransform.txx b/Utilities/ITK/Code/Common/itkSimilarity2DTransform.txx index ce9ec89fc5..85005184f7 100644 --- a/Utilities/ITK/Code/Common/itkSimilarity2DTransform.txx +++ b/Utilities/ITK/Code/Common/itkSimilarity2DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimilarity2DTransform.txx,v $ Language: C++ - Date: $Date: 2008-01-24 05:12:41 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-04-09 09:23:21 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkSimilarity2DTransform_txx -#define _itkSimilarity2DTransform_txx +#ifndef __itkSimilarity2DTransform_txx +#define __itkSimilarity2DTransform_txx #include "itkSimilarity2DTransform.h" #include "vnl/vnl_math.h" @@ -98,8 +98,6 @@ Similarity2DTransform<TScalarType> return this->m_Parameters; } - - // Set Scale Part template <class TScalarType> void @@ -223,10 +221,36 @@ Similarity2DTransform<TScalarType>:: CloneInverseTo( Pointer & result ) const { result = New(); - result->SetCenter( this->GetCenter() ); // inverse have the same center - result->SetScale( 1.0 / this->GetScale() ); - result->SetAngle( -this->GetAngle() ); - result->SetTranslation( -( this->GetInverseMatrix() * this->GetTranslation() ) ); + this->GetInverse(result.GetPointer()); +} + +// return an inverse transformation +template<class TScalarType> +bool +Similarity2DTransform<TScalarType>:: +GetInverse( Self* inverse) const +{ + if(!inverse) + { + return false; + } + + inverse->SetCenter( this->GetCenter() ); // inverse have the same center + inverse->SetScale( 1.0 / this->GetScale() ); + inverse->SetAngle( -this->GetAngle() ); + inverse->SetTranslation( -( this->GetInverseMatrix() * this->GetTranslation() ) ); + + return true; +} + +// Return an inverse of this transform +template<class TScalarType> +typename Similarity2DTransform<TScalarType>::InverseTransformBasePointer +Similarity2DTransform<TScalarType> +::GetInverseTransform() const +{ + Pointer inv = New(); + return GetInverse(inv) ? inv.GetPointer() : NULL; } // Create and return a clone of the transformation diff --git a/Utilities/ITK/Code/Common/itkSimilarity3DTransform.h b/Utilities/ITK/Code/Common/itkSimilarity3DTransform.h index 64bb3bcd83..9c5665f668 100644 --- a/Utilities/ITK/Code/Common/itkSimilarity3DTransform.h +++ b/Utilities/ITK/Code/Common/itkSimilarity3DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimilarity3DTransform.h,v $ Language: C++ - Date: $Date: 2006-08-09 04:35:32 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:09:20 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,8 @@ namespace itk { -/** \brief Similarity3DTransform of a vector space (e.g. space coordinates) +/** \class Similarity3DTransform + * \brief Similarity3DTransform of a vector space (e.g. space coordinates) * * This transform applies a rotation, translation and isotropic scaling to the space. * @@ -78,7 +79,7 @@ public: typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; - typedef typename Superclass::OutputCovariantVectorType + typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType; typedef typename Superclass::MatrixType MatrixType; typedef typename Superclass::InverseMatrixType InverseMatrixType; diff --git a/Utilities/ITK/Code/Common/itkSimilarity3DTransform.txx b/Utilities/ITK/Code/Common/itkSimilarity3DTransform.txx index 9917f94d3f..d63363a310 100644 --- a/Utilities/ITK/Code/Common/itkSimilarity3DTransform.txx +++ b/Utilities/ITK/Code/Common/itkSimilarity3DTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimilarity3DTransform.txx,v $ Language: C++ - Date: $Date: 2007-11-27 16:04:48 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-03 15:09:21 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkSimilarity3DTransform_txx -#define _itkSimilarity3DTransform_txx +#ifndef __itkSimilarity3DTransform_txx +#define __itkSimilarity3DTransform_txx #include "itkSimilarity3DTransform.h" #include "vnl/vnl_math.h" @@ -61,8 +61,8 @@ void Similarity3DTransform<TScalarType> ::SetScale( ScaleType scale ) { - m_Scale = scale; - this->ComputeMatrix(); + m_Scale = scale; + this->ComputeMatrix(); } @@ -105,7 +105,7 @@ Similarity3DTransform<TScalarType> const double tolerance = 1e-10; if( !this->MatrixIsOrthogonal( testForOrthogonal, tolerance ) ) - { + { itkExceptionMacro( << "Attempting to set a non-orthogonal matrix (after removing scaling)" ); } @@ -300,7 +300,7 @@ Similarity3DTransform<TScalarType> { MatrixType matrix = this->GetMatrix(); - m_Scale = vnl_math_cuberoot( vnl_det( matrix.GetVnlMatrix() ) ) ; + m_Scale = vnl_math_cuberoot( vnl_det( matrix.GetVnlMatrix() ) ); matrix /= m_Scale; diff --git a/Utilities/ITK/Code/Common/itkSimpleDataObjectDecorator.h b/Utilities/ITK/Code/Common/itkSimpleDataObjectDecorator.h index 07f4a324ea..6cb494b6e6 100644 --- a/Utilities/ITK/Code/Common/itkSimpleDataObjectDecorator.h +++ b/Utilities/ITK/Code/Common/itkSimpleDataObjectDecorator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimpleDataObjectDecorator.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-21 14:20:10 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -61,9 +61,9 @@ class ITK_EXPORT SimpleDataObjectDecorator : public DataObject public: /** Standard typedefs. */ typedef SimpleDataObjectDecorator Self; - typedef DataObject Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef DataObject Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Typedef for the component type (object being decorated) */ typedef T ComponentType; @@ -79,7 +79,7 @@ public: /** Get the contained object */ virtual T& Get() { return m_Component; } - virtual T Get() const { return m_Component; } + virtual const T& Get() const { return m_Component; } protected: @@ -94,6 +94,7 @@ private: void operator=(const Self&); //purposely not implemented ComponentType m_Component; + bool m_Initialized; }; } // end namespace itk @@ -113,6 +114,4 @@ private: # include "itkSimpleDataObjectDecorator.txx" #endif - #endif - diff --git a/Utilities/ITK/Code/Common/itkSimpleDataObjectDecorator.txx b/Utilities/ITK/Code/Common/itkSimpleDataObjectDecorator.txx index 3922ce6212..fbb7835491 100644 --- a/Utilities/ITK/Code/Common/itkSimpleDataObjectDecorator.txx +++ b/Utilities/ITK/Code/Common/itkSimpleDataObjectDecorator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimpleDataObjectDecorator.txx,v $ Language: C++ - Date: $Date: 2004-03-18 19:24:08 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-12 18:42:40 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,8 +17,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkSimpleDataObjectDecorator_txx -#define _itkSimpleDataObjectDecorator_txx +#ifndef __itkSimpleDataObjectDecorator_txx +#define __itkSimpleDataObjectDecorator_txx #include "itkSimpleDataObjectDecorator.h" @@ -32,7 +32,10 @@ template<class T> SimpleDataObjectDecorator<T> ::SimpleDataObjectDecorator() { - m_Component = ComponentType(); // initialize here to avoid Purify UMR + this->m_Component = ComponentType(); // initialize here to avoid Purify UMR + this->m_Initialized = false; // Still needed since not all objects + // are initialized at construction time. + // for example the itkArray. } @@ -54,9 +57,10 @@ void SimpleDataObjectDecorator<T> ::Set(const T& val) { - if (m_Component != val) + if( !this->m_Initialized || ( this->m_Component != val) ) { - m_Component = val; + this->m_Component = val; + this->m_Initialized = true; this->Modified(); } } @@ -71,7 +75,8 @@ SimpleDataObjectDecorator<T> { Superclass::PrintSelf(os,indent); - os << indent << "Component: " << typeid(m_Component).name() << std::endl; + os << indent << "Component : " << typeid(this->m_Component).name() << std::endl; + os << indent << "Initialized: " << this->m_Initialized << std::endl; } } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkSimpleFastMutexLock.h b/Utilities/ITK/Code/Common/itkSimpleFastMutexLock.h index 7676272b48..3858c51f31 100644 --- a/Utilities/ITK/Code/Common/itkSimpleFastMutexLock.h +++ b/Utilities/ITK/Code/Common/itkSimpleFastMutexLock.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimpleFastMutexLock.h,v $ Language: C++ - Date: $Date: 2006-03-06 15:07:34 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:09:22 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -93,4 +93,3 @@ protected: }//end itk namespace #endif - diff --git a/Utilities/ITK/Code/Common/itkSimpleFilterWatcher.cxx b/Utilities/ITK/Code/Common/itkSimpleFilterWatcher.cxx index 7dfe06d69a..215d526b9a 100755 --- a/Utilities/ITK/Code/Common/itkSimpleFilterWatcher.cxx +++ b/Utilities/ITK/Code/Common/itkSimpleFilterWatcher.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimpleFilterWatcher.cxx,v $ Language: C++ - Date: $Date: 2005-12-10 13:48:34 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:09:25 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -267,4 +267,3 @@ SimpleFilterWatcher } } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkSimpleFilterWatcher.h b/Utilities/ITK/Code/Common/itkSimpleFilterWatcher.h index a5a1ad6542..aa1feeb2c4 100755 --- a/Utilities/ITK/Code/Common/itkSimpleFilterWatcher.h +++ b/Utilities/ITK/Code/Common/itkSimpleFilterWatcher.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimpleFilterWatcher.h,v $ Language: C++ - Date: $Date: 2006-11-07 11:56:40 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-03 15:09:25 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -84,39 +84,39 @@ public: * SimpleFilterWatcher */ const char *GetNameOfClass () { - return (m_Process.GetPointer() ? m_Process->GetNameOfClass() : "None"); + return (m_Process.GetPointer() ? m_Process->GetNameOfClass() : "None"); } /** Methods to control the verbosity of the messages. Quiet * reporting limits the information emitted at a ProgressEvent. */ - void QuietOn() {m_Quiet = true;}; - void QuietOff() {m_Quiet = false;}; + void QuietOn() {m_Quiet = true;} + void QuietOff() {m_Quiet = false;} /** Methods to use to test the AbortEvent of the a filter. If * TestAbort is on, the filter being watched will be aborted when - * the progress reaches 30%.*/ - void TestAbortOn() {m_TestAbort = true;}; - void TestAbortOff() {m_TestAbort = false;}; + * the progress reaches 30%. */ + void TestAbortOn() {m_TestAbort = true;} + void TestAbortOff() {m_TestAbort = false;} /** Methods to access member data */ /** Get a pointer to the process object being watched. */ - ProcessObject *GetProcess () {return m_Process.GetPointer();}; + ProcessObject *GetProcess () {return m_Process.GetPointer();} /** Set/Get the steps completed. */ - void SetSteps(int val) {m_Steps=val;}; - int GetSteps() {return m_Steps;}; + void SetSteps(int val) {m_Steps=val;} + int GetSteps() {return m_Steps;} /** Set/Get the number of iterations completed. */ - void SetIterations(int val) {m_Iterations=val;}; - int GetIterations() {return m_Iterations;}; + void SetIterations(int val) {m_Iterations=val;} + int GetIterations() {return m_Iterations;} /** Set/Get the quiet mode boolean. If true, verbose progess is * reported. */ - void SetQuiet(bool val) {m_Quiet=val;}; - bool GetQuiet() {return m_Quiet;}; + void SetQuiet(bool val) {m_Quiet=val;} + bool GetQuiet() {return m_Quiet;} /** Get the comment for the watcher. */ - std::string GetComment() {return m_Comment;}; + std::string GetComment() {return m_Comment;} /** Get a reference to the TimeProbe */ TimeProbe &GetTimeProbe() {return m_TimeProbe;} @@ -125,7 +125,7 @@ protected: /** Callback method to show the ProgressEvent */ virtual void ShowProgress() - { + { if (m_Process) { m_Steps++; @@ -145,24 +145,24 @@ protected: } } } - } + } /** Callback method to show the AbortEvent */ virtual void ShowAbort() - { + { std::cout << std::endl << "-------Aborted" << std::endl << std::flush; - } + } /** Callback method to show the IterationEvent */ virtual void ShowIteration() - { + { std::cout << " # " << std::flush; m_Iterations++; - } + } /** Callback method to show the StartEvent */ virtual void StartFilter() - { + { m_Steps = 0; m_Iterations = 0; m_TimeProbe.Start(); @@ -182,11 +182,11 @@ protected: } std::cout << (m_Quiet ? "Progress Quiet " : "Progress ") << std::flush; - } + } /** Callback method to show the EndEvent */ virtual void EndFilter() - { + { m_TimeProbe.Stop(); std::cout << std::endl << "Filter took " << m_TimeProbe.GetMeanTime() @@ -214,12 +214,12 @@ protected: } private: - TimeProbe m_TimeProbe; - int m_Steps; - int m_Iterations; - bool m_Quiet; - bool m_TestAbort; - std::string m_Comment; + TimeProbe m_TimeProbe; + int m_Steps; + int m_Iterations; + bool m_Quiet; + bool m_TestAbort; + std::string m_Comment; itk::ProcessObject::Pointer m_Process; typedef SimpleMemberCommand<SimpleFilterWatcher> CommandType; diff --git a/Utilities/ITK/Code/Common/itkSimplexMesh.h b/Utilities/ITK/Code/Common/itkSimplexMesh.h index 11c3adbdd6..e422960ad4 100644 --- a/Utilities/ITK/Code/Common/itkSimplexMesh.h +++ b/Utilities/ITK/Code/Common/itkSimplexMesh.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMesh.h,v $ Language: C++ -Date: $Date: 2007-02-01 18:08:15 $ -Version: $Revision: 1.11 $ +Date: $Date: 2009-04-25 12:24:12 $ +Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,263 +35,255 @@ PURPOSE. See the above copyright notices for more information. #include <set> namespace itk - { - /** \class SimplexMesh - * \brief The class represents a 2-simplex mesh. - * - * A simplex mesh can be used for deformable model segmentation of 3D image data. - * To create a simplex mesh one needs a triangle mesh, which can be converted - * to using the class itkTriangleMeshToSimplexMeshFilter. The back filtering - * (from simplex to trinagle mesh)is done through a itkSimplexMeshToTriangleMeshFilter. - * - * - * - * \author Thomas Boettger. Division Medical and Biological Informatics, German Cancer Research Center, Heidelberg. - */ +{ +/** \class SimplexMesh + * \brief The class represents a 2-simplex mesh. + * + * A simplex mesh can be used for deformable model segmentation of 3D image data. + * To create a simplex mesh one needs a triangle mesh, which can be converted + * to using the class itkTriangleMeshToSimplexMeshFilter. The back filtering + * (from simplex to trinagle mesh)is done through a itkSimplexMeshToTriangleMeshFilter. + * + * \author Thomas Boettger. Division Medical and Biological Informatics, German Cancer Research Center, Heidelberg. + */ template <typename TPixelType, unsigned int VDimension = 3, typename TMeshTraits = DefaultStaticMeshTraits< TPixelType , VDimension, VDimension, TPixelType , TPixelType , TPixelType > > class SimplexMesh : public Mesh<TPixelType, VDimension, TMeshTraits> - { - public: - /** Standard typedefs. */ - typedef SimplexMesh Self; +{ +public: + /** Standard typedefs. */ + typedef SimplexMesh Self; - /** Standard typedefs. */ - typedef Mesh<TPixelType, VDimension, TMeshTraits> Superclass; + /** Standard typedefs. */ + typedef Mesh<TPixelType, VDimension, TMeshTraits> Superclass; - /** Standard typedefs. */ - typedef SmartPointer<Self> Pointer; + /** Standard typedefs. */ + typedef SmartPointer<Self> Pointer; - /** Standard typedefs. */ - typedef SmartPointer<const Self> ConstPointer; + /** Standard typedefs. */ + typedef SmartPointer<const Self> ConstPointer; - /** definition for array of indices*/ - typedef typename SimplexMeshGeometry::IndexArray IndexArray; + /** definition for array of indices. */ + typedef typename SimplexMeshGeometry::IndexArray IndexArray; - /** definition for a set of neighbor indices */ - typedef std::set<unsigned long> NeighborSetType; + /** definition for a set of neighbor indices */ + typedef std::set<unsigned long> NeighborSetType; - /** */ - typedef typename NeighborSetType::iterator NeighborSetIterator; + /** */ + typedef typename NeighborSetType::iterator NeighborSetIterator; - /** */ - typedef std::vector<unsigned long> NeighborListType; + /** */ + typedef std::vector<unsigned long> NeighborListType; - /** */ - typedef typename TMeshTraits::PointType PointType; + /** */ + typedef typename TMeshTraits::PointType PointType; - /** */ - typedef typename TMeshTraits::PointIdentifier PointIdentifier; + /** */ + typedef typename TMeshTraits::PointIdentifier PointIdentifier; - /** */ - typedef typename PointType::VectorType VectorType; + /** */ + typedef typename PointType::VectorType VectorType; - /** */ - typedef CovariantVector<typename VectorType::ValueType, 3> CovariantVectorType; + /** */ + typedef CovariantVector<typename VectorType::ValueType, 3> CovariantVectorType; + /** */ + typedef typename Superclass::CellType CellType; - /** */ - typedef typename Superclass::CellType CellType; + /** */ + typedef typename CellType::CellAutoPointer CellAutoPointer; + /** */ + typedef itk::LineCell<CellType> LineType; - /** */ - typedef typename CellType::CellAutoPointer CellAutoPointer; - /** */ - typedef itk::LineCell<CellType> LineType; + /** map containing a SimplexMeshGeometry data object for each mesh + * point */ + typedef itk::MapContainer<unsigned long, SimplexMeshGeometry *> GeometryMapType; - /** map containing a SimplexMeshGeometry data object for each mesh point*/ - typedef itk::MapContainer<unsigned long, SimplexMeshGeometry *> GeometryMapType; + /** smartpointer def for the geometry map */ + typedef typename GeometryMapType::Pointer GeometryMapPointer; - /** smartpointer def for the geometry map */ - typedef typename GeometryMapType::Pointer GeometryMapPointer; + /** iterator definition for iterating over a geometry map */ + typedef typename GeometryMapType::Iterator GeometryMapIterator; - /** iterator definition for iterating over a geometry map */ - typedef typename GeometryMapType::Iterator GeometryMapIterator; + /** Method for creation through the object factory. */ + itkNewMacro(Self); + /** Standard part of every itk Object. */ + itkTypeMacro(SimplexMesh, Mesh); - /** Method for creation through the object factory. */ - itkNewMacro(Self); + /** Hold on to the type information specified by the template parameters. */ + typedef TMeshTraits MeshTraits; + typedef typename MeshTraits::PixelType PixelType; + typedef typename MeshTraits::PointsContainer PointsContainer; + typedef typename Superclass::PointsContainerPointer PointsContainerPointer; + typedef typename Superclass::PointsContainer::Iterator PointsContainerIterator; + typedef typename Superclass::PointsContainerConstIterator PointsContainerConstIterator; + typedef typename Superclass::CellsContainerPointer CellsContainerPointer; + typedef typename Superclass::CellsContainerIterator CellsContainerIterator; + /** set the map of geometrydata to the new pointer */ + itkSetMacro(GeometryData, GeometryMapPointer ); - /** Standard part of every itk Object. */ - itkTypeMacro(SimplexMesh, Mesh); + /** returns the current map of geometrydata */ + itkGetConstReferenceMacro(GeometryData, GeometryMapPointer ); - /** Hold on to the type information specified by the template parameters. */ - typedef TMeshTraits MeshTraits; - typedef typename MeshTraits::PixelType PixelType; - typedef typename MeshTraits::PointsContainer PointsContainer; - typedef typename Superclass::PointsContainerPointer PointsContainerPointer; - typedef typename Superclass::PointsContainer::Iterator PointsContainerIterator; - typedef typename Superclass::PointsContainerConstIterator PointsContainerConstIterator; - typedef typename Superclass::CellsContainerPointer CellsContainerPointer; - typedef typename Superclass::CellsContainerIterator CellsContainerIterator; - /** set the map of geometrydata to the new pointer */ - itkSetMacro(GeometryData, GeometryMapPointer ); + /** Get the first free id for new cells */ + itkSetMacro(LastCellId, unsigned long); - /** returns the current map of geometrydata */ - itkGetConstReferenceMacro(GeometryData, GeometryMapPointer ); + /** Set the id value valid for new cells */ + itkGetConstMacro(LastCellId, unsigned long); - /** Get the first free id for new cells*/ - itkSetMacro(LastCellId, unsigned long); + /** + * copy all necessary information from passed object + * to the mesh + */ + virtual void CopyInformation(const DataObject *data); - /** Set the id value valid for new cells */ - itkGetMacro(LastCellId, unsigned long); - /** - * copy all necessary information from passed object - * to the mesh - */ - virtual void CopyInformation(const DataObject *data); + /** + * Add a new edge to the simplex mesh by specifying the ids of the start + * and end point of the edge + * Note: This can destroy the simplex mesh structure! Better use the + * simplex mesh modification or creation filters + */ + unsigned long AddEdge(unsigned long startPointId, unsigned long endPointId); - /** - * Add a new edge to the simplex mesh by specifying the ids of the start - * and end point of the edge - * Note: This can destroy the simplex mesh structure! Better use the - * simplex mesh modification or creation filters - */ - unsigned long AddEdge(unsigned long startPointId, unsigned long endPointId); + /** + * Add a new simplex mesh cell to the mesh by passing an AutoPointer of a + * previously created simplex mesh cell + * + * Note: This can destroy the simplex mesh structure! You should use the + * simplex mesh modification or creation filters. + */ + unsigned long AddFace(CellAutoPointer &cellPointer); - - /** - * Add a new simplex mesh cell to the mesh by passing an AutoPointer of a - * previously created simplex mesh cell - * - * Note: This can destroy the simplex mesh structure! You should use the - * simplex mesh modification or creation filters. - */ - unsigned long AddFace(CellAutoPointer &cellPointer); - - /** - * Replaces the cell specified by replaceIndex with the new cell passed by its - * AutoPopinter - */ + /** + * Replaces the cell specified by replaceIndex with the new cell passed by its + * AutoPopinter + */ unsigned long ReplaceFace(unsigned long replaceIndex, CellAutoPointer &cellPointer); - /** - * Get the three direct neighbors of a point - */ - IndexArray GetNeighbors(unsigned long pointId) const; - - /** - * Get all neighbor points with a specified radius - */ - NeighborListType* GetNeighbors(unsigned long pointId, unsigned int radius, NeighborListType* list = NULL) const; - - /** - * Add a neighbor to a point. - * Note: This can destroy the simplex mesh topology! - * Better use te simplex mesh creation filters. - */ - void AddNeighbor(unsigned long pointId, unsigned long neighborId); - - /** - * Replace a neighbor of a specific point by a new one - */ - void ReplaceNeighbor(unsigned long pointId, unsigned long oldNeighborId,unsigned long newNeighborIdx); - - /** - * Swap the order of two neighbors - */ - void SwapNeighbors(unsigned long pointId, unsigned long firstNeighborId,unsigned long secondNeighborId); - - /** - * Set the geometry data for a specified point - */ - void SetGeometryData(unsigned long pointId, SimplexMeshGeometry*); - - /** - * Set the geometry data for a specified point - */ - void SetBarycentricCoordinates(unsigned long idx, PointType values); - - /** - * Set the barycentric coordinates for a specified point - */ - PointType GetBarycentricCoordinates(unsigned long idx) const; - - /** - * Set the reference metrics for a specified point - */ - void SetReferenceMetrics(unsigned long idx, PointType values); - - /** - * Return the reference metrics for the specified point - */ - PointType GetReferenceMetrics(unsigned long idx) const; - - /** - * Set the simplex angle for the specified point - */ - void SetPhi(unsigned long idx, double values); - - /** - * Get the simplex angle for the specified point - */ - double GetPhi(unsigned long idx) const; - - /** - * Set the mean curvature for the specified point - */ - void SetMeanCurvature(unsigned long idx, double values); - - /** - * Get the mean curvature for the specified point - */ - double GetMeanCurvature(unsigned long idx) const; - - /** - * Set the circum circles radius for the specified point - */ - void SetRadius(unsigned long idx, double values); - - /** - * Get the circum circles radius for the specified point - */ - double GetRadius(unsigned long idx) const; - - /** - * Set the distance to the foot point for the specified point - */ - void SetDistance(unsigned long idx, double values); - - /** - * Get the distance to the foot point for the specified point - */ - double GetDistance(unsigned long idx) const; - - /** compute the normal vector in the specified mesh point */ - CovariantVectorType ComputeNormal(unsigned long idx ) const; - - protected: - // /** Constructor for use by New() method. */ - SimplexMesh(); - virtual ~SimplexMesh(); - void PrintSelf(std::ostream& os, Indent indent) const; - - /** - * The map stores a SimplexMeshGeometry object for each mesh point - */ - GeometryMapPointer m_GeometryData; - - /* */ - /** - * The last cell id is the index which is used for insertion of new - * cells. It increases during mesh creation. This is done because - * one cannot rely on the size of the map or the highest index when - * cells are removed. - */ - unsigned long m_LastCellId; - - - private: - SimplexMesh(const Self&); //purposely not implemented - // void operator=(const Self&); //purposely not implemented - - - - }; // End Class: SimplexMesh - - } // end namespace itk + /** + * Get the three direct neighbors of a point + */ + IndexArray GetNeighbors(unsigned long pointId) const; + + /** + * Get all neighbor points with a specified radius + */ + NeighborListType* GetNeighbors(unsigned long pointId, unsigned int radius, NeighborListType* list = NULL) const; + + /** + * Add a neighbor to a point. + * Note: This can destroy the simplex mesh topology! + * Better use te simplex mesh creation filters. + */ + void AddNeighbor(unsigned long pointId, unsigned long neighborId); + + /** + * Replace a neighbor of a specific point by a new one + */ + void ReplaceNeighbor(unsigned long pointId, unsigned long oldNeighborId,unsigned long newNeighborIdx); + + /** + * Swap the order of two neighbors + */ + void SwapNeighbors(unsigned long pointId, unsigned long firstNeighborId,unsigned long secondNeighborId); + + /** + * Set the geometry data for a specified point + */ + void SetGeometryData(unsigned long pointId, SimplexMeshGeometry*); + + /** + * Set the geometry data for a specified point + */ + void SetBarycentricCoordinates(unsigned long idx, PointType values); + + /** + * Set the barycentric coordinates for a specified point + */ + PointType GetBarycentricCoordinates(unsigned long idx) const; + + /** + * Set the reference metrics for a specified point + */ + void SetReferenceMetrics(unsigned long idx, PointType values); + + /** + * Return the reference metrics for the specified point + */ + PointType GetReferenceMetrics(unsigned long idx) const; + + /** + * Set the simplex angle for the specified point + */ + void SetPhi(unsigned long idx, double values); + + /** + * Get the simplex angle for the specified point + */ + double GetPhi(unsigned long idx) const; + + /** + * Set the mean curvature for the specified point + */ + void SetMeanCurvature(unsigned long idx, double values); + + /** + * Get the mean curvature for the specified point + */ + double GetMeanCurvature(unsigned long idx) const; + + /** + * Set the circum circles radius for the specified point + */ + void SetRadius(unsigned long idx, double values); + + /** + * Get the circum circles radius for the specified point + */ + double GetRadius(unsigned long idx) const; + + /** + * Set the distance to the foot point for the specified point + */ + void SetDistance(unsigned long idx, double values); + + /** + * Get the distance to the foot point for the specified point + */ + double GetDistance(unsigned long idx) const; + + /** compute the normal vector in the specified mesh point */ + CovariantVectorType ComputeNormal(unsigned long idx ) const; + +protected: + // /** Constructor for use by New() method. */ + SimplexMesh(); + virtual ~SimplexMesh(); + void PrintSelf(std::ostream& os, Indent indent) const; + + /** + * The map stores a SimplexMeshGeometry object for each mesh point + */ + GeometryMapPointer m_GeometryData; + + /** + * The last cell id is the index which is used for insertion of new + * cells. It increases during mesh creation. This is done because + * one cannot rely on the size of the map or the highest index when + * cells are removed. + */ + unsigned long m_LastCellId; + +private: + SimplexMesh(const Self&); //purposely not implemented + // void operator=(const Self&); //purposely not implemented +}; // End Class: SimplexMesh + +} // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkSimplexMesh.txx" diff --git a/Utilities/ITK/Code/Common/itkSimplexMesh.txx b/Utilities/ITK/Code/Common/itkSimplexMesh.txx index 4471ec6992..a82f6f3d3e 100644 --- a/Utilities/ITK/Code/Common/itkSimplexMesh.txx +++ b/Utilities/ITK/Code/Common/itkSimplexMesh.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMesh.txx,v $ Language: C++ -Date: $Date: 2007-04-14 11:54:34 $ -Version: $Revision: 1.21 $ +Date: $Date: 2009-03-03 15:09:26 $ +Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkSimplexMesh_txx -#define _itkSimplexMesh_txx +#ifndef __itkSimplexMesh_txx +#define __itkSimplexMesh_txx #include "itkSimplexMesh.h" @@ -46,8 +46,6 @@ SimplexMesh<TPixelType, VDimension, TMeshTraits> m_GeometryData = GeometryMapType::New(); } - - /** * Mesh Destructor takes care of releasing the memory of Cells * and CellBoundaries objects for which normal pointers are @@ -236,7 +234,7 @@ SimplexMesh<TPixelType, VDimension, TMeshTraits> { this->SetCell( m_LastCellId , cellPointer ); m_LastCellId++; - return m_LastCellId-1; + return m_LastCellId-1; } template <typename TPixelType, unsigned int VDimension, typename TMeshTraits> @@ -247,7 +245,7 @@ SimplexMesh<TPixelType, VDimension, TMeshTraits> this->GetCells()->DeleteIndex( replaceIndex ); this->SetCell( replaceIndex , cellPointer ); this->SetCellData( replaceIndex , (PixelType) 1.0 ); - return replaceIndex; + return replaceIndex; } /* PrintSelf. */ @@ -268,7 +266,7 @@ SimplexMesh<TPixelType, VDimension, TMeshTraits> { os << indent << "cell id: " << cellIt->Index() << ", point ids: "; CellType *nextCell = cellIt->Value(); - typename CellType::PointIdIterator pointIt = nextCell->PointIdsBegin() ; + typename CellType::PointIdIterator pointIt = nextCell->PointIdsBegin(); while (pointIt != nextCell->PointIdsEnd() ) { os << *pointIt++ << "-"; } os << std::endl; cellIt++; diff --git a/Utilities/ITK/Code/Common/itkSimplexMeshGeometry.cxx b/Utilities/ITK/Code/Common/itkSimplexMeshGeometry.cxx index da03b0e93b..7ef420e52b 100644 --- a/Utilities/ITK/Code/Common/itkSimplexMeshGeometry.cxx +++ b/Utilities/ITK/Code/Common/itkSimplexMeshGeometry.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshGeometry.cxx,v $ Language: C++ - Date: $Date: 2005-01-14 05:17:43 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:09:26 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -92,9 +92,8 @@ SimplexMeshGeometry bXd.SetVnlVector( cross_3d<double>(b.GetVnlVector(),d.GetVnlVector()) ); sphereTmp.SetVnlVector( d.GetSquaredNorm()* cXb.GetVnlVector() + - b.GetSquaredNorm()* dXc.GetVnlVector() + - c.GetSquaredNorm()* bXd.GetVnlVector() - ); + b.GetSquaredNorm()* dXc.GetVnlVector() + + c.GetSquaredNorm()* bXd.GetVnlVector()); double val = 2 * (c[0]*(b[1]*d[2]-b[2]*d[1]) - c[1]*( b[0]*d[2]-b[2]*d[0] ) + @@ -109,12 +108,10 @@ SimplexMeshGeometry sphereRadius = sphereTmp.GetNorm()/val; - if (sphereRadius < 0) { + if (sphereRadius < 0) + { sphereRadius = -1 * sphereRadius; - } + } } - - } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkSimplexMeshGeometry.h b/Utilities/ITK/Code/Common/itkSimplexMeshGeometry.h index 8419b84dcb..8dd6b6dc36 100644 --- a/Utilities/ITK/Code/Common/itkSimplexMeshGeometry.h +++ b/Utilities/ITK/Code/Common/itkSimplexMeshGeometry.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshGeometry.h,v $ Language: C++ - Date: $Date: 2006-04-01 13:44:21 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:09:26 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,18 +32,18 @@ namespace itk { /** - * \class SimplexMeshGeometry - * \brief handle geometric properties for vertices of a simplx mesh - * - * It stores and recomputes geometric properties of simplex mesh - * vertices, i.e. the normal vector, the barycentric coordinates of - * the point related to its three neighbor vertices, simplex angle - * circumsphere and circumcirlce radius and center. - * - * - * \author Thomas Boettger. Division Medical and Biological Informatics, German Cancer Research Center, Heidelberg. - * - */ + * \class SimplexMeshGeometry + * \brief handle geometric properties for vertices of a simplx mesh + * + * It stores and recomputes geometric properties of simplex mesh + * vertices, i.e. the normal vector, the barycentric coordinates of + * the point related to its three neighbor vertices, simplex angle + * circumsphere and circumcirlce radius and center. + * + * + * \author Thomas Boettger. Division Medical and Biological Informatics, German Cancer Research Center, Heidelberg. + * + */ class ITKCommon_EXPORT SimplexMeshGeometry { @@ -61,8 +61,8 @@ public: /** Definition of some attributes for - * faster deformable model computation - */ + * faster deformable model computation + */ /* stores the indices of the three direct neighbors */ IndexArray neighborIndices; @@ -79,12 +79,12 @@ public: /* coordinates of the corresponding point in previous iteration */ PointType oldPos; - /* barycentric coordinates of corresponding point with respect + /** barycentric coordinates of corresponding point with respect * to its three direct neighbors */ PointType eps; - /* + /** * reference metric params */ PointType referenceMetrics; @@ -92,22 +92,22 @@ public: /* normal vector of corresponding point */ CovariantVectorType normal; - /* stores external force component for + /** stores external force component for * current deformable model iteration */ VectorType externalForce; - /* stores internal force component for + /** stores internal force component for * current deformable model iteration */ VectorType internalForce; - /* + /** * store the location of the closest attractor to this point */ PointType closestAttractor; - /* + /** * stores the index of the closest attractor to this point */ unsigned long closestAttractorIndex; @@ -139,9 +139,9 @@ public: unsigned long forceIndex; /** - * Computes the center and radius of the circum circle of the - * three neighbor points and of the circum sphere - */ + * Computes the center and radius of the circum circle of the + * three neighbor points and of the circum sphere + */ void ComputeGeometry(); protected: diff --git a/Utilities/ITK/Code/Common/itkSize.h b/Utilities/ITK/Code/Common/itkSize.h index 9e984f0cdf..e06cd041d5 100644 --- a/Utilities/ITK/Code/Common/itkSize.h +++ b/Utilities/ITK/Code/Common/itkSize.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSize.h,v $ Language: C++ - Date: $Date: 2008-04-22 18:23:01 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-03-03 15:09:26 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -145,7 +145,7 @@ public: /** Get the size. This provides a read only reference to the size. * \sa SetSize */ - const SizeValueType *GetSize() const { return m_Size; }; + const SizeValueType *GetSize() const { return m_Size; } /** Set the size. * Try to prototype this function so that val has to point to a block of diff --git a/Utilities/ITK/Code/Common/itkSliceIterator.h b/Utilities/ITK/Code/Common/itkSliceIterator.h index 795b7811d5..c045630238 100644 --- a/Utilities/ITK/Code/Common/itkSliceIterator.h +++ b/Utilities/ITK/Code/Common/itkSliceIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSliceIterator.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:26 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-03 15:09:26 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,32 +52,32 @@ public: /** Returns a SliceIterator that points to the beginning of the slice. */ SliceIterator Begin() { - SliceIterator ans = *this; - ans.m_Pos = 0; - return ans; + SliceIterator ans = *this; + ans.m_Pos = 0; + return ans; } /** Returns a SliceIterator that points to one past the end of the slice. */ SliceIterator End() { - SliceIterator ans = *this; - ans.m_Pos = static_cast<unsigned long>(m_Slice.size()); - return ans; + SliceIterator ans = *this; + ans.m_Pos = static_cast<unsigned long>(m_Slice.size()); + return ans; } /** Increments the iterator. */ SliceIterator operator++() { - m_Pos++; - return *this; + m_Pos++; + return *this; } /** Increments the iterator. */ SliceIterator operator++(int) { - SliceIterator ans = *this; - m_Pos++; - return ans; + SliceIterator ans = *this; + m_Pos++; + return ans; } /** Returns the element at position n of the slice. Sets the @@ -94,9 +94,9 @@ public: * stride, and start locations. */ bool operator==(const SliceIterator &orig) { - return orig.m_Pos==this->m_Pos - && orig.m_Slice.stride()==this->m_Slice.stride() - && orig.m_Slice.start() ==this->m_Slice.start(); + return orig.m_Pos == this->m_Pos + && orig.m_Slice.stride() == this->m_Slice.stride() + && orig.m_Slice.start() == this->m_Slice.start(); } /** Returns the logical inverse of the boolean == of two slice iterators. */ @@ -110,18 +110,18 @@ public: * start location. */ bool operator<(const SliceIterator &orig) { - return this->m_Pos < orig.m_Pos - && this->m_Slice.stride()==orig.m_Slice.stride() - && this->m_Slice.start()==orig.m_Slice.start(); + return this->m_Pos < orig.m_Pos + && this->m_Slice.stride() == orig.m_Slice.stride() + && this->m_Slice.start() == orig.m_Slice.start(); } private: /** Returns the value located at position n of the slice. */ TPixel& Loc(unsigned long n) const { - const unsigned long start = static_cast<unsigned long>( m_Slice.start() ); - const unsigned long stride = static_cast<unsigned long>( m_Slice.stride() ); - return (*m_ContainerPointer)[ start + n * stride ]; + const unsigned long start = static_cast<unsigned long>( m_Slice.start() ); + const unsigned long stride = static_cast<unsigned long>( m_Slice.stride() ); + return (*m_ContainerPointer)[ start + n * stride ]; } /** Pointer to the container referenced by the slice iterator. */ diff --git a/Utilities/ITK/Code/Common/itkSmapsFileParser.cxx b/Utilities/ITK/Code/Common/itkSmapsFileParser.cxx index 91b56798d8..752965dd2d 100644 --- a/Utilities/ITK/Code/Common/itkSmapsFileParser.cxx +++ b/Utilities/ITK/Code/Common/itkSmapsFileParser.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSmapsFileParser.cxx,v $ Language: C++ - Date: $Date: 2008-10-24 18:11:22 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-05 10:56:46 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -16,6 +16,7 @@ =========================================================================*/ #include "itkSmapsFileParser.h" +#include <stdlib.h> namespace itk { @@ -282,7 +283,7 @@ ITKCommon_EXPORT std::istream& operator>>(std::istream &in, VMMapRecord &record) //bool ITKCommon_EXPORT ci_equal(char a, char b); // located in itkSmapsFileParser.cxx /** Binary functor to accumulate memory usage in kB -*/ + */ template<class TFirstType> struct MapRecordPlusor{ MapRecordPlusor<TFirstType>(const char * token = "Size") diff --git a/Utilities/ITK/Code/Common/itkSmartPointer.h b/Utilities/ITK/Code/Common/itkSmartPointer.h index bb01a208df..b44d0b6301 100644 --- a/Utilities/ITK/Code/Common/itkSmartPointer.h +++ b/Utilities/ITK/Code/Common/itkSmartPointer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSmartPointer.h,v $ Language: C++ - Date: $Date: 2008-05-16 20:15:32 $ - Version: $Revision: 1.39 $ + Date: $Date: 2009-03-03 15:09:28 $ + Version: $Revision: 1.40 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -56,7 +56,7 @@ public: /** Constructor to pointer p */ SmartPointer (ObjectType *p): m_Pointer(p) - { this->Register(); } + { this->Register(); } /** Destructor */ ~SmartPointer () @@ -75,17 +75,17 @@ public: /** Test if the pointer has been initialized */ bool IsNotNull() const - { return m_Pointer != 0; } + { return m_Pointer != 0; } bool IsNull() const - { return m_Pointer == 0; } + { return m_Pointer == 0; } /** Template comparison operators. */ - template <typename R> - bool operator == ( R r ) const + template <typename TR> + bool operator == ( TR r ) const { return (m_Pointer == static_cast<const ObjectType*>(r) ); } - template <typename R> - bool operator != ( R r ) const + template <typename TR> + bool operator != ( TR r ) const { return (m_Pointer != static_cast<const ObjectType*>(r) ); } /** Access function to pointer. */ @@ -114,7 +114,7 @@ public: /** Overload operator assignment. */ SmartPointer &operator = (ObjectType *r) - { + { if (m_Pointer != r) { ObjectType* tmp = m_Pointer; //avoid recursive unregisters by retaining temporarily diff --git a/Utilities/ITK/Code/Common/itkSmartPointerForwardReference.h b/Utilities/ITK/Code/Common/itkSmartPointerForwardReference.h index 1e8fba6995..67c6e72ae7 100644 --- a/Utilities/ITK/Code/Common/itkSmartPointerForwardReference.h +++ b/Utilities/ITK/Code/Common/itkSmartPointerForwardReference.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSmartPointerForwardReference.h,v $ Language: C++ - Date: $Date: 2006-03-06 15:07:34 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-03 15:09:30 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -106,12 +106,12 @@ private: }; - template <typename T> - std::ostream& operator<< (std::ostream& os, SmartPointerForwardReference<T> p) - { - p.Print(os); - return os; - } +template <typename T> +std::ostream& operator<< (std::ostream& os, SmartPointerForwardReference<T> p) +{ + p.Print(os); + return os; +} } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkSmartPointerForwardReference.txx b/Utilities/ITK/Code/Common/itkSmartPointerForwardReference.txx index e273da693e..edcb1edc5c 100644 --- a/Utilities/ITK/Code/Common/itkSmartPointerForwardReference.txx +++ b/Utilities/ITK/Code/Common/itkSmartPointerForwardReference.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSmartPointerForwardReference.txx,v $ Language: C++ - Date: $Date: 2006-03-06 15:07:34 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-03 15:09:30 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkSmartPointerForwardReference_txx -#define _itkSmartPointerForwardReference_txx +#ifndef __itkSmartPointerForwardReference_txx +#define __itkSmartPointerForwardReference_txx #include "itkSmartPointerForwardReference.h" @@ -47,7 +47,7 @@ SmartPointerForwardReference<T> { m_Pointer = p; this->Register(); -} +} //---------------------------------------------------------------------------- template <class T> @@ -142,7 +142,7 @@ template <class T> SmartPointerForwardReference<T> & SmartPointerForwardReference<T> ::operator = (T *r) -{ +{ if (m_Pointer != r) { T* tmp = m_Pointer; //avoid recursive unregisters by retaining temporarily diff --git a/Utilities/ITK/Code/Common/itkSmartPointerForwardReferenceProcessObject.cxx b/Utilities/ITK/Code/Common/itkSmartPointerForwardReferenceProcessObject.cxx index 5e41313643..e1f2ba2a88 100755 --- a/Utilities/ITK/Code/Common/itkSmartPointerForwardReferenceProcessObject.cxx +++ b/Utilities/ITK/Code/Common/itkSmartPointerForwardReferenceProcessObject.cxx @@ -1,9 +1,21 @@ -#include "itkSmartPointerForwardReference.h" -#include "itkSmartPointerForwardReference.txx" -#include "itkProcessObject.h" +/*========================================================================= -template class ITKCommon_EXPORT itk::SmartPointerForwardReference<itk::ProcessObject>; + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSmartPointerForwardReferenceProcessObject.cxx,v $ + Language: C++ + Date: $Date: 2009-03-03 15:09:30 $ + Version: $Revision: 1.2 $ + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. +=========================================================================*/ +#include "itkSmartPointerForwardReference.h" +#include "itkSmartPointerForwardReference.txx" +#include "itkProcessObject.h" +template class ITKCommon_EXPORT itk::SmartPointerForwardReference<itk::ProcessObject>; diff --git a/Utilities/ITK/Code/Common/itkSobelOperator.h b/Utilities/ITK/Code/Common/itkSobelOperator.h index 5c14badcc3..b34967e73c 100644 --- a/Utilities/ITK/Code/Common/itkSobelOperator.h +++ b/Utilities/ITK/Code/Common/itkSobelOperator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSobelOperator.h,v $ Language: C++ - Date: $Date: 2007-02-01 14:39:33 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-03 15:09:30 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,7 +49,7 @@ namespace itk { * \endverbatim * The Sobel Operator in horizonal direction is for 2 dimensions is * \verbatim - * -1 0 1 + * -1 0 1 * -2 0 2 * -1 0 1 * \endverbatim @@ -88,7 +88,7 @@ class ITK_EXPORT SobelOperator { public: /** Standard typedefs */ - typedef SobelOperator Self; + typedef SobelOperator Self; typedef NeighborhoodOperator<TPixel, VDimension, TAllocator> Superclass; itkTypeMacro(SobelOperator, NeighborhoodOperator); @@ -96,7 +96,7 @@ public: SobelOperator() {} SobelOperator(const Self& other) : NeighborhoodOperator<TPixel, VDimension, TAllocator>(other) - { } + {} /** Creates the operator with length only in the specified direction. For * the Sobel operator, this @@ -104,9 +104,9 @@ public: * the operator will work. * \sa CreateToRadius \sa FillCenteredDirectional \sa SetDirection() \sa GetDirection() */ virtual void CreateDirectional() - { + { this->CreateToRadius(1); - } + } /** Creates the operator with a specified radius ("square", same length * on each side). The spatial location of the coefficients within the @@ -125,10 +125,10 @@ public: * Prints some debugging information */ virtual void PrintSelf(std::ostream &os, Indent i) const - { + { os << i << "SobelOperator { this=" << this << "}" << std::endl; Superclass::PrintSelf(os, i.GetNextIndent()); - } + } protected: /** @@ -136,7 +136,7 @@ protected: * work around compiler bug on VC++. */ typedef typename Superclass::CoefficientVector CoefficientVector; - typedef typename Superclass::PixelType PixelType; + typedef typename Superclass::PixelType PixelType; /** * Calculates operator coefficients. @@ -168,5 +168,3 @@ protected: #endif #endif - - diff --git a/Utilities/ITK/Code/Common/itkSobelOperator.txx b/Utilities/ITK/Code/Common/itkSobelOperator.txx index c3781eaaa6..e782170386 100644 --- a/Utilities/ITK/Code/Common/itkSobelOperator.txx +++ b/Utilities/ITK/Code/Common/itkSobelOperator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSobelOperator.txx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:26 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-03-03 15:09:30 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkSobelOperator_txx -#define _itkSobelOperator_txx +#ifndef __itkSobelOperator_txx +#define __itkSobelOperator_txx #include "itkSobelOperator.h" #include "itkObject.h" @@ -38,41 +38,41 @@ SobelOperator <TPixel, VDimension, TAllocator> if (VDimension == 3) { - i = 0; - for (z = -1; z <= 1; z++) + i = 0; + for (z = -1; z <= 1; z++) + { + for (y = -1; y <= 1; y++ ) { - for (y = -1; y <= 1; y++ ) - { - for (x = -1; x <= 1; x++) - { - pos = center + z * this->GetStride(2) + y * this->GetStride(1) + - x * this->GetStride(0); - this->operator[](pos) = static_cast<TPixel>(coeff[i]); - i++; - } - } + for (x = -1; x <= 1; x++) + { + pos = center + z * this->GetStride(2) + y * this->GetStride(1) + + x * this->GetStride(0); + this->operator[](pos) = static_cast<TPixel>(coeff[i]); + i++; + } } + } } else if (VDimension == 2) { - i = 0; - for (y = -1; y <= 1; y++ ) + i = 0; + for (y = -1; y <= 1; y++ ) + { + for (x = -1; x <= 1; x++) { - for (x = -1; x <= 1; x++) - { - pos = center + y * this->GetStride(1) + x * this->GetStride(0); - this->operator[](pos) = static_cast<TPixel>(coeff[i]); - i++; - } - } + pos = center + y * this->GetStride(1) + x * this->GetStride(0); + this->operator[](pos) = static_cast<TPixel>(coeff[i]); + i++; + } + } } else { - itkExceptionMacro( << "The ND version of the Sobel operator is not yet implemented. Currently only the 2D and 3D versions are available." ); + itkExceptionMacro( << "The ND version of the Sobel operator is not yet implemented. Currently only the 2D and 3D versions are available." ); } } - + template <class TPixel, unsigned int VDimension, class TAllocator> typename SobelOperator<TPixel, VDimension, TAllocator> ::CoefficientVector @@ -82,61 +82,61 @@ SobelOperator<TPixel, VDimension, TAllocator> std::vector<double> coeff; if (VDimension == 2 && this->GetDirection() == 0) { - coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); - coeff.push_back(-2.0); coeff.push_back(0.0); coeff.push_back(2); - coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); + coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); + coeff.push_back(-2.0); coeff.push_back(0.0); coeff.push_back(2); + coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); } else if (VDimension == 2 && this->GetDirection() == 1) { - coeff.push_back(-1.0); coeff.push_back(-2); coeff.push_back(-1.0); - coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); - coeff.push_back(1.0); coeff.push_back(2); coeff.push_back(1.0); + coeff.push_back(-1.0); coeff.push_back(-2); coeff.push_back(-1.0); + coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); + coeff.push_back(1.0); coeff.push_back(2); coeff.push_back(1.0); } else if (VDimension == 3 && this->GetDirection() == 0) { - coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); - coeff.push_back(-3.0); coeff.push_back(0.0); coeff.push_back(3.0); - coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); - - coeff.push_back(-3.0); coeff.push_back(0.0); coeff.push_back(3.0); - coeff.push_back(-6.0); coeff.push_back(0.0); coeff.push_back(6.0); - coeff.push_back(-3.0); coeff.push_back(0.0); coeff.push_back(3.0); + coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); + coeff.push_back(-3.0); coeff.push_back(0.0); coeff.push_back(3.0); + coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); + + coeff.push_back(-3.0); coeff.push_back(0.0); coeff.push_back(3.0); + coeff.push_back(-6.0); coeff.push_back(0.0); coeff.push_back(6.0); + coeff.push_back(-3.0); coeff.push_back(0.0); coeff.push_back(3.0); - coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); - coeff.push_back(-3.0); coeff.push_back(0.0); coeff.push_back(3.0); - coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); + coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); + coeff.push_back(-3.0); coeff.push_back(0.0); coeff.push_back(3.0); + coeff.push_back(-1.0); coeff.push_back(0.0); coeff.push_back(1.0); } else if (VDimension == 3 && this->GetDirection() == 1) { - coeff.push_back(-1.0); coeff.push_back(-3.0); coeff.push_back(-1.0); - coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); - coeff.push_back(1.0); coeff.push_back(3.0); coeff.push_back(1.0); + coeff.push_back(-1.0); coeff.push_back(-3.0); coeff.push_back(-1.0); + coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); + coeff.push_back(1.0); coeff.push_back(3.0); coeff.push_back(1.0); - coeff.push_back(-3.0); coeff.push_back(-6.0); coeff.push_back(-3.0); - coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); - coeff.push_back(3.0); coeff.push_back(6.0); coeff.push_back(3.0); + coeff.push_back(-3.0); coeff.push_back(-6.0); coeff.push_back(-3.0); + coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); + coeff.push_back(3.0); coeff.push_back(6.0); coeff.push_back(3.0); - coeff.push_back(-1.0); coeff.push_back(-3.0); coeff.push_back(-1.0); - coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); - coeff.push_back(1.0); coeff.push_back(3.0); coeff.push_back(1.0); + coeff.push_back(-1.0); coeff.push_back(-3.0); coeff.push_back(-1.0); + coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); + coeff.push_back(1.0); coeff.push_back(3.0); coeff.push_back(1.0); } else if (VDimension == 3 && this->GetDirection() == 2) { - coeff.push_back(-1.0); coeff.push_back(-3.0); coeff.push_back(-1.0); - coeff.push_back(-3.0); coeff.push_back(-6.0); coeff.push_back(-3.0); - coeff.push_back(-1.0); coeff.push_back(-3.0); coeff.push_back(-1.0); + coeff.push_back(-1.0); coeff.push_back(-3.0); coeff.push_back(-1.0); + coeff.push_back(-3.0); coeff.push_back(-6.0); coeff.push_back(-3.0); + coeff.push_back(-1.0); coeff.push_back(-3.0); coeff.push_back(-1.0); - coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); - coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); - coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); + coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); + coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); + coeff.push_back(0.0); coeff.push_back(0.0); coeff.push_back(0.0); - coeff.push_back(1.0); coeff.push_back(3.0); coeff.push_back(1.0); - coeff.push_back(3.0); coeff.push_back(6.0); coeff.push_back(3.0); - coeff.push_back(1.0); coeff.push_back(3.0); coeff.push_back(1.0); + coeff.push_back(1.0); coeff.push_back(3.0); coeff.push_back(1.0); + coeff.push_back(3.0); coeff.push_back(6.0); coeff.push_back(3.0); + coeff.push_back(1.0); coeff.push_back(3.0); coeff.push_back(1.0); } else { - itkExceptionMacro( << "The ND version of the Sobel operator has not been implemented. Currently only 2D and 3D versions are available." ); + itkExceptionMacro( << "The ND version of the Sobel operator has not been implemented. Currently only 2D and 3D versions are available." ); } return coeff; diff --git a/Utilities/ITK/Code/Common/itkSparseImage.h b/Utilities/ITK/Code/Common/itkSparseImage.h index fdc32b23ce..c76edcf3b8 100644 --- a/Utilities/ITK/Code/Common/itkSparseImage.h +++ b/Utilities/ITK/Code/Common/itkSparseImage.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSparseImage.h,v $ Language: C++ - Date: $Date: 2005-12-28 19:08:07 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-03 15:09:32 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkSparseImage_h_ -#define __itkSparseImage_h_ +#ifndef __itkSparseImage_h +#define __itkSparseImage_h #include "itkImage.h" #include "itkSparseFieldLayer.h" @@ -50,13 +50,13 @@ namespace itk { template <class TNode, unsigned int VImageDimension=2> class ITK_EXPORT SparseImage : public Image <TNode*, VImageDimension> { - public: +public: /** Standard typedefs. */ - typedef SparseImage Self; + typedef SparseImage Self; typedef Image <TNode*, VImageDimension> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; - typedef WeakPointer<const Self> ConstWeakPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef WeakPointer<const Self> ConstWeakPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -74,13 +74,14 @@ class ITK_EXPORT SparseImage : public Image <TNode*, VImageDimension> /** Types derived from the Superclass */ typedef typename Superclass::IndexType IndexType; - /** Tyepdef for the functor used to access a neighborhood of pixel pointers.*/ + /** Tyepdef for the functor used to access a neighborhood of pixel + * pointers. */ typedef NeighborhoodAccessorFunctor< Self > NeighborhoodAccessorFunctorType; typedef typename Superclass::IOPixelType IOPixelType; - /** The list types for storing the active pixels.*/ + /** The list types for storing the active pixels. */ typedef SparseFieldLayer <NodeType> NodeListType; typedef ObjectStore <NodeType> NodeStoreType; @@ -97,20 +98,20 @@ class ITK_EXPORT SparseImage : public Image <TNode*, VImageDimension> /** This function should be used to allocate memory for a variable at the desired pixel location. */ NodeType *AddNode(const IndexType &index) - { + { m_NodeList->PushFront(m_NodeStore->Borrow()); NodeType *node = m_NodeList->Front(); node->m_Index=index; this->SetPixel(index,node); return node; - } + } /** This function returns the allocated node list which can be used to iterate through the valid nodes. */ NodeListType* GetNodeList() - { - return m_NodeList; - } + { + return m_NodeList; + } /** This function initializes the m_NodeList and m_NodeStore variables, and calls the superclass Initialize method. */ diff --git a/Utilities/ITK/Code/Common/itkSparseImage.txx b/Utilities/ITK/Code/Common/itkSparseImage.txx index dbe8112368..9e405f855f 100644 --- a/Utilities/ITK/Code/Common/itkSparseImage.txx +++ b/Utilities/ITK/Code/Common/itkSparseImage.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSparseImage.txx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:26 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:09:33 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkSparseImage_txx_ -#define __itkSparseImage_txx_ +#ifndef __itkSparseImage_txx +#define __itkSparseImage_txx #include "itkSparseImage.h" #include "itkSparseFieldLayer.h" diff --git a/Utilities/ITK/Code/Common/itkSpatialFunction.h b/Utilities/ITK/Code/Common/itkSpatialFunction.h index 0dc691661e..0b380da237 100644 --- a/Utilities/ITK/Code/Common/itkSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkSpatialFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialFunction.h,v $ Language: C++ - Date: $Date: 2007-01-30 23:39:53 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-03-03 15:09:33 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,10 +47,10 @@ class ITK_EXPORT SpatialFunction : public FunctionBase<TInput, TOutput> { public: /** Standard class typedefs. */ - typedef SpatialFunction Self; + typedef SpatialFunction Self; typedef FunctionBase< TInput, TOutput> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(SpatialFunction, FunctionBase); diff --git a/Utilities/ITK/Code/Common/itkSpatialOrientation.h b/Utilities/ITK/Code/Common/itkSpatialOrientation.h index b720d4ff57..e6822b771b 100644 --- a/Utilities/ITK/Code/Common/itkSpatialOrientation.h +++ b/Utilities/ITK/Code/Common/itkSpatialOrientation.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialOrientation.h,v $ Language: C++ - Date: $Date: 2007-04-29 16:30:20 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:09:33 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,282 +24,281 @@ namespace itk { namespace SpatialOrientation { - // Coordinate orientation codes have a place-value organization such that - // an ImageDimension-al sequence of subcodes says both which varies fastest - // through which varies slowest, but also which end of the frame of - // reference - // is considered zero for each of the coordinates. For example, 'RIP' - // means - // Right to Left varies fastest, then Inferior to Superior, and Posterior - // to - // Anterior varies the slowest. - typedef enum { - ITK_COORDINATE_UNKNOWN=0, - ITK_COORDINATE_Right=2, - ITK_COORDINATE_Left=3, - ITK_COORDINATE_Posterior=4, //back - ITK_COORDINATE_Anterior=5, //front - ITK_COORDINATE_Inferior=8, //below - ITK_COORDINATE_Superior=9 //above - // ITK_COORDINATE_Historical=16, - // ITK_COORDINATE_Future=17 - } CoordinateTerms; +// Coordinate orientation codes have a place-value organization such that +// an ImageDimension-al sequence of subcodes says both which varies fastest +// through which varies slowest, but also which end of the frame of +// reference +// is considered zero for each of the coordinates. For example, 'RIP' +// means +// Right to Left varies fastest, then Inferior to Superior, and Posterior +// to +// Anterior varies the slowest. +typedef enum { + ITK_COORDINATE_UNKNOWN=0, + ITK_COORDINATE_Right=2, + ITK_COORDINATE_Left=3, + ITK_COORDINATE_Posterior=4, //back + ITK_COORDINATE_Anterior=5, //front + ITK_COORDINATE_Inferior=8, //below + ITK_COORDINATE_Superior=9 //above + // ITK_COORDINATE_Historical=16, + // ITK_COORDINATE_Future=17 +} CoordinateTerms; - typedef enum { - // These code place values have to be far enough apart to - // separate the CoordinateTerms above. - // However, if we added History/Future direction in time, - // we would need at least 5 bits per. - ITK_COORDINATE_PrimaryMinor=0, - ITK_COORDINATE_SecondaryMinor=8, - ITK_COORDINATE_TertiaryMinor=16 - // Majorness is in terms of rank-minor because a - // fourth dimension, time, would be even More major than the - // PrimaryMajor==TertiaryMinor. - // ITK_COORDINATE_QuaternaryMinor=24 - } CoordinateMajornessTerms; - // Adding time IN GENERAL would make these 8 x 6 = 48 triples into 16 - // x 24 = 384 4-tuples. - // A general fourth dimension would need a unique pair of letters to - // add to the code; - // Maybe use H and F, from History to Future? Maybe use 48 x 2 with - // time ALWAYS highest - // order, or 48 x 2 x 2, with 3-space always highest or lowest order? - // Multispectra might be - // co-registered and pieced together.... PD-T2 interleaving of - // slices is handled with choosing - // which spectrum to load via the prototypical file name. - typedef enum { - ITK_COORDINATE_ORIENTATION_INVALID=ITK_COORDINATE_UNKNOWN, - ITK_COORDINATE_ORIENTATION_RIP = (ITK_COORDINATE_Right - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_LIP = (ITK_COORDINATE_Left - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_RSP = (ITK_COORDINATE_Right - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_LSP = (ITK_COORDINATE_Left - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_RIA = (ITK_COORDINATE_Right - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_LIA = (ITK_COORDINATE_Left - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_RSA = (ITK_COORDINATE_Right - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_LSA = (ITK_COORDINATE_Left - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), +typedef enum { + // These code place values have to be far enough apart to + // separate the CoordinateTerms above. + // However, if we added History/Future direction in time, + // we would need at least 5 bits per. + ITK_COORDINATE_PrimaryMinor=0, + ITK_COORDINATE_SecondaryMinor=8, + ITK_COORDINATE_TertiaryMinor=16 + // Majorness is in terms of rank-minor because a + // fourth dimension, time, would be even More major than the + // PrimaryMajor==TertiaryMinor. + // ITK_COORDINATE_QuaternaryMinor=24 +} CoordinateMajornessTerms; +// Adding time IN GENERAL would make these 8 x 6 = 48 triples into 16 +// x 24 = 384 4-tuples. +// A general fourth dimension would need a unique pair of letters to +// add to the code; +// Maybe use H and F, from History to Future? Maybe use 48 x 2 with +// time ALWAYS highest +// order, or 48 x 2 x 2, with 3-space always highest or lowest order? +// Multispectra might be +// co-registered and pieced together.... PD-T2 interleaving of +// slices is handled with choosing +// which spectrum to load via the prototypical file name. +typedef enum { + ITK_COORDINATE_ORIENTATION_INVALID=ITK_COORDINATE_UNKNOWN, + ITK_COORDINATE_ORIENTATION_RIP = (ITK_COORDINATE_Right + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_LIP = (ITK_COORDINATE_Left + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_RSP = (ITK_COORDINATE_Right + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_LSP = (ITK_COORDINATE_Left + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_RIA = (ITK_COORDINATE_Right + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_LIA = (ITK_COORDINATE_Left + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_RSA = (ITK_COORDINATE_Right + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_LSA = (ITK_COORDINATE_Left + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), + + ITK_COORDINATE_ORIENTATION_IRP = (ITK_COORDINATE_Inferior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_ILP = (ITK_COORDINATE_Inferior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_SRP = (ITK_COORDINATE_Superior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_SLP = (ITK_COORDINATE_Superior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_IRA = (ITK_COORDINATE_Inferior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_ILA = (ITK_COORDINATE_Inferior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_SRA = (ITK_COORDINATE_Superior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_SLA = (ITK_COORDINATE_Superior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_IRP = (ITK_COORDINATE_Inferior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_ILP = (ITK_COORDINATE_Inferior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_SRP = (ITK_COORDINATE_Superior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_SLP = (ITK_COORDINATE_Superior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_IRA = (ITK_COORDINATE_Inferior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_ILA = (ITK_COORDINATE_Inferior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_SRA = (ITK_COORDINATE_Superior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_SLA = (ITK_COORDINATE_Superior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_RPI = (ITK_COORDINATE_Right + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_LPI = (ITK_COORDINATE_Left + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_RAI = (ITK_COORDINATE_Right + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_LAI = (ITK_COORDINATE_Left + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_RPS = (ITK_COORDINATE_Right + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_LPS = (ITK_COORDINATE_Left + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_RAS = (ITK_COORDINATE_Right + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_LAS = (ITK_COORDINATE_Left + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_RPI = (ITK_COORDINATE_Right - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_LPI = (ITK_COORDINATE_Left - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_RAI = (ITK_COORDINATE_Right - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_LAI = (ITK_COORDINATE_Left - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_RPS = (ITK_COORDINATE_Right - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_LPS = (ITK_COORDINATE_Left - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_RAS = (ITK_COORDINATE_Right - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_LAS = (ITK_COORDINATE_Left - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_PRI = (ITK_COORDINATE_Posterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_PLI = (ITK_COORDINATE_Posterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_ARI = (ITK_COORDINATE_Anterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_ALI = (ITK_COORDINATE_Anterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_PRS = (ITK_COORDINATE_Posterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_PLS = (ITK_COORDINATE_Posterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_ARS = (ITK_COORDINATE_Anterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_ALS = (ITK_COORDINATE_Anterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_PRI = (ITK_COORDINATE_Posterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_PLI = (ITK_COORDINATE_Posterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_ARI = (ITK_COORDINATE_Anterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_ALI = (ITK_COORDINATE_Anterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_PRS = (ITK_COORDINATE_Posterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_PLS = (ITK_COORDINATE_Posterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_ARS = (ITK_COORDINATE_Anterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_ALS = (ITK_COORDINATE_Anterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_IPR = (ITK_COORDINATE_Inferior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_SPR = (ITK_COORDINATE_Superior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_IAR = (ITK_COORDINATE_Inferior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_SAR = (ITK_COORDINATE_Superior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_IPL = (ITK_COORDINATE_Inferior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_SPL = (ITK_COORDINATE_Superior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_IAL = (ITK_COORDINATE_Inferior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_SAL = (ITK_COORDINATE_Superior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_IPR = (ITK_COORDINATE_Inferior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_SPR = (ITK_COORDINATE_Superior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_IAR = (ITK_COORDINATE_Inferior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_SAR = (ITK_COORDINATE_Superior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_IPL = (ITK_COORDINATE_Inferior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_SPL = (ITK_COORDINATE_Superior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Posterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_IAL = (ITK_COORDINATE_Inferior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_SAL = (ITK_COORDINATE_Superior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Anterior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), - - ITK_COORDINATE_ORIENTATION_PIR = (ITK_COORDINATE_Posterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_PSR = (ITK_COORDINATE_Posterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_AIR = (ITK_COORDINATE_Anterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_ASR = (ITK_COORDINATE_Anterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_PIL = (ITK_COORDINATE_Posterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_PSL = (ITK_COORDINATE_Posterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_AIL = (ITK_COORDINATE_Anterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), - ITK_COORDINATE_ORIENTATION_ASL = (ITK_COORDINATE_Anterior - << ITK_COORDINATE_PrimaryMinor) - + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) - + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor) - } ValidCoordinateOrientationFlags; + ITK_COORDINATE_ORIENTATION_PIR = (ITK_COORDINATE_Posterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_PSR = (ITK_COORDINATE_Posterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_AIR = (ITK_COORDINATE_Anterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_ASR = (ITK_COORDINATE_Anterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Right << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_PIL = (ITK_COORDINATE_Posterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_PSL = (ITK_COORDINATE_Posterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_AIL = (ITK_COORDINATE_Anterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Inferior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor), + ITK_COORDINATE_ORIENTATION_ASL = (ITK_COORDINATE_Anterior + << ITK_COORDINATE_PrimaryMinor) + + (ITK_COORDINATE_Superior << ITK_COORDINATE_SecondaryMinor) + + (ITK_COORDINATE_Left << ITK_COORDINATE_TertiaryMinor) +} ValidCoordinateOrientationFlags; // ^^^ // ||| -// ||\Sequential indexes are separated by (planes=rows*columns) memory +// ||\Sequential indexes are separated by (planes=rows*columns) memory // locations -// |\Sequential indexes are separated by rows memory locations (sweep out +// |\Sequential indexes are separated by rows memory locations (sweep out // a plane) // \Sequential indexes are adjacent memory locations (sweep out a row) #ifndef __TEMPORARILY_INCLUDED_IN_COMPILATIONS__ - typedef enum { - ITK_ORIGIN_IRP =0, /**< Denotes a zeroCorner (image origin) */ - /* is Inferior Right Posterior */ - ITK_ORIGIN_IRA =1, /**< Denotes a zeroCorner (image origin) */ - /* is Inferior Right Anterior */ - ITK_ORIGIN_ILP =2, /**< Denotes a zeroCorner (image origin) */ - /* is Inferior Left Posterior */ - ITK_ORIGIN_ILA =3, /**< Denotes a zeroCorner (image origin) */ - /* is Inferior Left Anterior */ - ITK_ORIGIN_SRP =4, /**< Denotes a zeroCorner (image origin) */ - /* is Superior Right Posterior */ - ITK_ORIGIN_SRA =5, /**< Denotes a zeroCorner (image origin) */ - /* is Superior Right Anterior */ - ITK_ORIGIN_SLP =6, /**< Denotes a zeroCorner (image origin) */ - /* is Superior Left Posterior */ - ITK_ORIGIN_SLA =7 /**< Denotes a zeroCorner (image origin) */ - /* is Superior Left Anterior */ - } ValidOriginFlags; +typedef enum { + ITK_ORIGIN_IRP =0, /**< Denotes a zeroCorner (image origin) */ + /* is Inferior Right Posterior */ + ITK_ORIGIN_IRA =1, /**< Denotes a zeroCorner (image origin) */ + /* is Inferior Right Anterior */ + ITK_ORIGIN_ILP =2, /**< Denotes a zeroCorner (image origin) */ + /* is Inferior Left Posterior */ + ITK_ORIGIN_ILA =3, /**< Denotes a zeroCorner (image origin) */ + /* is Inferior Left Anterior */ + ITK_ORIGIN_SRP =4, /**< Denotes a zeroCorner (image origin) */ + /* is Superior Right Posterior */ + ITK_ORIGIN_SRA =5, /**< Denotes a zeroCorner (image origin) */ + /* is Superior Right Anterior */ + ITK_ORIGIN_SLP =6, /**< Denotes a zeroCorner (image origin) */ + /* is Superior Left Posterior */ + ITK_ORIGIN_SLA =7 /**< Denotes a zeroCorner (image origin) */ + /* is Superior Left Anterior */ +} ValidOriginFlags; #endif } // end of namespace SpatialOrientation } // end namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkSpatialOrientationAdapter.cxx b/Utilities/ITK/Code/Common/itkSpatialOrientationAdapter.cxx index 2f5be4b788..f84180757a 100644 --- a/Utilities/ITK/Code/Common/itkSpatialOrientationAdapter.cxx +++ b/Utilities/ITK/Code/Common/itkSpatialOrientationAdapter.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialOrientationAdapter.cxx,v $ Language: C++ - Date: $Date: 2007-12-24 16:46:28 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:09:34 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -136,4 +136,3 @@ SpatialOrientationAdapter } } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkSpatialOrientationAdapter.h b/Utilities/ITK/Code/Common/itkSpatialOrientationAdapter.h index 2a8f042a0b..abaa1dcb96 100644 --- a/Utilities/ITK/Code/Common/itkSpatialOrientationAdapter.h +++ b/Utilities/ITK/Code/Common/itkSpatialOrientationAdapter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialOrientationAdapter.h,v $ Language: C++ - Date: $Date: 2007-12-24 16:46:28 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:09:35 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -67,8 +67,6 @@ inline int Sign(double x) } // namespace Function - - /** \class SpatialOrientationAdapter * \brief converts SpatialOrientation flags to/from direction cosines */ diff --git a/Utilities/ITK/Code/Common/itkSpecialCoordinatesImage.h b/Utilities/ITK/Code/Common/itkSpecialCoordinatesImage.h index 1a6e84f127..396714e55a 100644 --- a/Utilities/ITK/Code/Common/itkSpecialCoordinatesImage.h +++ b/Utilities/ITK/Code/Common/itkSpecialCoordinatesImage.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpecialCoordinatesImage.h,v $ Language: C++ - Date: $Date: 2008-10-19 12:33:32 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-03-03 15:09:37 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -99,9 +99,9 @@ public: /** Standard class typedefs */ typedef SpecialCoordinatesImage Self; typedef ImageBase<VImageDimension> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; - typedef WeakPointer<const Self> ConstWeakPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef WeakPointer<const Self> ConstWeakPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -114,7 +114,7 @@ public: typedef TPixel PixelType; /** Typedef alias for PixelType */ - typedef TPixel ValueType ; + typedef TPixel ValueType; /** Internal Pixel representation. Used to maintain a uniform API * with Image Adaptors and allow to keep a particular internal @@ -130,7 +130,7 @@ public: /** Accessor functor to choose between accessors: DefaultPixelAccessor for * the Image, and DefaultVectorPixelAccessor for the vector image. The - * functor provides a generic API between the two accessors.*/ + * functor provides a generic API between the two accessors. */ typedef DefaultPixelAccessorFunctor< Self > AccessorFunctorType; /** Dimension of the image. This constant is used by functions that are @@ -165,7 +165,7 @@ public: typedef typename Superclass::PointType PointType; /** A pointer to the pixel container. */ - typedef typename PixelContainer::Pointer PixelContainerPointer; + typedef typename PixelContainer::Pointer PixelContainerPointer; typedef typename PixelContainer::ConstPointer PixelContainerConstPointer; /** Allocate the image memory. The size of the image must @@ -188,7 +188,7 @@ public: this->SetLargestPossibleRegion(region); this->SetBufferedRegion(region); this->SetRequestedRegion(region); - }; + } /** Restore the data object to its initial state. This means releasing * memory. */ @@ -214,10 +214,10 @@ public: * For efficiency, this function does not check that the * image has actually been allocated yet. */ const TPixel& GetPixel(const IndexType &index) const - { + { typename Superclass::OffsetValueType offset = this->ComputeOffset(index); return ( (*m_Buffer)[offset] ); - } + } /** \brief Get a reference to a pixel (e.g. for editing). * @@ -234,7 +234,7 @@ public: * For efficiency, this function does not check that the * image has actually been allocated yet. */ TPixel & operator[](const IndexType &index) - { return this->GetPixel(index); } + { return this->GetPixel(index); } /** \brief Access a pixel. This version can only be an rvalue. * @@ -335,4 +335,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Common/itkSpecialCoordinatesImage.txx b/Utilities/ITK/Code/Common/itkSpecialCoordinatesImage.txx index a8b8d8de7b..373a387f8d 100644 --- a/Utilities/ITK/Code/Common/itkSpecialCoordinatesImage.txx +++ b/Utilities/ITK/Code/Common/itkSpecialCoordinatesImage.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpecialCoordinatesImage.txx,v $ Language: C++ - Date: $Date: 2004-10-26 13:22:24 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-03-03 15:09:40 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,8 +17,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkSpecialCoordinatesImage_txx -#define _itkSpecialCoordinatesImage_txx +#ifndef __itkSpecialCoordinatesImage_txx +#define __itkSpecialCoordinatesImage_txx #include "itkSpecialCoordinatesImage.h" #include "itkProcessObject.h" #include "itkAffineTransform.h" @@ -111,7 +111,7 @@ SpecialCoordinatesImage<TPixel, VImageDimension> os << indent << "PixelContainer: " << std::endl; m_Buffer->Print(os, indent.GetNextIndent()); -// m_Origin and m_Spacing are printed in the Superclass + // m_Origin and m_Spacing are printed in the Superclass } diff --git a/Utilities/ITK/Code/Common/itkSphereSignedDistanceFunction.h b/Utilities/ITK/Code/Common/itkSphereSignedDistanceFunction.h index 856f26af1a..dcb4411cbe 100644 --- a/Utilities/ITK/Code/Common/itkSphereSignedDistanceFunction.h +++ b/Utilities/ITK/Code/Common/itkSphereSignedDistanceFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSphereSignedDistanceFunction.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-03 15:09:42 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,15 +44,15 @@ class ITK_EXPORT SphereSignedDistanceFunction : { public: /** Standard class typedefs. */ - typedef SphereSignedDistanceFunction Self; + typedef SphereSignedDistanceFunction Self; typedef ShapeSignedDistanceFunction< TCoordRep, VSpaceDimension > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(SphereSignedDistanceFunction, ShapeSignedDistancFunction); - /** New macro for creation of through the object factory.*/ + /** New macro for creation of through the object factory. */ itkNewMacro( Self ); /** OutputType typedef support. */ diff --git a/Utilities/ITK/Code/Common/itkSphereSpatialFunction.h b/Utilities/ITK/Code/Common/itkSphereSpatialFunction.h index 8ad47b8df7..5eb0395347 100644 --- a/Utilities/ITK/Code/Common/itkSphereSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkSphereSpatialFunction.h @@ -1,11 +1,10 @@ - /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSphereSpatialFunction.h,v $ Language: C++ - Date: $Date: 2007-01-30 23:39:53 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,11 +36,11 @@ class ITK_EXPORT SphereSpatialFunction { public: /** Standard class typedefs. */ - typedef SphereSpatialFunction<VImageDimension,TInput> Self; + typedef SphereSpatialFunction<VImageDimension,TInput> Self; typedef InteriorExteriorSpatialFunction<VImageDimension,TInput> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; - + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -58,11 +57,11 @@ public: OutputType Evaluate(const InputType& position) const; /** Get and set the center of the sphere. */ - itkGetMacro( Center, InputType); + itkGetConstMacro( Center, InputType); itkSetMacro( Center, InputType); /** Get and set the radius of the sphere */ - itkGetMacro( Radius, double); + itkGetConstMacro( Radius, double); itkSetMacro( Radius, double); protected: diff --git a/Utilities/ITK/Code/Common/itkStdStreamLogOutput.cxx b/Utilities/ITK/Code/Common/itkStdStreamLogOutput.cxx index 14db60efe0..91eaf72f55 100644 --- a/Utilities/ITK/Code/Common/itkStdStreamLogOutput.cxx +++ b/Utilities/ITK/Code/Common/itkStdStreamLogOutput.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkStdStreamLogOutput.cxx,v $ Language: C++ - Date: $Date: 2005-05-28 12:50:24 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,9 +32,9 @@ StdStreamLogOutput::StdStreamLogOutput() StdStreamLogOutput::~StdStreamLogOutput() { if( this->m_Stream ) - { + { this->m_Stream->flush(); - } + } } @@ -51,9 +51,9 @@ void StdStreamLogOutput::Flush() { StdStreamLogOutput::m_Mutex.Lock(); if( this->m_Stream ) - { + { this->m_Stream->flush(); - } + } StdStreamLogOutput::m_Mutex.Unlock(); } @@ -63,9 +63,9 @@ void StdStreamLogOutput::Write(double timestamp) { StdStreamLogOutput::m_Mutex.Lock(); if( this->m_Stream ) - { + { (*this->m_Stream) << timestamp; - } + } StdStreamLogOutput::m_Mutex.Unlock(); } @@ -96,8 +96,7 @@ void StdStreamLogOutput::Write(std::string const &content, double timestamp) void StdStreamLogOutput::PrintSelf(std::ostream &os, Indent indent) const { Superclass::PrintSelf(os,indent); - os << indent << "Stream: " << m_Stream << std::endl;; + os << indent << "Stream: " << m_Stream << std::endl; } } - diff --git a/Utilities/ITK/Code/Common/itkStdStreamLogOutput.h b/Utilities/ITK/Code/Common/itkStdStreamLogOutput.h index ed70bfe835..d96f99f18d 100644 --- a/Utilities/ITK/Code/Common/itkStdStreamLogOutput.h +++ b/Utilities/ITK/Code/Common/itkStdStreamLogOutput.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkStdStreamLogOutput.h,v $ Language: C++ - Date: $Date: 2006-02-05 20:57:46 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,7 +39,7 @@ namespace itk * ISIS Center, Georgetown University. * * - * \ingroup OSSystemObjects LoggingObjects + * \ingroup OSSystemObjects LoggingObjects */ class ITKCommon_EXPORT StdStreamLogOutput : public LogOutput @@ -47,9 +47,9 @@ class ITKCommon_EXPORT StdStreamLogOutput : public LogOutput public: - typedef StdStreamLogOutput Self; - typedef LogOutput Superclass; - typedef SmartPointer<Self> Pointer; + typedef StdStreamLogOutput Self; + typedef LogOutput Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; typedef std::ostream StreamType; @@ -59,7 +59,7 @@ public: itkNewMacro(StdStreamLogOutput); - itkGetMacro(Stream, StreamPointerType); + itkGetConstMacro(Stream, StreamPointerType); /** Set a standard stream pointer */ void SetStream(StreamType &Stream); diff --git a/Utilities/ITK/Code/Common/itkSumOfSquaresImageFunction.h b/Utilities/ITK/Code/Common/itkSumOfSquaresImageFunction.h index 6343a0a66d..54e54a0eca 100755 --- a/Utilities/ITK/Code/Common/itkSumOfSquaresImageFunction.h +++ b/Utilities/ITK/Code/Common/itkSumOfSquaresImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSumOfSquaresImageFunction.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,8 +48,8 @@ public: /** Standard class typedefs. */ typedef SumOfSquaresImageFunction Self; typedef ImageFunction<TInputImage, ITK_TYPENAME NumericTraits<typename TInputImage::PixelType>::RealType, - TCoordRep > Superclass; - typedef SmartPointer<Self> Pointer; + TCoordRep > Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ @@ -87,16 +87,16 @@ public: /** Evaluate the function at non-integer positions */ virtual RealType Evaluate( const PointType& point ) const { - IndexType index; - this->ConvertPointToNearestIndex( point, index ); - return this->EvaluateAtIndex( index ); + IndexType index; + this->ConvertPointToNearestIndex( point, index ); + return this->EvaluateAtIndex( index ); } virtual RealType EvaluateAtContinuousIndex( const ContinuousIndexType& cindex ) const { - IndexType index; - this->ConvertContinuousIndexToNearestIndex( cindex, index ); - return this->EvaluateAtIndex( index ) ; + IndexType index; + this->ConvertContinuousIndexToNearestIndex( cindex, index ); + return this->EvaluateAtIndex( index ); } /** Get/Set the radius of the neighborhood over which the @@ -104,7 +104,7 @@ public: itkGetConstReferenceMacro( NeighborhoodRadius, unsigned int ); void SetNeighborhoodRadius(unsigned int radius) - { + { m_NeighborhoodRadius = radius; m_NeighborhoodSize = 1; @@ -113,7 +113,7 @@ public: { m_NeighborhoodSize *= twoRPlus1; } - } + } itkGetConstReferenceMacro(NeighborhoodSize, unsigned int); @@ -149,4 +149,3 @@ private: #endif - diff --git a/Utilities/ITK/Code/Common/itkSumOfSquaresImageFunction.txx b/Utilities/ITK/Code/Common/itkSumOfSquaresImageFunction.txx index 8978b1c8d1..4f3d67836d 100755 --- a/Utilities/ITK/Code/Common/itkSumOfSquaresImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkSumOfSquaresImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSumOfSquaresImageFunction.txx,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -89,7 +89,7 @@ SumOfSquaresImageFunction<TInputImage,TCoordRep> for (unsigned int i = 0; i < size; ++i) { const RealType value = static_cast<RealType>( it.GetPixel(i) ); - sumOfSquares += value * value; + sumOfSquares += value * value; } return ( sumOfSquares ); diff --git a/Utilities/ITK/Code/Common/itkSymmetricEigenAnalysis.h b/Utilities/ITK/Code/Common/itkSymmetricEigenAnalysis.h index b12a2d65f1..7da95d874a 100644 --- a/Utilities/ITK/Code/Common/itkSymmetricEigenAnalysis.h +++ b/Utilities/ITK/Code/Common/itkSymmetricEigenAnalysis.h @@ -3,14 +3,14 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSymmetricEigenAnalysis.h,v $ Language: C++ - Date: $Date: 2005-07-09 22:43:35 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -21,27 +21,27 @@ namespace itk { - + /** \class SymmetricEigenAnalysis * \brief Find Eigen values of a real 2D symmetric matrix. It * serves as a thread safe alternative to the class: * vnl_symmetric_eigensystem, which uses netlib routines. * * The class is templated over the input matrix, (which is expected to provide - * access to its elements with the [][] operator), matrix to store eigen - * values, (must provide write operations on its elements with the [] operator), - * EigenMatrix to store eigen vectors (must provide write access to its elements + * access to its elements with the [][] operator), matrix to store eigen + * values, (must provide write operations on its elements with the [] operator), + * EigenMatrix to store eigen vectors (must provide write access to its elements * with the [][] operator). - * + * * The SetOrderEigenValues() method can be used to order eigen values (and their - * corresponding eigen vectors if computed) in ascending order. This is the + * corresponding eigen vectors if computed) in ascending order. This is the * default ordering scheme. Eigen vectors and values can be obtained without * ordering by calling SetOrderEigenValues(false) * - * The SetOrderEigenMagnitudes() method can be used to order eigen values (and + * The SetOrderEigenMagnitudes() method can be used to order eigen values (and * their corresponding eigen vectors if computed) by magnitude in ascending order. * - * The user of this class is explicitly supposed to set the dimension of the + * The user of this class is explicitly supposed to set the dimension of the * 2D matrix using the SetDimension() method. * * The class contains routines taken from netlib sources. (www.netlib.org). @@ -49,12 +49,12 @@ namespace itk * netlib/tql2.c * netlib/tred1.c * netlib/tred2.c - * + * * Reference: - * num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and - * wilkinson. - * handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). - */ + * num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and + * wilkinson. + * handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). + */ template < typename TMatrix, typename TVector, typename TEigenMatrix=TMatrix > class SymmetricEigenAnalysis @@ -65,18 +65,18 @@ public: OrderByMagnitude, DoNotOrder }EigenValueOrderType; - + SymmetricEigenAnalysis(): m_Dimension(0), m_Order(0), m_OrderEigenValues(OrderByValue) - {} ; - + {}; + SymmetricEigenAnalysis( const unsigned int dimension ): m_Dimension(dimension), m_Order(dimension), m_OrderEigenValues(OrderByValue) - {} ; + {}; ~SymmetricEigenAnalysis() {}; @@ -84,14 +84,12 @@ public: typedef TEigenMatrix EigenMatrixType; typedef TVector VectorType; - - - /** Compute Eigen values of A - * A is any type that overloads the [][] operator and contains the + /** Compute Eigen values of A + * A is any type that overloads the [][] operator and contains the * symmetric matrix. In practice only the upper triangle of the - * matrix will be accessed. (Both itk::Matrix and vnl_matrix + * matrix will be accessed. (Both itk::Matrix and vnl_matrix * overload [][] operator.) - * + * * 'EigenValues' is any type that overloads the [] operator and will contain * the eigen values. * @@ -99,27 +97,27 @@ public: * m_Dimension. 'EigenValues' is expected to be of length m_Dimension. * The matrix is not checked to see if it is symmetric. */ - unsigned int ComputeEigenValues( + unsigned int ComputeEigenValues( const TMatrix & A, TVector & EigenValues) const; - - /** Compute Eigen values and vectors of A - * A is any type that overloads the [][] operator and contains the + + /** Compute Eigen values and vectors of A + * A is any type that overloads the [][] operator and contains the * symmetric matrix. In practice only the upper triangle of the - * matrix will be accessed. (Both itk::Matrix and vnl_matrix + * matrix will be accessed. (Both itk::Matrix and vnl_matrix * overload [][] operator.) - * + * * 'EigenValues' is any type that overloads the [] operator and will contain * the eigen values. * - * 'EigenVectors' is any type that provides access to its elements with the + * 'EigenVectors' is any type that provides access to its elements with the * [][] operator. It is expected be of size m_Dimension * m_Dimension. * * No size checking is performed. A is expected to be a square matrix of size * m_Dimension. 'EigenValues' is expected to be of length m_Dimension. * The matrix is not checked to see if it is symmetric. * - * Each row of the matrix 'EigenVectors' represents an eigen vector. (unlike MATLAB + * Each row of the matrix 'EigenVectors' represents an eigen vector. (unlike MATLAB * where the columns of the [EigenVectors, EigenValues] = eig(A) contains the * eigenvectors). */ @@ -128,189 +126,185 @@ public: TVector & EigenValues, TEigenMatrix & EigenVectors ) const; - - /** Matrix order. Defaults to matrix dimension if not set **/ + + /** Matrix order. Defaults to matrix dimension if not set */ void SetOrder(const unsigned int n) { m_Order = n; } - + /** Get the Matrix order. Will be 0 unless explicitly set, or unless a * call to SetDimension has been made in which case it will be the * matrix dimension. */ unsigned int GetOrder() const { return m_Order; } - /** Set/Get methods to order the eigen values in ascending order. + /** Set/Get methods to order the eigen values in ascending order. * This is the default. ie lambda_1 < lambda_2 < .... */ - void SetOrderEigenValues( const bool b ) - { + void SetOrderEigenValues( const bool b ) + { if (b) { m_OrderEigenValues = OrderByValue; } else { m_OrderEigenValues = DoNotOrder; } } bool GetOrderEigenValues() const { return (m_OrderEigenValues == OrderByValue); } - /** Set/Get methods to order the eigen value magnitudes in ascending order. + /** Set/Get methods to order the eigen value magnitudes in ascending order. * In other words, |lambda_1| < |lambda_2| < ..... */ - void SetOrderEigenMagnitudes( const bool b ) - { + void SetOrderEigenMagnitudes( const bool b ) + { if (b) { m_OrderEigenValues = OrderByMagnitude; } else { m_OrderEigenValues = DoNotOrder; } - } + } bool GetOrderEigenMagnitudes() const { return (m_OrderEigenValues == OrderByMagnitude); } - /** Set the dimension of the input matrix A. A is a square matrix of + /** Set the dimension of the input matrix A. A is a square matrix of * size m_Dimension. */ void SetDimension( const unsigned int n ) { m_Dimension = n; - if (m_Order == 0 ) + if (m_Order == 0 ) { m_Order = m_Dimension; } } - - /** Get Matrix dimension, Will be 0 unless explicitly set by a + + /** Get Matrix dimension, Will be 0 unless explicitly set by a * call to SetDimension. */ unsigned int GetDimension() const { return m_Dimension; } private: - unsigned int m_Dimension; - unsigned int m_Order; - EigenValueOrderType m_OrderEigenValues; + unsigned int m_Dimension; + unsigned int m_Order; + EigenValueOrderType m_OrderEigenValues; + - /** Reduces a real symmetric matrix to a symmetric tridiagonal matrix using * orthogonal similarity transformations. - * 'inputMatrix' contains the real symmetric input matrix. Only the lower + * 'inputMatrix' contains the real symmetric input matrix. Only the lower * triangle of the matrix need be supplied. The upper triangle is unaltered. - * 'd' contains the diagonal elements of the tridiagonal matrix. - * 'e' contains the subdiagonal elements of the tridiagonal matrix in its - * last n-1 positions. e(1) is set to zero. - * 'e2' contains the squares of the corresponding elements of e. - * 'e2' may coincide with e if the squares are not needed. + * 'd' contains the diagonal elements of the tridiagonal matrix. + * 'e' contains the subdiagonal elements of the tridiagonal matrix in its + * last n-1 positions. e(1) is set to zero. + * 'e2' contains the squares of the corresponding elements of e. + * 'e2' may coincide with e if the squares are not needed. * questions and comments should be directed to burton s. garbow. - * mathematics and computer science div, argonne national laboratory - * this version dated august 1983. + * mathematics and computer science div, argonne national laboratory + * this version dated august 1983. * - * Function Adapted from netlib/tred1.c. - * [Changed: remove static vars, enforce const correctness. - * Use vnl routines as necessary]. + * Function Adapted from netlib/tred1.c. + * [Changed: remove static vars, enforce const correctness. + * Use vnl routines as necessary]. * Reference: - * num. math. 11, 181-195(1968) by martin, reinsch, and wilkinson. + * num. math. 11, 181-195(1968) by martin, reinsch, and wilkinson. * handbook for auto. comp., vol.ii-linear algebra, 212-226(1971). */ - void ReduceToTridiagonalMatrix(double *inputMatrix, VectorType &d, + void ReduceToTridiagonalMatrix(double *inputMatrix, VectorType &d, double *e, double *e2) const; - - /** Reduces a real symmetric matrix to a symmetric tridiagonal matrix using * and accumulating orthogonal similarity transformations. - * 'inputMatrix' contains the real symmetric input matrix. Only the lower + * 'inputMatrix' contains the real symmetric input matrix. Only the lower * triangle of the matrix need be supplied. The upper triangle is unaltered. - * 'diagonalElements' will contains the diagonal elements of the tridiagonal - * matrix. - * 'subDiagonalElements' will contain the subdiagonal elements of the tridiagonal - * matrix in its last n-1 positions. subDiagonalElements(1) is set to zero. - * 'transformMatrix' contains the orthogonal transformation matrix produced - * in the reduction. - * + * 'diagonalElements' will contains the diagonal elements of the tridiagonal + * matrix. + * 'subDiagonalElements' will contain the subdiagonal elements of the tridiagonal + * matrix in its last n-1 positions. subDiagonalElements(1) is set to zero. + * 'transformMatrix' contains the orthogonal transformation matrix produced + * in the reduction. + * * questions and comments should be directed to burton s. garbow. - * mathematics and computer science div, argonne national laboratory - * this version dated august 1983. + * mathematics and computer science div, argonne national laboratory + * this version dated august 1983. * - * Function Adapted from netlib/tred2.c. - * [Changed: remove static vars, enforce const correctness. - * Use vnl routines as necessary]. + * Function Adapted from netlib/tred2.c. + * [Changed: remove static vars, enforce const correctness. + * Use vnl routines as necessary]. * Reference: - * num. math. 11, 181-195(1968) by martin, reinsch, and wilkinson. + * num. math. 11, 181-195(1968) by martin, reinsch, and wilkinson. * handbook for auto. comp., vol.ii-linear algebra, 212-226(1971). */ void ReduceToTridiagonalMatrixAndGetTransformation( - double *inputMatrix, VectorType &diagonalElements, + double *inputMatrix, VectorType &diagonalElements, double *subDiagonalElements, double *transformMatrix) const; - - /* Finds the eigenvalues of a symmetric tridiagonal matrix by the ql method. * * On input: - * 'd' contains the diagonal elements of the input matrix. - * 'e' contains the subdiagonal elements of the input matrix - * in its last n-1 positions. e(1) is arbitrary. + * 'd' contains the diagonal elements of the input matrix. + * 'e' contains the subdiagonal elements of the input matrix + * in its last n-1 positions. e(1) is arbitrary. * On Output: * 'd' contains the eigenvalues. - * 'e' has been destroyed. - * - * Returns: - * zero for normal return, - * j if the j-th eigenvalue has not been - * determined after 30 iterations. - * - * + * 'e' has been destroyed. + * + * Returns: + * zero for normal return, + * j if the j-th eigenvalue has not been + * determined after 30 iterations. + * + * * Reference - * this subroutine is a translation of the algol procedure tql1, - * num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and - * wilkinson. - * handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). - * - * Questions and comments should be directed to burton s. garbow, - * mathematics and computer science div, argonne national laboratory - * this version dated august 1983. - * - * Function Adapted from netlib/tql1.c. - * [Changed: remove static vars, enforce const correctness. + * this subroutine is a translation of the algol procedure tql1, + * num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and + * wilkinson. + * handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). + * + * Questions and comments should be directed to burton s. garbow, + * mathematics and computer science div, argonne national laboratory + * this version dated august 1983. + * + * Function Adapted from netlib/tql1.c. + * [Changed: remove static vars, enforce const correctness. * Use vnl routines as necessary] */ unsigned int ComputeEigenValuesUsingQL( VectorType &d, double *e) const; - - /* Finds the eigenvalues and eigenvectors of a symmetric tridiagonal matrix + + /* Finds the eigenvalues and eigenvectors of a symmetric tridiagonal matrix * by the ql method. * * On input: - * 'd' contains the diagonal elements of the input matrix. - * 'e' contains the subdiagonal elements of the input matrix - * in its last n-1 positions. e(1) is arbitrary. - * 'z' contains the transformation matrix produced in the reduction by - * ReduceToTridiagonalMatrixAndGetTransformation(), if performed. If the - * eigenvectors of the tridiagonal matrix are desired, z must contain - * the identity matrix. + * 'd' contains the diagonal elements of the input matrix. + * 'e' contains the subdiagonal elements of the input matrix + * in its last n-1 positions. e(1) is arbitrary. + * 'z' contains the transformation matrix produced in the reduction by + * ReduceToTridiagonalMatrixAndGetTransformation(), if performed. If the + * eigenvectors of the tridiagonal matrix are desired, z must contain + * the identity matrix. * On Output: * 'd' contains the eigenvalues. - * 'e' has been destroyed. - * 'z' contains orthonormal eigenvectors of the symmetric tridiagonal - * (or full) matrix. - * - * Returns: - * zero for normal return, - * j if the j-th eigenvalue has not been - * determined after 1000 iterations. - * + * 'e' has been destroyed. + * 'z' contains orthonormal eigenvectors of the symmetric tridiagonal + * (or full) matrix. + * + * Returns: + * zero for normal return, + * j if the j-th eigenvalue has not been + * determined after 1000 iterations. + * * Reference - * this subroutine is a translation of the algol procedure tql1, - * num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and - * wilkinson. - * handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). - * - * Questions and comments should be directed to burton s. garbow, - * mathematics and computer science div, argonne national laboratory - * this version dated august 1983. - * - * Function Adapted from netlib/tql2.c. - * [Changed: remove static vars, enforce const correctness. - * Use vnl routines as necessary] + * this subroutine is a translation of the algol procedure tql1, + * num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and + * wilkinson. + * handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). + * + * Questions and comments should be directed to burton s. garbow, + * mathematics and computer science div, argonne national laboratory + * this version dated august 1983. + * + * Function Adapted from netlib/tql2.c. + * [Changed: remove static vars, enforce const correctness. + * Use vnl routines as necessary] */ unsigned int ComputeEigenValuesAndVectorsUsingQL( VectorType &d, double *e, double *z) const; - + }; template< typename TMatrix, typename TVector, typename TEigenMatrix > -std::ostream & operator<<(std::ostream& os, - const SymmetricEigenAnalysis< TMatrix, TVector, TEigenMatrix > &s) +std::ostream & operator<<(std::ostream& os, + const SymmetricEigenAnalysis< TMatrix, TVector, TEigenMatrix > &s) { os << "[ClassType: SymmetricEigenAnalysis]" << std::endl; os << " Dimension : " << s.GetDimension() << std::endl; @@ -328,4 +322,3 @@ std::ostream & operator<<(std::ostream& os, #endif #endif - diff --git a/Utilities/ITK/Code/Common/itkSymmetricEigenAnalysis.txx b/Utilities/ITK/Code/Common/itkSymmetricEigenAnalysis.txx index 4930825db5..15c92ba507 100644 --- a/Utilities/ITK/Code/Common/itkSymmetricEigenAnalysis.txx +++ b/Utilities/ITK/Code/Common/itkSymmetricEigenAnalysis.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSymmetricEigenAnalysis.txx,v $ Language: C++ - Date: $Date: 2006-11-08 23:39:12 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -101,9 +101,6 @@ ComputeEigenValuesAndVectors( return eigenErrIndex; //index of eigen value that could not be computed } - - - template< class TMatrix, class TVector, class TEigenMatrix > void SymmetricEigenAnalysis< TMatrix, TVector, TEigenMatrix >:: @@ -221,8 +218,6 @@ ReduceToTridiagonalMatrix(double * a, VectorType &d, } } - - template< class TMatrix, class TVector, class TEigenMatrix > void SymmetricEigenAnalysis< TMatrix, TVector, TEigenMatrix >:: @@ -387,8 +382,6 @@ ReduceToTridiagonalMatrixAndGetTransformation(double * a, VectorType &d, } - - template< class TMatrix, class TVector, class TEigenMatrix > unsigned int SymmetricEigenAnalysis< TMatrix, TVector, TEigenMatrix >:: @@ -406,13 +399,15 @@ ComputeEigenValuesUsingQL(VectorType &d, double *e) const double tst1, tst2; unsigned int ierr = 0; - if (m_Order == 1) { - return 1; - } + if (m_Order == 1) + { + return 1; + } - for (i = 1; i < m_Order; ++i) { - e[i-1] = e[i]; - } + for (i = 1; i < m_Order; ++i) + { + e[i-1] = e[i]; + } f = 0.; tst1 = 0.; @@ -440,7 +435,6 @@ ComputeEigenValuesUsingQL(VectorType &d, double *e) const if (m != l) { - do { if (j == 30) @@ -532,8 +526,6 @@ ComputeEigenValuesUsingQL(VectorType &d, double *e) const } - - template< class TMatrix, class TVector, class TEigenMatrix > unsigned int SymmetricEigenAnalysis< TMatrix, TVector, TEigenMatrix >:: @@ -677,7 +669,7 @@ ComputeEigenValuesAndVectorsUsingQL(VectorType &d, double *e, double *z) const } k = j; p = d[j]; - } + } if (k == i) { @@ -710,7 +702,7 @@ ComputeEigenValuesAndVectorsUsingQL(VectorType &d, double *e, double *z) const } k = j; p = d[j]; - } + } if (k == i) { @@ -732,9 +724,6 @@ ComputeEigenValuesAndVectorsUsingQL(VectorType &d, double *e, double *z) const return ierr; } - - } // end namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h b/Utilities/ITK/Code/Common/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h index 648d445ca4..90e24f185a 100644 --- a/Utilities/ITK/Code/Common/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h,v $ Language: C++ - Date: $Date: 2007-01-30 23:39:53 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,10 +42,10 @@ class ITK_EXPORT SymmetricEllipsoidInteriorExteriorSpatialFunction: public: /** Standard class typedefs. */ typedef SymmetricEllipsoidInteriorExteriorSpatialFunction Self; - typedef InteriorExteriorSpatialFunction<VDimension> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; - typedef Vector<double,VDimension> VectorType; + typedef InteriorExteriorSpatialFunction<VDimension> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef Vector<double,VDimension> VectorType; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -63,7 +63,7 @@ public: OutputType Evaluate(const InputType& position) const; /** Get and set the center of the ellipsoid. */ - itkGetMacro(Center, InputType); + itkGetConstMacro(Center, InputType); itkSetMacro(Center, InputType); /** Set the orientation vector of the ellipsoid's unique axis and axes lengths. diff --git a/Utilities/ITK/Code/Common/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.txx b/Utilities/ITK/Code/Common/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.txx index 8d0ce67766..daba151eba 100644 --- a/Utilities/ITK/Code/Common/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.txx +++ b/Utilities/ITK/Code/Common/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSymmetricEllipsoidInteriorExteriorSpatialFunction.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:36:59 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkSymmetricEllipsoidInteriorExteriorSpatialFunction_cpp -#define __itkSymmetricEllipsoidInteriorExteriorSpatialFunction_cpp +#ifndef __itkSymmetricEllipsoidInteriorExteriorSpatialFunction_txx +#define __itkSymmetricEllipsoidInteriorExteriorSpatialFunction_txx #include "itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h" #include <math.h> @@ -45,8 +45,8 @@ typename SymmetricEllipsoidInteriorExteriorSpatialFunction<VDimension, TInput>:: SymmetricEllipsoidInteriorExteriorSpatialFunction<VDimension, TInput> ::Evaluate(const InputType& position) const { - double uniqueTerm; // Term in ellipsoid equation for unique axis - double symmetricTerm; // Term in ellipsoid equation for symmetric axes + double uniqueTerm; // Term in ellipsoid equation for unique axis + double symmetricTerm; // Term in ellipsoid equation for symmetric axes Vector<double, VDimension> pointVector; Vector<double, VDimension> symmetricVector; @@ -62,8 +62,8 @@ SymmetricEllipsoidInteriorExteriorSpatialFunction<VDimension, TInput> symmetricTerm = vcl_pow(static_cast<double>(((symmetricVector.GetNorm())/(.5*m_SymmetricAxes))),static_cast<double>(2)); if((uniqueTerm + symmetricTerm) >= 0 && (uniqueTerm + symmetricTerm) <= 1) - { - return 1; // Inside the ellipsoid. + { + return 1; // Inside the ellipsoid. } //Default return value assumes outside the ellipsoid return 0; // Outside the ellipsoid. diff --git a/Utilities/ITK/Code/Common/itkSymmetricSecondRankTensor.h b/Utilities/ITK/Code/Common/itkSymmetricSecondRankTensor.h index 921d06e512..d48b852f31 100644 --- a/Utilities/ITK/Code/Common/itkSymmetricSecondRankTensor.h +++ b/Utilities/ITK/Code/Common/itkSymmetricSecondRankTensor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSymmetricSecondRankTensor.h,v $ Language: C++ - Date: $Date: 2008-03-10 22:48:13 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,8 +95,8 @@ public: typedef Matrix<TComponent, NDimension, NDimension> EigenVectorsMatrixType; /** Define the component type. */ - typedef TComponent ComponentType; - typedef typename Superclass::ValueType ValueType; + typedef TComponent ComponentType; + typedef typename Superclass::ValueType ValueType; typedef typename NumericTraits<ValueType>::RealType AccumulateValueType; typedef typename NumericTraits<ValueType>::RealType RealValueType; @@ -112,7 +112,7 @@ public: /** Pass-through constructor for the Array base class. */ SymmetricSecondRankTensor(const Self& r): BaseArray(r) {} - SymmetricSecondRankTensor(const ComponentArrayType r): BaseArray(r) {} + SymmetricSecondRankTensor(const ComponentArrayType r): BaseArray(r) {} /** Pass-through assignment operator for the Array base class. */ Self& operator= (const Self& r); diff --git a/Utilities/ITK/Code/Common/itkSymmetricSecondRankTensor.txx b/Utilities/ITK/Code/Common/itkSymmetricSecondRankTensor.txx index 7624ae0679..9ff8e1a358 100644 --- a/Utilities/ITK/Code/Common/itkSymmetricSecondRankTensor.txx +++ b/Utilities/ITK/Code/Common/itkSymmetricSecondRankTensor.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSymmetricSecondRankTensor.txx,v $ Language: C++ - Date: $Date: 2008-03-10 22:48:13 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkSymmetricSecondRankTensor_txx -#define _itkSymmetricSecondRankTensor_txx +#ifndef __itkSymmetricSecondRankTensor_txx +#define __itkSymmetricSecondRankTensor_txx #include "itkSymmetricSecondRankTensor.h" #include "itkNumericTraitsTensorPixel.h" @@ -23,7 +23,7 @@ namespace itk { -/* +/** * Assignment Operator */ template<class T,unsigned int NDimension> @@ -36,7 +36,7 @@ SymmetricSecondRankTensor<T,NDimension> } -/* +/** * Assignment Operator from a scalar constant */ template<class T,unsigned int NDimension> @@ -49,7 +49,7 @@ SymmetricSecondRankTensor<T,NDimension> } -/* +/** * Assigment from a plain array */ template<class T,unsigned int NDimension> @@ -61,8 +61,6 @@ SymmetricSecondRankTensor<T,NDimension> return *this; } - - /** * Returns a temporary copy of a vector */ @@ -79,9 +77,6 @@ SymmetricSecondRankTensor<T,NDimension> return result; } - - - /** * Returns a temporary copy of a vector */ @@ -97,8 +92,6 @@ SymmetricSecondRankTensor<T,NDimension> } return result; } - - /** * Performs addition in place @@ -115,9 +108,6 @@ SymmetricSecondRankTensor<T,NDimension> return *this; } - - - /** * Performs subtraction in place */ @@ -133,8 +123,6 @@ SymmetricSecondRankTensor<T,NDimension> return *this; } - - /** * Performs multiplication by a scalar, in place */ @@ -150,8 +138,6 @@ SymmetricSecondRankTensor<T,NDimension> return *this; } - - /** * Performs division by a scalar, in place */ @@ -167,9 +153,6 @@ SymmetricSecondRankTensor<T,NDimension> return *this; } - - - /** * Performs multiplication with a scalar */ @@ -186,7 +169,6 @@ SymmetricSecondRankTensor<T,NDimension> return result; } - /** * Performs division by a scalar */ @@ -203,8 +185,7 @@ SymmetricSecondRankTensor<T,NDimension> return result; } - -/* +/** * Matrix notation access to elements */ template<class T,unsigned int NDimension> @@ -233,8 +214,7 @@ SymmetricSecondRankTensor<T,NDimension> } - -/* +/** * Matrix notation access to elements */ template<class T,unsigned int NDimension> @@ -262,8 +242,7 @@ SymmetricSecondRankTensor<T,NDimension> return (*this)[k]; } - -/* +/** * Set the Tensor to an Identity. * Set ones in the diagonal and zeroes every where else. */ @@ -280,7 +259,7 @@ SymmetricSecondRankTensor<T,NDimension> } -/* +/** * Get the Trace */ template<class T,unsigned int NDimension> @@ -299,7 +278,7 @@ SymmetricSecondRankTensor<T,NDimension> } -/* +/** * Compute Eigen Values */ template<class T,unsigned int NDimension> @@ -323,7 +302,7 @@ SymmetricSecondRankTensor<T,NDimension> } -/* +/** * Compute Eigen analysis, it returns an array with eigen values * and a Matrix with eigen vectors */ @@ -349,7 +328,7 @@ SymmetricSecondRankTensor<T,NDimension> } -/* +/** * Pre-multiply the Tensor by a Matrix */ template<class T,unsigned int NDimension> @@ -357,24 +336,24 @@ SymmetricSecondRankTensor<T,NDimension> SymmetricSecondRankTensor<T,NDimension> ::PreMultiply( const MatrixType & m ) const { -Self result; -typedef typename NumericTraits<T>::AccumulateType AccumulateType; -for(unsigned int r=0; r<NDimension; r++) - { - for(unsigned int c=0; c<NDimension; c++) + Self result; + typedef typename NumericTraits<T>::AccumulateType AccumulateType; + for(unsigned int r=0; r<NDimension; r++) { - AccumulateType sum = NumericTraits<AccumulateType>::ZeroValue(); - for(unsigned int t=0; t<NDimension; t++) + for(unsigned int c=0; c<NDimension; c++) { - sum += m(r,t) * (*this)(t,c); + AccumulateType sum = NumericTraits<AccumulateType>::ZeroValue(); + for(unsigned int t=0; t<NDimension; t++) + { + sum += m(r,t) * (*this)(t,c); + } + result(r,c) = static_cast<T>( sum ); } - result(r,c) = static_cast<T>( sum ); } - } -return result; + return result; } -/* +/** * Post-multiply the Tensor by a Matrix */ template<class T,unsigned int NDimension> @@ -382,26 +361,23 @@ SymmetricSecondRankTensor<T,NDimension> SymmetricSecondRankTensor<T,NDimension> ::PostMultiply( const MatrixType & m ) const { -Self result; -typedef typename NumericTraits<T>::AccumulateType AccumulateType; -for(unsigned int r=0; r<NDimension; r++) - { - for(unsigned int c=0; c<NDimension; c++) + Self result; + typedef typename NumericTraits<T>::AccumulateType AccumulateType; + for(unsigned int r=0; r<NDimension; r++) { - AccumulateType sum = NumericTraits<AccumulateType>::ZeroValue(); - for(unsigned int t=0; t<NDimension; t++) + for(unsigned int c=0; c<NDimension; c++) { - sum += (*this)(r,t) * m(t,c); + AccumulateType sum = NumericTraits<AccumulateType>::ZeroValue(); + for(unsigned int t=0; t<NDimension; t++) + { + sum += (*this)(r,t) * m(t,c); + } + result(r,c) = static_cast<T>( sum ); } - result(r,c) = static_cast<T>( sum ); } - } -return result; + return result; } - - - /** * Print content to an ostream */ diff --git a/Utilities/ITK/Code/Common/itkTanImageAdaptor.h b/Utilities/ITK/Code/Common/itkTanImageAdaptor.h index de573ceb94..b4c5fc3d4e 100644 --- a/Utilities/ITK/Code/Common/itkTanImageAdaptor.h +++ b/Utilities/ITK/Code/Common/itkTanImageAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTanImageAdaptor.h,v $ Language: C++ - Date: $Date: 2006-03-19 04:36:59 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,12 +73,12 @@ class ITK_EXPORT TanImageAdaptor : public { public: /** Standard class typedefs. */ - typedef TanImageAdaptor Self; + typedef TanImageAdaptor Self; typedef ImageAdaptor<TImage,Accessor::TanPixelAccessor< typename TImage::PixelType, TOutputPixelType> > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -86,11 +86,11 @@ public: /** Run-time type information (and related methods). */ itkTypeMacro( TanImageAdaptor, ImageAdaptor ); - protected: +protected: TanImageAdaptor() {} virtual ~TanImageAdaptor() {} - private: +private: TanImageAdaptor(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkTestMain.h b/Utilities/ITK/Code/Common/itkTestMain.h index 5e359bf826..c883c10a97 100644 --- a/Utilities/ITK/Code/Common/itkTestMain.h +++ b/Utilities/ITK/Code/Common/itkTestMain.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTestMain.h,v $ Language: C++ - Date: $Date: 2008-11-09 18:18:51 $ - Version: $Revision: 1.32 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,6 +17,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ +#ifndef __itkTestMain_h +#define __itkTestMain_h // This file is used to create TestDriver executables // These executables are able to register a function pointer to a string name @@ -242,10 +244,10 @@ int RegressionTestImage (const char *testImageFilename, unsigned int radiusTolerance ) { // Use the factory mechanism to read the test and baseline files and convert them to double - typedef itk::Image<double,ITK_TEST_DIMENSION_MAX> ImageType; + typedef itk::Image<double,ITK_TEST_DIMENSION_MAX> ImageType; typedef itk::Image<unsigned char,ITK_TEST_DIMENSION_MAX> OutputType; - typedef itk::Image<unsigned char,2> DiffOutputType; - typedef itk::ImageFileReader<ImageType> ReaderType; + typedef itk::Image<unsigned char,2> DiffOutputType; + typedef itk::ImageFileReader<ImageType> ReaderType; // Read the baseline file ReaderType::Pointer baselineReader = ReaderType::New(); @@ -305,9 +307,9 @@ int RegressionTestImage (const char *testImageFilename, if ( (status > numberOfPixelsTolerance) && reportErrors ) { typedef itk::RescaleIntensityImageFilter<ImageType,OutputType> RescaleType; - typedef itk::ExtractImageFilter<OutputType,DiffOutputType> ExtractType; - typedef itk::ImageFileWriter<DiffOutputType> WriterType; - typedef itk::ImageRegion<ITK_TEST_DIMENSION_MAX> RegionType; + typedef itk::ExtractImageFilter<OutputType,DiffOutputType> ExtractType; + typedef itk::ImageFileWriter<DiffOutputType> WriterType; + typedef itk::ImageRegion<ITK_TEST_DIMENSION_MAX> RegionType; OutputType::SizeType size; size.Fill(0); RescaleType::Pointer rescale = RescaleType::New(); @@ -482,7 +484,7 @@ std::map<std::string,int> RegressionTestBaselines (char *baselineFilename) std::ifstream filestream(filename.str().c_str()); if (!filestream) { - break; + break; } baselines[filename.str()] = 0; filestream.close(); @@ -492,3 +494,5 @@ std::map<std::string,int> RegressionTestBaselines (char *baselineFilename) // Needed for explicit instantiation #include "itkDifferenceImageFilter.txx" + +#endif diff --git a/Utilities/ITK/Code/Common/itkTetrahedronCell.h b/Utilities/ITK/Code/Common/itkTetrahedronCell.h index dc8b01ca51..b903985150 100644 --- a/Utilities/ITK/Code/Common/itkTetrahedronCell.h +++ b/Utilities/ITK/Code/Common/itkTetrahedronCell.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTetrahedronCell.h,v $ Language: C++ - Date: $Date: 2007-05-18 14:31:13 $ - Version: $Revision: 1.54 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.55 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -103,7 +103,7 @@ public: double *, InterpolationWeightType*); - public: +public: TetrahedronCell() { for (unsigned int i = 0; i < itkGetStaticConstMacro(NumberOfPoints); i++) @@ -113,15 +113,15 @@ public: } ~TetrahedronCell() {} - protected: +protected: /** Store the number of points needed for a tetrahedron. */ PointIdentifier m_PointIds[NumberOfPoints]; - private: +private: TetrahedronCell(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented - }; +}; } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkTetrahedronCell.txx b/Utilities/ITK/Code/Common/itkTetrahedronCell.txx index 974b6aa67a..b16ee6efe9 100644 --- a/Utilities/ITK/Code/Common/itkTetrahedronCell.txx +++ b/Utilities/ITK/Code/Common/itkTetrahedronCell.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTetrahedronCell.txx,v $ Language: C++ - Date: $Date: 2008-01-07 13:33:59 $ - Version: $Revision: 1.47 $ + Date: $Date: 2009-03-03 15:09:43 $ + Version: $Revision: 1.48 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkTetrahedronCell_txx -#define _itkTetrahedronCell_txx +#ifndef __itkTetrahedronCell_txx +#define __itkTetrahedronCell_txx #include "itkTetrahedronCell.h" #include "itkTriangleCell.h" #include "vnl/algo/vnl_determinant.h" @@ -241,60 +241,59 @@ TetrahedronCell< TCellInterface > switch (dimension) { case 0: - { - VertexAutoPointer vertexPointer; - if( this->GetVertex(featureId,vertexPointer) ) - { - TransferAutoPointer(cellPointer,vertexPointer); - return true; - } - else { - cellPointer.Reset(); - return false; + VertexAutoPointer vertexPointer; + if( this->GetVertex(featureId,vertexPointer) ) + { + TransferAutoPointer(cellPointer,vertexPointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - break; - } case 1: - { - EdgeAutoPointer edgePointer; - if( this->GetEdge(featureId,edgePointer) ) - { - TransferAutoPointer(cellPointer,edgePointer); - return true; - } - else { - cellPointer.Reset(); - return false; + EdgeAutoPointer edgePointer; + if( this->GetEdge(featureId,edgePointer) ) + { + TransferAutoPointer(cellPointer,edgePointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - break; - } case 2: - { - FaceAutoPointer facePointer; - if( this->GetFace(featureId,facePointer) ) { - TransferAutoPointer(cellPointer,facePointer); - return true; + FaceAutoPointer facePointer; + if( this->GetFace(featureId,facePointer) ) + { + TransferAutoPointer(cellPointer,facePointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - else + default: { cellPointer.Reset(); return false; } - break; - } - default: - { - cellPointer.Reset(); - return false; - } } return false; } - /** * Standard CellInterface: * Set the point id list used by the cell. It is assumed that the given @@ -307,7 +306,7 @@ TetrahedronCell< TCellInterface > ::SetPointIds(PointIdConstIterator first) { PointIdConstIterator ii(first); - for(unsigned int i=0; i < Self::NumberOfPoints ; ++i) + for(unsigned int i=0; i < Self::NumberOfPoints; ++i) { m_PointIds[i] = *ii++; } @@ -478,8 +477,6 @@ TetrahedronCell< TCellInterface > return true; } - - /** * Tetrahedron-specific: * Get the face specified by the given cell feature Id. diff --git a/Utilities/ITK/Code/Common/itkTetrahedronCellTopology.cxx b/Utilities/ITK/Code/Common/itkTetrahedronCellTopology.cxx index 2fcc85e60c..ed7a98c29a 100644 --- a/Utilities/ITK/Code/Common/itkTetrahedronCellTopology.cxx +++ b/Utilities/ITK/Code/Common/itkTetrahedronCellTopology.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTetrahedronCellTopology.cxx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:27 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:09:44 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,8 +36,6 @@ const int TetrahedronCellTopology ::m_Edges[6][2] = { {0,1}, {1,2}, {2,0}, {0,3}, {1,3}, {2,3} }; - - TetrahedronCellTopology ::TetrahedronCellTopology() { @@ -48,6 +46,4 @@ TetrahedronCellTopology { } - } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkTetrahedronCellTopology.h b/Utilities/ITK/Code/Common/itkTetrahedronCellTopology.h index 4bc7e3bdf0..2969b511e9 100644 --- a/Utilities/ITK/Code/Common/itkTetrahedronCellTopology.h +++ b/Utilities/ITK/Code/Common/itkTetrahedronCellTopology.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTetrahedronCellTopology.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:27 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:09:44 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,16 +34,14 @@ namespace itk class ITKCommon_EXPORT TetrahedronCellTopology { -protected: - - /** Tetrahedron topology data. */ - static const int m_Edges[6][2]; - static const int m_Faces[4][3]; - public: TetrahedronCellTopology(); ~TetrahedronCellTopology(); +protected: + /** Tetrahedron topology data. */ + static const int m_Edges[6][2]; + static const int m_Faces[4][3]; }; } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkThinPlateR2LogRSplineKernelTransform.h b/Utilities/ITK/Code/Common/itkThinPlateR2LogRSplineKernelTransform.h index ba870a0339..1cbc6dd453 100644 --- a/Utilities/ITK/Code/Common/itkThinPlateR2LogRSplineKernelTransform.h +++ b/Utilities/ITK/Code/Common/itkThinPlateR2LogRSplineKernelTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkThinPlateR2LogRSplineKernelTransform.h,v $ Language: C++ - Date: $Date: 2007-12-20 17:10:46 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-03 15:09:44 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,10 +38,10 @@ class ITK_EXPORT ThinPlateR2LogRSplineKernelTransform : { public: /** Standard class typedefs. */ - typedef ThinPlateR2LogRSplineKernelTransform Self; + typedef ThinPlateR2LogRSplineKernelTransform Self; typedef KernelTransform< TScalarType, NDimensions> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** New macro for creation of through a Smart Pointer */ itkNewMacro( Self ); @@ -63,13 +63,13 @@ public: /** These (rather redundant) typedefs are needed because on SGI, typedefs * are not inherited */ - typedef typename Superclass::InputPointType InputPointType; - typedef typename Superclass::OutputPointType OutputPointType; - typedef typename Superclass::InputVectorType InputVectorType; - typedef typename Superclass::OutputVectorType OutputVectorType; - typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::OutputPointType OutputPointType; + typedef typename Superclass::InputVectorType InputVectorType; + typedef typename Superclass::OutputVectorType OutputVectorType; + typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType; - typedef typename Superclass::PointsIterator PointsIterator; + typedef typename Superclass::PointsIterator PointsIterator; protected: @@ -100,7 +100,7 @@ protected: virtual void ComputeDeformationContribution( const InputPointType & inputPoint, OutputPointType & result ) const; - private: +private: ThinPlateR2LogRSplineKernelTransform(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkThinPlateR2LogRSplineKernelTransform.txx b/Utilities/ITK/Code/Common/itkThinPlateR2LogRSplineKernelTransform.txx index 7da9caf960..699e4b8dec 100644 --- a/Utilities/ITK/Code/Common/itkThinPlateR2LogRSplineKernelTransform.txx +++ b/Utilities/ITK/Code/Common/itkThinPlateR2LogRSplineKernelTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkThinPlateR2LogRSplineKernelTransform.txx,v $ Language: C++ - Date: $Date: 2007-10-25 03:55:09 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-03 15:09:44 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkThinPlateR2LogRSplineKernelTransform_txx -#define _itkThinPlateR2LogRSplineKernelTransform_txx +#ifndef __itkThinPlateR2LogRSplineKernelTransform_txx +#define __itkThinPlateR2LogRSplineKernelTransform_txx #include "itkThinPlateR2LogRSplineKernelTransform.h" namespace itk diff --git a/Utilities/ITK/Code/Common/itkThinPlateSplineKernelTransform.h b/Utilities/ITK/Code/Common/itkThinPlateSplineKernelTransform.h index 5bc14b9d9f..dedcd1275b 100644 --- a/Utilities/ITK/Code/Common/itkThinPlateSplineKernelTransform.h +++ b/Utilities/ITK/Code/Common/itkThinPlateSplineKernelTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkThinPlateSplineKernelTransform.h,v $ Language: C++ - Date: $Date: 2007-12-20 17:10:46 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-03-03 15:09:45 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,10 +36,10 @@ class ITK_EXPORT ThinPlateSplineKernelTransform : { public: /** Standard class typedefs. */ - typedef ThinPlateSplineKernelTransform Self; - typedef KernelTransform< TScalarType, NDimensions> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef ThinPlateSplineKernelTransform Self; + typedef KernelTransform< TScalarType, NDimensions> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** New macro for creation of through a Smart Pointer */ itkNewMacro( Self ); @@ -61,13 +61,13 @@ public: /** These (rather redundant) typedefs are needed because on SGI, typedefs * are not inherited */ - typedef typename Superclass::InputPointType InputPointType; - typedef typename Superclass::OutputPointType OutputPointType; - typedef typename Superclass::InputVectorType InputVectorType; - typedef typename Superclass::OutputVectorType OutputVectorType; - typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::OutputPointType OutputPointType; + typedef typename Superclass::InputVectorType InputVectorType; + typedef typename Superclass::OutputVectorType OutputVectorType; + typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType; - typedef typename Superclass::PointsIterator PointsIterator; + typedef typename Superclass::PointsIterator PointsIterator; protected: @@ -98,7 +98,7 @@ protected: virtual void ComputeDeformationContribution( const InputPointType & inputPoint, OutputPointType & result ) const; - private: +private: ThinPlateSplineKernelTransform(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkThinPlateSplineKernelTransform.txx b/Utilities/ITK/Code/Common/itkThinPlateSplineKernelTransform.txx index 6e99c06145..923b8587ed 100644 --- a/Utilities/ITK/Code/Common/itkThinPlateSplineKernelTransform.txx +++ b/Utilities/ITK/Code/Common/itkThinPlateSplineKernelTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkThinPlateSplineKernelTransform.txx,v $ Language: C++ - Date: $Date: 2007-10-25 03:55:09 $ - Version: $Revision: 1.20 $ + Date: $Date: 2009-03-03 15:09:49 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkThinPlateSplineKernelTransform_txx -#define _itkThinPlateSplineKernelTransform_txx +#ifndef __itkThinPlateSplineKernelTransform_txx +#define __itkThinPlateSplineKernelTransform_txx #include "itkThinPlateSplineKernelTransform.h" namespace itk @@ -50,8 +50,6 @@ ComputeG(const InputVectorType & x, GMatrixType & gmatrix) const } } - - template <class TScalarType, unsigned int NDimensions> void ThinPlateSplineKernelTransform<TScalarType, NDimensions>:: diff --git a/Utilities/ITK/Code/Common/itkThreadLogger.cxx b/Utilities/ITK/Code/Common/itkThreadLogger.cxx index 893f926f38..8b2516016e 100644 --- a/Utilities/ITK/Code/Common/itkThreadLogger.cxx +++ b/Utilities/ITK/Code/Common/itkThreadLogger.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkThreadLogger.cxx,v $ Language: C++ - Date: $Date: 2005-11-08 22:06:08 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:09:50 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -92,9 +92,9 @@ void ThreadLogger::Flush() { this->m_Mutex.Lock(); - while( !this->m_OperationQ.empty() ) + while( !this->m_OperationQ.empty() ) { - switch( this->m_OperationQ.front() ) + switch( this->m_OperationQ.front() ) { case ThreadLogger::SET_PRIORITY_LEVEL: this->m_PriorityLevel = this->m_LevelQ.front(); @@ -120,9 +120,9 @@ void ThreadLogger::Flush() this->Logger::Flush(); break; } - this->m_OperationQ.pop(); + this->m_OperationQ.pop(); } - this->m_Output->Flush(); + this->m_Output->Flush(); this->m_Mutex.Unlock(); } @@ -142,9 +142,9 @@ ThreadLogger::~ThreadLogger() { this->m_WaitMutex.Unlock(); if( this->m_Threader ) - { + { this->m_Threader->TerminateThread(this->m_ThreadID); - } + } } @@ -153,19 +153,19 @@ ITK_THREAD_RETURN_TYPE ThreadLogger::ThreadFunction(void* pInfoStruct) struct MultiThreader::ThreadInfoStruct * pInfo = (struct MultiThreader::ThreadInfoStruct*)pInfoStruct; if( pInfo == NULL ) - { + { return ITK_THREAD_RETURN_VALUE; - } + } if( pInfo->UserData == NULL ) - { + { return ITK_THREAD_RETURN_VALUE; - } + } ThreadLogger *pLogger = (ThreadLogger*)pInfo->UserData; while(1) - { + { pLogger->m_WaitMutex.Lock(); @@ -173,44 +173,44 @@ ITK_THREAD_RETURN_TYPE ThreadLogger::ThreadFunction(void* pInfoStruct) int activeFlag = *pInfo->ActiveFlag; pInfo->ActiveFlagLock->Unlock(); if( !activeFlag ) - { + { break; - } + } pLogger->m_Mutex.Lock(); while( !pLogger->m_OperationQ.empty() ) - { - switch( pLogger->m_OperationQ.front() ) { - case ThreadLogger::SET_PRIORITY_LEVEL: - pLogger->m_PriorityLevel = pLogger->m_LevelQ.front(); - pLogger->m_LevelQ.pop(); - break; - - case ThreadLogger::SET_LEVEL_FOR_FLUSHING: - pLogger->m_LevelForFlushing = pLogger->m_LevelQ.front(); - pLogger->m_LevelQ.pop(); - break; - - case ThreadLogger::ADD_LOG_OUTPUT: - pLogger->m_Output->AddLogOutput(pLogger->m_OutputQ.front()); - pLogger->m_OutputQ.pop(); - break; - - case ThreadLogger::WRITE: - pLogger->Logger::Write(pLogger->m_LevelQ.front(), pLogger->m_MessageQ.front()); - pLogger->m_LevelQ.pop(); - pLogger->m_MessageQ.pop(); - break; - case ThreadLogger::FLUSH: - pLogger->Logger::Flush(); - break; - } + switch( pLogger->m_OperationQ.front() ) + { + case ThreadLogger::SET_PRIORITY_LEVEL: + pLogger->m_PriorityLevel = pLogger->m_LevelQ.front(); + pLogger->m_LevelQ.pop(); + break; + + case ThreadLogger::SET_LEVEL_FOR_FLUSHING: + pLogger->m_LevelForFlushing = pLogger->m_LevelQ.front(); + pLogger->m_LevelQ.pop(); + break; + + case ThreadLogger::ADD_LOG_OUTPUT: + pLogger->m_Output->AddLogOutput(pLogger->m_OutputQ.front()); + pLogger->m_OutputQ.pop(); + break; + + case ThreadLogger::WRITE: + pLogger->Logger::Write(pLogger->m_LevelQ.front(), pLogger->m_MessageQ.front()); + pLogger->m_LevelQ.pop(); + pLogger->m_MessageQ.pop(); + break; + case ThreadLogger::FLUSH: + pLogger->Logger::Flush(); + break; + } pLogger->m_OperationQ.pop(); - } + } pLogger->m_Mutex.Unlock(); pLogger->m_WaitMutex.Unlock(); - } + } return ITK_THREAD_RETURN_VALUE; } @@ -229,4 +229,3 @@ void ThreadLogger::PrintSelf(std::ostream &os, Indent indent) const } // namespace itk - diff --git a/Utilities/ITK/Code/Common/itkThreadLogger.h b/Utilities/ITK/Code/Common/itkThreadLogger.h index 1bba025807..c8c278fd00 100644 --- a/Utilities/ITK/Code/Common/itkThreadLogger.h +++ b/Utilities/ITK/Code/Common/itkThreadLogger.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkThreadLogger.h,v $ Language: C++ - Date: $Date: 2006-02-05 20:57:46 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:09:52 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,7 +37,7 @@ namespace itk * ISIS Center, Georgetown University. * * - * \ingroup OSSystemObjects LoggingObjects + * \ingroup OSSystemObjects LoggingObjects */ class ITKCommon_EXPORT ThreadLogger : public Logger @@ -45,9 +45,9 @@ class ITKCommon_EXPORT ThreadLogger : public Logger public: - typedef ThreadLogger Self; - typedef Logger Superclass; - typedef SmartPointer<Self> Pointer; + typedef ThreadLogger Self; + typedef Logger Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ @@ -61,16 +61,15 @@ public: typedef Logger::PriorityLevelType PriorityLevelType; /** Definition of types of operations for ThreadLogger. */ - typedef enum - { + typedef enum + { SET_PRIORITY_LEVEL, SET_LEVEL_FOR_FLUSHING, ADD_LOG_OUTPUT, WRITE, FLUSH - } OperationType; - - + } OperationType; + /** Set the priority level for the current logger. Only messages that have * priorities equal or greater than the one set here will be posted to the * current outputs */ diff --git a/Utilities/ITK/Code/Common/itkTimeProbesCollectorBase.cxx b/Utilities/ITK/Code/Common/itkTimeProbesCollectorBase.cxx index 700464af7f..cf830d2f84 100644 --- a/Utilities/ITK/Code/Common/itkTimeProbesCollectorBase.cxx +++ b/Utilities/ITK/Code/Common/itkTimeProbesCollectorBase.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTimeProbesCollectorBase.cxx,v $ Language: C++ - Date: $Date: 2008-10-24 18:11:22 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:09:52 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,14 +27,9 @@ TimeProbesCollectorBase { } - - TimeProbesCollectorBase ::~TimeProbesCollectorBase() { } - } // end namespace itk - - diff --git a/Utilities/ITK/Code/Common/itkTimeStamp.cxx b/Utilities/ITK/Code/Common/itkTimeStamp.cxx index 695364bc5d..4bb1832709 100644 --- a/Utilities/ITK/Code/Common/itkTimeStamp.cxx +++ b/Utilities/ITK/Code/Common/itkTimeStamp.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTimeStamp.cxx,v $ Language: C++ - Date: $Date: 2008-05-13 11:45:17 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-03-05 10:22:03 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,7 @@ #include "itkWindows.h" #elif defined(__APPLE__) - // OSAtomic.h optimizations only used in 10.5 and later +// OSAtomic.h optimizations only used in 10.5 and later #include <AvailabilityMacros.h> #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 #include <libkern/OSAtomic.h> @@ -67,12 +67,12 @@ void TimeStamp ::Modified() { -// Windows optimization + // Windows optimization #if defined(WIN32) || defined(_WIN32) static LONG itkTimeStampTime = 0; m_ModifiedTime = (unsigned long)InterlockedIncrement(&itkTimeStampTime); -// Mac optimization + // Mac optimization #elif defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) #if __LP64__ // "m_ModifiedTime" is "unsigned long", a type that changess sizes @@ -88,8 +88,11 @@ TimeStamp // gcc optimization #elif defined(__GLIBCPP__) || defined(__GLIBCXX__) - static volatile _Atomic_word itkTimeStampTime = 0; - m_ModifiedTime = (unsigned long)__exchange_and_add(&itkTimeStampTime, 1)+1; + // We start from 1 since __exchange_and_add returns the old (non-incremented) + // value. This is not really necessary but will make the absolute value of the + // timestamp more consistent across platforms. + static volatile _Atomic_word itkTimeStampTime = 1; + m_ModifiedTime = (unsigned long)__exchange_and_add(&itkTimeStampTime, 1); // General case #else diff --git a/Utilities/ITK/Code/Common/itkTimeStamp.h b/Utilities/ITK/Code/Common/itkTimeStamp.h index 886dab5442..ceda6c5d3b 100644 --- a/Utilities/ITK/Code/Common/itkTimeStamp.h +++ b/Utilities/ITK/Code/Common/itkTimeStamp.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTimeStamp.h,v $ Language: C++ - Date: $Date: 2009-02-23 16:37:20 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-03-03 15:10:09 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -80,7 +80,7 @@ public: /** Return this object's Modified time. */ unsigned long GetMTime() const - {return m_ModifiedTime;}; + {return m_ModifiedTime;} /** Support comparisons of time stamp objects directly. */ bool operator>(TimeStamp& ts) diff --git a/Utilities/ITK/Code/Common/itkTorusInteriorExteriorSpatialFunction.h b/Utilities/ITK/Code/Common/itkTorusInteriorExteriorSpatialFunction.h index 396202087a..1b88c57704 100644 --- a/Utilities/ITK/Code/Common/itkTorusInteriorExteriorSpatialFunction.h +++ b/Utilities/ITK/Code/Common/itkTorusInteriorExteriorSpatialFunction.h @@ -1,11 +1,10 @@ - /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTorusInteriorExteriorSpatialFunction.h,v $ Language: C++ - Date: $Date: 2007-01-30 23:39:53 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-25 12:24:12 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,11 +41,11 @@ class ITK_EXPORT TorusInteriorExteriorSpatialFunction: public: /** Standard class typedefs. */ - typedef TorusInteriorExteriorSpatialFunction Self; + typedef TorusInteriorExteriorSpatialFunction Self; typedef InteriorExteriorSpatialFunction<VDimension> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; - + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + /** Run time information. */ itkTypeMacro(TorusInteriorExteriorSpatialFunction,InteriorExteriorSpatialFunction); @@ -64,15 +63,15 @@ public: /** Set/Get the origin of the torus (the point from which the major * radius is measured). */ - itkGetMacro( Origin, InputType); + itkGetConstMacro( Origin, InputType); itkSetMacro( Origin, InputType); /** Set/Get the major radius of the torus. */ - itkGetMacro( MajorRadius, double); + itkGetConstMacro( MajorRadius, double); itkSetMacro( MajorRadius, double); /** Set/Get the major radius of the torus. */ - itkGetMacro( MinorRadius, double); + itkGetConstMacro( MinorRadius, double); itkSetMacro( MinorRadius, double); protected: diff --git a/Utilities/ITK/Code/Common/itkTransform.h b/Utilities/ITK/Code/Common/itkTransform.h index 0b5a3309ba..21bc4b8ed8 100644 --- a/Utilities/ITK/Code/Common/itkTransform.h +++ b/Utilities/ITK/Code/Common/itkTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransform.h,v $ Language: C++ - Date: $Date: 2008-06-29 12:58:58 $ - Version: $Revision: 1.64 $ + Date: $Date: 2009-04-10 16:47:58 $ + Version: $Revision: 1.69 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -67,9 +67,9 @@ class ITK_EXPORT Transform : public TransformBase { public: /** Standard class typedefs. */ - typedef Transform Self; - typedef TransformBase Superclass; - typedef SmartPointer< Self > Pointer; + typedef Transform Self; + typedef TransformBase Superclass; + typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** New method for creating an object using a factory. */ @@ -112,9 +112,19 @@ public: typedef vnl_vector_fixed<TScalarType, NOutputDimensions> OutputVnlVectorType; /** Standard coordinate point type for this class */ - typedef Point<CoordRepType, NInputDimensions> InputPointType; + typedef Point<CoordRepType, NInputDimensions> InputPointType; typedef Point<CoordRepType, NOutputDimensions> OutputPointType; + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost. */ +#if defined(_MSC_VER) + typedef TransformBase InverseTransformBaseType; +#else + typedef Transform< + TScalarType, NOutputDimensions, NInputDimensions > InverseTransformBaseType; +#endif + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; + /** Method to transform a point. */ virtual OutputPointType TransformPoint(const InputPointType & ) const { return OutputPointType(); } @@ -186,26 +196,26 @@ public: * * \f[ * - J=\left[ \begin{array}{cccc} - \frac{\partial x_{1}}{\partial p_{1}} & - \frac{\partial x_{1}}{\partial p_{2}} & - \cdots & \frac{\partial x_{1}}{\partial p_{m}}\\ - \frac{\partial x_{2}}{\partial p_{1}} & - \frac{\partial x_{2}}{\partial p_{2}} & - \cdots & \frac{\partial x_{2}}{\partial p_{m}}\\ - \vdots & \vdots & \ddots & \vdots \\ - \frac{\partial x_{n}}{\partial p_{1}} & - \frac{\partial x_{n}}{\partial p_{2}} & - \cdots & \frac{\partial x_{n}}{\partial p_{m}} - \end{array}\right] + J=\left[ \begin{array}{cccc} + \frac{\partial x_{1}}{\partial p_{1}} & + \frac{\partial x_{1}}{\partial p_{2}} & + \cdots & \frac{\partial x_{1}}{\partial p_{m}}\\ + \frac{\partial x_{2}}{\partial p_{1}} & + \frac{\partial x_{2}}{\partial p_{2}} & + \cdots & \frac{\partial x_{2}}{\partial p_{m}}\\ + \vdots & \vdots & \ddots & \vdots \\ + \frac{\partial x_{n}}{\partial p_{1}} & + \frac{\partial x_{n}}{\partial p_{2}} & + \cdots & \frac{\partial x_{n}}{\partial p_{m}} + \end{array}\right] * * \f] - * **/ + * */ virtual const JacobianType & GetJacobian(const InputPointType &) const { itkExceptionMacro( << "Subclass should override this method" ); // Next line is needed to avoid errors due to: - // "function must return a value". + // "function must return a value" . return this->m_Jacobian; } @@ -223,6 +233,14 @@ public: */ bool GetInverse(Self * inverseTransform) const {return false;} + /** Return an inverse of this transform. If the inverse has not been + * implemented, return NULL. The type of the inverse transform + * does not necessarily need to match the type of the forward + * transform. This allows one to return a numeric inverse transform + * instead. + */ + virtual InverseTransformBasePointer GetInverseTransform() const { return NULL; } + /** Generate a platform independant name */ virtual std::string GetTransformTypeAsString() const; @@ -238,7 +256,7 @@ public: * However, transforms for which this is true will overload and reimplement * this method accordingly. * - **/ + */ virtual bool IsLinear() const { return false; } protected: diff --git a/Utilities/ITK/Code/Common/itkTransform.txx b/Utilities/ITK/Code/Common/itkTransform.txx index 7a573cc003..1aa2f3af70 100644 --- a/Utilities/ITK/Code/Common/itkTransform.txx +++ b/Utilities/ITK/Code/Common/itkTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransform.txx,v $ Language: C++ - Date: $Date: 2007-11-20 20:08:16 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-03-03 15:10:26 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkTransform_txx -#define _itkTransform_txx +#ifndef __itkTransform_txx +#define __itkTransform_txx #include "itkTransform.h" @@ -38,8 +38,6 @@ Transform< TScalarType,NInputDimensions,NOutputDimensions> itkWarningMacro(<< "Using default transform constructor. Should specify NOutputDims and NParameters as args to constructor."); } - - /** * Constructor */ diff --git a/Utilities/ITK/Code/Common/itkTransformBase.h b/Utilities/ITK/Code/Common/itkTransformBase.h index 92d7da3a03..fbe3a01781 100644 --- a/Utilities/ITK/Code/Common/itkTransformBase.h +++ b/Utilities/ITK/Code/Common/itkTransformBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransformBase.h,v $ Language: C++ - Date: $Date: 2008-06-29 12:58:58 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-03 15:10:26 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,9 +40,9 @@ class ITK_EXPORT TransformBase : public Object { public: /** Standard class typedefs. */ - typedef TransformBase Self; - typedef Object Superclass; - typedef SmartPointer< Self > Pointer; + typedef TransformBase Self; + typedef Object Superclass; + typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** Type of the input parameters. */ diff --git a/Utilities/ITK/Code/Common/itkTransformFactory.h b/Utilities/ITK/Code/Common/itkTransformFactory.h index c4618d1d07..ebf6f4fa16 100644 --- a/Utilities/ITK/Code/Common/itkTransformFactory.h +++ b/Utilities/ITK/Code/Common/itkTransformFactory.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransformFactory.h,v $ Language: C++ - Date: $Date: 2008-07-03 13:37:55 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:10:26 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -43,7 +43,7 @@ public: t->GetTransformTypeAsString().c_str(), 1, CreateObjectFunction<T>::New() ); - }; + } }; } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkTransformFactoryBase.cxx b/Utilities/ITK/Code/Common/itkTransformFactoryBase.cxx index 6531508aab..eb88681d14 100644 --- a/Utilities/ITK/Code/Common/itkTransformFactoryBase.cxx +++ b/Utilities/ITK/Code/Common/itkTransformFactoryBase.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransformFactoryBase.cxx,v $ Language: C++ -Date: $Date: 2008-07-03 13:38:44 $ -Version: $Revision: 1.6 $ +Date: $Date: 2009-03-03 15:10:27 $ +Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,10 +44,7 @@ PURPOSE. See the above copyright notices for more information. namespace itk { - TransformFactoryBase* TransformFactoryBase::m_Factory = 0; - - - +TransformFactoryBase* TransformFactoryBase::m_Factory = 0; TransformFactoryBase::TransformFactoryBase() { @@ -135,4 +132,3 @@ TransformFactoryBase::GetDescription() const } } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkTransformFactoryBase.h b/Utilities/ITK/Code/Common/itkTransformFactoryBase.h index f76e07a0a8..798ef9f27a 100644 --- a/Utilities/ITK/Code/Common/itkTransformFactoryBase.h +++ b/Utilities/ITK/Code/Common/itkTransformFactoryBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransformFactoryBase.h,v $ Language: C++ - Date: $Date: 2005-04-01 15:52:35 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:10:27 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,9 +32,9 @@ class ITKCommon_EXPORT TransformFactoryBase : public ObjectFactoryBase { public: /** Standard class typedefs. */ - typedef TransformFactoryBase Self; - typedef ObjectFactoryBase Superclass; - typedef SmartPointer< Self > Pointer; + typedef TransformFactoryBase Self; + typedef ObjectFactoryBase Superclass; + typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** Class methods used to interface with the registered factories. */ @@ -69,9 +69,9 @@ public: const char* description, bool enableFlag, CreateObjectFunctionBase* createFunction) - { + { this->RegisterOverride ( classOverride, overrideClassName, description, enableFlag, createFunction ); - } + } protected: TransformFactoryBase(); diff --git a/Utilities/ITK/Code/Common/itkTranslationTransform.h b/Utilities/ITK/Code/Common/itkTranslationTransform.h index 2a63bd1269..a362b7e5c2 100644 --- a/Utilities/ITK/Code/Common/itkTranslationTransform.h +++ b/Utilities/ITK/Code/Common/itkTranslationTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTranslationTransform.h,v $ Language: C++ - Date: $Date: 2007-07-15 16:38:25 $ - Version: $Revision: 1.36 $ + Date: $Date: 2009-04-09 09:23:25 $ + Version: $Revision: 1.38 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,13 +23,11 @@ #include "itkExceptionObject.h" #include "itkMatrix.h" - - - namespace itk { -/** \brief Translation transformation of a vector space (e.g. space coordinates) +/** \class TranslationTransform + * \brief Translation transformation of a vector space (e.g. space coordinates) * * The same functionality could be obtained by using the Affine tranform, * but with a large difference in performace. @@ -44,12 +42,12 @@ class ITK_EXPORT TranslationTransform : { public: /** Standard class typedefs. */ - typedef TranslationTransform Self; + typedef TranslationTransform Self; typedef Transform< TScalarType, NDimensions, NDimensions > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; - /** New macro for creation of through the object factory.*/ + /** New macro for creation of through the object factory. */ itkNewMacro( Self ); /** Run-time type information (and related methods). */ @@ -83,6 +81,11 @@ public: /** Standard coordinate point type for this class. */ typedef Point<TScalarType, itkGetStaticConstMacro(SpaceDimension)> InputPointType; typedef Point<TScalarType, itkGetStaticConstMacro(SpaceDimension)> OutputPointType; + + /** Base inverse transform type. This type should not be changed to the + * concrete inverse transform type or inheritance would be lost.*/ + typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; + typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; /** This method returns the value of the offset of the * TranslationTransform. */ @@ -136,6 +139,9 @@ public: * false is returned. */ bool GetInverse(Self* inverse) const; + /** Return an inverse of this transform. */ + virtual InverseTransformBasePointer GetInverseTransform() const; + /** Compute the Jacobian Matrix of the transformation at one point */ virtual const JacobianType & GetJacobian(const InputPointType &point ) const; @@ -153,20 +159,20 @@ public: */ virtual bool IsLinear() const { return true; } - /** Set the fixed parameters and update internal transformation. + /** Set the fixed parameters and update internal transformation. * The Translation Transform does not require fixed parameters, * therefore the implementation of this method is a null operation. */ virtual void SetFixedParameters( const ParametersType & ) - { /* purposely blank */ }; + {} /** Get the Fixed Parameters. The TranslationTransform does not - * require Fixed parameters, therefore this method returns an - * parameters array of size zero. */ + * require Fixed parameters, therefore this method returns an + * parameters array of size zero. */ virtual const ParametersType& GetFixedParameters(void) const { this->m_FixedParameters.SetSize(0); - return this->m_FixedParameters; - }; + return this->m_FixedParameters; + } protected: TranslationTransform(); @@ -193,9 +199,6 @@ BackTransform(const OutputPointType &point) const { return point - m_Offset; } - - - // Back transform a vector template<class TScalarType, unsigned int NDimensions> inline @@ -206,9 +209,6 @@ BackTransform(const OutputVectorType &vect ) const return vect; } - - - // Back transform a vnl_vector template<class TScalarType, unsigned int NDimensions> inline diff --git a/Utilities/ITK/Code/Common/itkTranslationTransform.txx b/Utilities/ITK/Code/Common/itkTranslationTransform.txx index 453a2764a3..5c0a340eee 100644 --- a/Utilities/ITK/Code/Common/itkTranslationTransform.txx +++ b/Utilities/ITK/Code/Common/itkTranslationTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTranslationTransform.txx,v $ Language: C++ - Date: $Date: 2007-11-14 20:17:26 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-04-09 09:23:26 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkTranslationTransform_txx -#define _itkTranslationTransform_txx +#ifndef __itkTranslationTransform_txx +#define __itkTranslationTransform_txx #include "itkTranslationTransform.h" @@ -73,9 +73,6 @@ TranslationTransform<TScalarType, NDimensions> } } - - - // Get the parameters template <class TScalarType, unsigned int NDimensions> const typename TranslationTransform<TScalarType, NDimensions>::ParametersType & @@ -89,8 +86,6 @@ TranslationTransform<TScalarType, NDimensions> return this->m_Parameters; } - - // Print self template<class TScalarType, unsigned int NDimensions> void @@ -129,8 +124,6 @@ Translate(const OutputVectorType &offset, bool ) return; } - - // Transform a point template<class TScalarType, unsigned int NDimensions> typename TranslationTransform<TScalarType, NDimensions>::OutputPointType @@ -170,8 +163,6 @@ TransformCovariantVector(const InputCovariantVectorType &vect) const return vect; } - - // return an inverse transformation template<class TScalarType, unsigned int NDimensions> bool @@ -187,6 +178,16 @@ GetInverse( Self* inverse) const return true; } +// Return an inverse of this transform +template<class TScalarType, unsigned int NDimensions> +typename TranslationTransform<TScalarType, NDimensions>::InverseTransformBasePointer +TranslationTransform<TScalarType, NDimensions> +::GetInverseTransform() const +{ + Pointer inv = New(); + return GetInverse(inv) ? inv.GetPointer() : NULL; +} + // Compute the Jacobian in one position template<class TScalarType, unsigned int NDimensions> const typename TranslationTransform<TScalarType, NDimensions>::JacobianType & @@ -198,8 +199,6 @@ GetJacobian( const InputPointType & ) const return this->m_Jacobian; } - - // Set the parameters for an Identity transform of this class template<class TScalarType, unsigned int NDimensions> void diff --git a/Utilities/ITK/Code/Common/itkTreeChangeEvent.h b/Utilities/ITK/Code/Common/itkTreeChangeEvent.h index 98c195268a..7ca1dbb361 100644 --- a/Utilities/ITK/Code/Common/itkTreeChangeEvent.h +++ b/Utilities/ITK/Code/Common/itkTreeChangeEvent.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeChangeEvent.h,v $ Language: C++ - Date: $Date: 2008-06-20 20:28:48 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:10:32 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __TreeChangeEvent_h -#define __TreeChangeEvent_h +#ifndef __itkTreeChangeEvent_h +#define __itkTreeChangeEvent_h #include "itkMacro.h" #include <itkEventObject.h> @@ -35,7 +35,7 @@ public: /** Typedefs */ typedef TreeChangeEvent Self; - typedef ModifiedEvent Superclass; + typedef ModifiedEvent Superclass; /** Constructor */ TreeChangeEvent() @@ -78,15 +78,18 @@ public: TreeChangeEvent(const Self&s) : itk::ModifiedEvent(s) {}; -private: - void operator=(const Self&); - protected: const TreeIteratorBase<TTreeType>* m_ChangePosition; + +private: + void operator=(const Self&); + }; -/** Signals, that a node has been set to another value. Position of the changed node is provided */ +/** \class TreeNodeChangeEvent + * Signals, that a node has been set to another value. Position of the + * changed node is provided */ template <class TTreeType> class TreeNodeChangeEvent : public TreeChangeEvent<TTreeType> { @@ -130,7 +133,7 @@ class TreeAddEvent : public TreeChangeEvent<TTreeType> public: /** Typedefs */ - typedef TreeAddEvent Self; + typedef TreeAddEvent Self; typedef TreeChangeEvent<TTreeType> Superclass; /** Constructor */ @@ -152,7 +155,7 @@ public: return dynamic_cast<const Self*>(e); } - /** Make the event object */ + /** Make the event object */ virtual ::itk::EventObject* MakeObject() const { return new Self( *this->m_ChangePosition ); @@ -197,19 +200,21 @@ public: return dynamic_cast<const Self*>(e); } - /** Make the event object */ + /** Make the event object */ virtual ::itk::EventObject* MakeObject() const { return new Self( *this->m_ChangePosition ); } - TreeRemoveEvent(const Self&s) : TreeChangeEvent<TTreeType>(s) {} + TreeRemoveEvent(const Self&s) : TreeChangeEvent<TTreeType>(s) {} private: void operator=(const Self&); }; -/** Signals that a node and all its childs will shortly be removed. Position of the top-level removed node is provided */ +/** \class TreePruneEvent + * Signals that a node and all its childs will shortly be + * removed. Position of the top-level removed node is provided */ template <class TTreeType> class TreePruneEvent : public TreeRemoveEvent<TTreeType> { @@ -226,21 +231,21 @@ public: /** */ virtual const char * GetEventName() const - { + { return "TreePruneEvent"; - } + } /** */ virtual bool CheckEvent(const ::itk::EventObject* e) const - { + { return dynamic_cast<const Self*>(e); - } + } - /** */ + /** */ virtual ::itk::EventObject* MakeObject() const - { + { return new Self( *this->m_ChangePosition ); - } + } TreePruneEvent(const Self& s) : TreeRemoveEvent<TTreeType>(s) {} private: diff --git a/Utilities/ITK/Code/Common/itkTreeContainer.h b/Utilities/ITK/Code/Common/itkTreeContainer.h index f74f261884..39d0065396 100644 --- a/Utilities/ITK/Code/Common/itkTreeContainer.h +++ b/Utilities/ITK/Code/Common/itkTreeContainer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeContainer.h,v $ Language: C++ - Date: $Date: 2008-06-20 20:28:54 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:10:33 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -45,14 +45,14 @@ public: /** Standard typedefs */ typedef TreeContainerBase<TValueType> Superclass; - typedef TreeContainer<TValueType> Self; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; - typedef TValueType ValueType; - typedef TreeNode<ValueType> TreeNodeType; + typedef TreeContainer<TValueType> Self; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef TValueType ValueType; + typedef TreeNode<ValueType> TreeNodeType; /** Iterators typedef */ - typedef TreeIteratorBase<Self> IteratorType; + typedef TreeIteratorBase<Self> IteratorType; typedef PreOrderTreeIterator<Self> PreOrderIteratorType; /** Method for creation through the object factory. */ @@ -76,8 +76,8 @@ public: /** Set the root as a tree node */ virtual bool SetRoot( TreeNode<TValueType>* node); - /** Return true if the element is in the tree*/ - bool Contains( const TValueType element ) ; + /** Return true if the element is in the tree */ + bool Contains( const TValueType element ); /** Return the number of elements in the tree */ int Count() const; @@ -100,7 +100,7 @@ public: /** Get the root */ const TreeNodeType* GetRoot() const {return m_Root.GetPointer();} - /** Add a child to a given parent using values*/ + /** Add a child to a given parent using values */ bool Add(const TValueType child, const TValueType parent); /** Get node given a value */ @@ -111,8 +111,8 @@ protected: TreeContainer(); virtual ~TreeContainer(); - typename TreeNodeType::Pointer m_Root; - int m_DefaultChildrenCount; + typename TreeNodeType::Pointer m_Root; + int m_DefaultChildrenCount; void PrintSelf(std::ostream& os, Indent indent) const; diff --git a/Utilities/ITK/Code/Common/itkTreeContainer.txx b/Utilities/ITK/Code/Common/itkTreeContainer.txx index 34f9e1fbfa..9f3add17fe 100644 --- a/Utilities/ITK/Code/Common/itkTreeContainer.txx +++ b/Utilities/ITK/Code/Common/itkTreeContainer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeContainer.txx,v $ Language: C++ - Date: $Date: 2008-06-20 20:28:54 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:10:35 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkTreeContainer_txx -#define _itkTreeContainer_txx +#ifndef __itkTreeContainer_txx +#define __itkTreeContainer_txx #include "itkTreeContainer.h" @@ -95,7 +95,6 @@ TreeContainer<TValueType>::Count() const ++it; } return size; -return 0; } /** Swap the iterators */ @@ -148,7 +147,7 @@ TreeContainer<TValueType>::Contains( const TValueType element ) it.GoToBegin(); while(!it.IsAtEnd()) { - if(it.Get()== element) + if(it.Get() == element) { return true; } diff --git a/Utilities/ITK/Code/Common/itkTreeContainerBase.h b/Utilities/ITK/Code/Common/itkTreeContainerBase.h index 7c285c6297..cd1fac5ab9 100644 --- a/Utilities/ITK/Code/Common/itkTreeContainerBase.h +++ b/Utilities/ITK/Code/Common/itkTreeContainerBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeContainerBase.h,v $ Language: C++ - Date: $Date: 2008-06-20 20:28:54 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:10:35 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,9 +32,9 @@ class TreeContainerBase : public Object public: - typedef Object Superclass; - typedef TreeContainerBase Self; - typedef SmartPointer<Self> Pointer; + typedef Object Superclass; + typedef TreeContainerBase Self; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; typedef TValueType ValueType; @@ -78,9 +78,6 @@ protected: }; - - } // namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkTreeIteratorBase.h b/Utilities/ITK/Code/Common/itkTreeIteratorBase.h index 4d7e2ab76b..b81731d478 100644 --- a/Utilities/ITK/Code/Common/itkTreeIteratorBase.h +++ b/Utilities/ITK/Code/Common/itkTreeIteratorBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeIteratorBase.h,v $ Language: C++ - Date: $Date: 2008-06-20 20:28:54 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-03 15:10:36 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,7 +58,7 @@ public: virtual bool Add(TTreeType& subTree); /** Get a value */ - virtual const ValueType& Get() const ; + virtual const ValueType& Get() const; /** Get the subtree */ virtual TTreeType* GetSubTree() const; @@ -132,13 +132,13 @@ public: void GoToBegin() { m_Position = m_Begin; - }; + } /** Move an iterator to the end of the tree. */ void GoToEnd() { m_Position = m_End; - }; + } /** Is the iterator at the beginning of the tree? */ bool IsAtBegin(void) const @@ -146,7 +146,8 @@ public: return (m_Position == m_Begin); } - /** Is the iterator at the end of the tree?. The iterator is at the end if it points to NULL*/ + /** Is the iterator at the end of the tree?. The iterator is at the + * end if it points to NULL */ bool IsAtEnd(void) const { return (m_Position == m_End); @@ -203,8 +204,8 @@ protected: mutable TreeNodeType* m_Position; // Current position of the iterator mutable TreeNodeType* m_Begin; mutable TreeNodeType* m_End; - const TreeNodeType* m_Root; - TTreeType* m_Tree; + const TreeNodeType* m_Root; + TTreeType* m_Tree; virtual bool HasNext() const = 0; virtual const ValueType& Next() = 0; diff --git a/Utilities/ITK/Code/Common/itkTreeIteratorBase.txx b/Utilities/ITK/Code/Common/itkTreeIteratorBase.txx index 8dcf89b3f4..6491b75087 100644 --- a/Utilities/ITK/Code/Common/itkTreeIteratorBase.txx +++ b/Utilities/ITK/Code/Common/itkTreeIteratorBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeIteratorBase.txx,v $ Language: C++ - Date: $Date: 2008-06-22 19:18:56 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-03-03 15:10:37 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkTreeContainerBase_txx -#define __itkTreeContainerBase_txx +#ifndef __itkTreeIteratorBase_txx +#define __itkTreeIteratorBase_txx #include <itkTreeIteratorBase.h> #include "itkTreeChangeEvent.h" @@ -89,18 +89,18 @@ TreeIteratorBase<TTreeType>::Add(ValueType element) bool returnValue = false; if ( m_Tree ) { - returnValue = const_cast<TTreeType*>(m_Tree)->SetRoot( element ); + returnValue = const_cast<TTreeType*>(m_Tree)->SetRoot( element ); } - // signal AddEvent for self - m_Root = dynamic_cast<const TreeNodeType*>(const_cast<TTreeType*>(m_Tree)->GetRoot()); - m_Position = const_cast<TreeNodeType*>(m_Root); - m_Tree->Modified(); - m_Tree->InvokeEvent( TreeAddEvent<TTreeType>(*this) ); - return returnValue; + // signal AddEvent for self + m_Root = dynamic_cast<const TreeNodeType*>(const_cast<TTreeType*>(m_Tree)->GetRoot()); + m_Position = const_cast<TreeNodeType*>(m_Root); + m_Tree->Modified(); + m_Tree->InvokeEvent( TreeAddEvent<TTreeType>(*this) ); + return returnValue; } - else if ( m_Position == NULL ) + else if ( m_Position == NULL ) { - return false; + return false; } typename TreeNodeType::Pointer node = TreeNodeType::New(); @@ -126,7 +126,7 @@ TreeIteratorBase<TTreeType>::Add( int itkNotUsed(childPosition), ValueType eleme { typename TreeNodeType::Pointer node = TreeNodeType::New(); node->Set(element); - m_Position->AddChild(node) ; + m_Position->AddChild(node); m_Tree->Modified(); // signal AddEvent @@ -215,10 +215,10 @@ TreeIteratorBase<TTreeType>::HasChild( int number ) const { return false; } - if ( m_Position->GetChild( number ) != NULL ) - { - return true; - } + if ( m_Position->GetChild( number ) != NULL ) + { + return true; + } return false; } @@ -247,15 +247,15 @@ TreeIteratorBase<TTreeType>::RemoveChild( int number ) if( child != NULL ) { - // signal PruneEvent (node plus all children are removed) - TreeIteratorBase<TTreeType>* childIterator = Clone(); - childIterator->m_Position = child; - m_Tree->InvokeEvent( TreePruneEvent<TTreeType>(*childIterator) ); // signal "child has been added deleted" - delete childIterator; + // signal PruneEvent (node plus all children are removed) + TreeIteratorBase<TTreeType>* childIterator = Clone(); + childIterator->m_Position = child; + m_Tree->InvokeEvent( TreePruneEvent<TTreeType>(*childIterator) ); // signal "child has been added deleted" + delete childIterator; - const_cast<TreeNodeType*>(m_Position)->Remove( child ); // and really remove child (and subitems) - m_Tree->Modified(); - return true; + const_cast<TreeNodeType*>(m_Position)->Remove( child ); // and really remove child (and subitems) + m_Tree->Modified(); + return true; } return false; } @@ -416,7 +416,7 @@ int TreeIteratorBase<TTreeType>::Count() return 0; } while (this->Next() ) - { + { size++; } return size; @@ -507,4 +507,3 @@ TreeIteratorBase<TTreeType>::GetTree() const } // namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkTreeIteratorClone.h b/Utilities/ITK/Code/Common/itkTreeIteratorClone.h index c5d3068788..8000b4a2ab 100644 --- a/Utilities/ITK/Code/Common/itkTreeIteratorClone.h +++ b/Utilities/ITK/Code/Common/itkTreeIteratorClone.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeIteratorClone.h,v $ Language: C++ - Date: $Date: 2008-06-20 20:28:54 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:10:40 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,7 @@ public: /** Typedefs */ typedef TreeIteratorClone<TObjectType> Self; - typedef TObjectType ObjectType; + typedef TObjectType ObjectType; /** Constructor */ TreeIteratorClone () @@ -56,14 +56,14 @@ public: { m_Pointer=p->Clone(); } - } + } /** Constructor to reference p */ TreeIteratorClone (const ObjectType &p) { m_Pointer = 0; m_Pointer=const_cast<ObjectType*>(&p)->Clone(); - } + } /** Destructor */ ~TreeIteratorClone () @@ -78,17 +78,17 @@ public: /** Test if the pointer has been initialized */ bool IsNotNull() const - { return m_Pointer != 0; } + { return m_Pointer != 0; } bool IsNull() const - { return m_Pointer == 0; } + { return m_Pointer == 0; } /** Template comparison operators. */ - template <typename R> - bool operator == ( R r ) const + template <typename TR> + bool operator == ( TR r ) const { return (m_Pointer == (ObjectType*)(r) ); } - template <typename R> - bool operator != ( R r ) const + template <typename TR> + bool operator != ( TR r ) const { return (m_Pointer != (ObjectType*)(r) ); } /** Access function to pointer. */ @@ -117,7 +117,7 @@ public: /** Overload operator assignment. */ TreeIteratorClone &operator = (const ObjectType *r) - { + { if (m_Pointer != r) { delete m_Pointer; @@ -132,7 +132,9 @@ public: operator++() { if(m_Pointer) + { ++(*m_Pointer); + } return *this; } diff --git a/Utilities/ITK/Code/Common/itkTreeNode.h b/Utilities/ITK/Code/Common/itkTreeNode.h index ac1f70642b..76243b9bad 100644 --- a/Utilities/ITK/Code/Common/itkTreeNode.h +++ b/Utilities/ITK/Code/Common/itkTreeNode.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeNode.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-03 15:10:44 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -118,8 +118,8 @@ protected: TreeNode(); virtual ~TreeNode(); - TValueType m_Data; - Self* m_Parent; + TValueType m_Data; + Self* m_Parent; ChildrenListType m_Children; private: TreeNode(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkTreeNode.txx b/Utilities/ITK/Code/Common/itkTreeNode.txx index 0824ff9c58..49fcef6c02 100644 --- a/Utilities/ITK/Code/Common/itkTreeNode.txx +++ b/Utilities/ITK/Code/Common/itkTreeNode.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeNode.txx,v $ Language: C++ - Date: $Date: 2008-07-18 17:20:25 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-05 10:56:46 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,11 +14,12 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkTreeNode_txx -#define _itkTreeNode_txx +#ifndef __itkTreeNode_txx +#define __itkTreeNode_txx #include "itkTreeNode.h" #include <cstring> +#include <string.h> namespace itk { @@ -38,10 +39,10 @@ TreeNode<TValueType>::~TreeNode() m_Parent->Remove(this); } - for ( size_t i=m_Children.size() ; i > 0; i-- ) - { - m_Children[i-1]->SetParent(NULL); - } + for ( size_t i=m_Children.size(); i > 0; i-- ) + { + m_Children[i-1]->SetParent(NULL); + } m_Children.clear(); m_Parent = NULL; m_Data = 0; @@ -192,7 +193,7 @@ int TreeNode<TValueType>::ChildPosition( TValueType element ) const template <class TValueType> void TreeNode<TValueType>::AddChild( TreeNode<TValueType> *node ) { - Pointer nodeKeepAlive = node; + Pointer nodeKeepAlive = node; node->SetParent(this); m_Children.push_back(node); } diff --git a/Utilities/ITK/Code/Common/itkTriangleCell.h b/Utilities/ITK/Code/Common/itkTriangleCell.h index ef7a413a6e..e20edac549 100644 --- a/Utilities/ITK/Code/Common/itkTriangleCell.h +++ b/Utilities/ITK/Code/Common/itkTriangleCell.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTriangleCell.h,v $ Language: C++ - Date: $Date: 2008-07-19 14:52:53 $ - Version: $Revision: 1.61 $ + Date: $Date: 2009-03-03 15:11:01 $ + Version: $Revision: 1.62 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -110,17 +110,17 @@ public: PointType ComputeCenterOfGravity( PointsContainer* ); PointType ComputeCircumCenter( PointsContainer* ); - public: +public: TriangleCell() : m_PointIds( NumberOfPoints, NumericTraits<PointIdentifier>::max() ) {} ~TriangleCell() {} - protected: +protected: /** Store the number of points needed for a triangle. */ std::vector< PointIdentifier > m_PointIds; - private: +private: TriangleCell(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkTriangleCell.txx b/Utilities/ITK/Code/Common/itkTriangleCell.txx index 3fd6771835..ff9d34eb8d 100644 --- a/Utilities/ITK/Code/Common/itkTriangleCell.txx +++ b/Utilities/ITK/Code/Common/itkTriangleCell.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTriangleCell.txx,v $ Language: C++ - Date: $Date: 2008-07-19 17:47:52 $ - Version: $Revision: 1.54 $ + Date: $Date: 2009-03-03 15:11:04 $ + Version: $Revision: 1.55 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkTriangleCell_txx -#define _itkTriangleCell_txx +#ifndef __itkTriangleCell_txx +#define __itkTriangleCell_txx #include "itkTriangleCell.h" #include "vnl/algo/vnl_determinant.h" @@ -94,41 +94,41 @@ TriangleCell< TCellInterface > switch (dimension) { case 0: - { - VertexAutoPointer vertexPointer; - if( this->GetVertex(featureId,vertexPointer) ) - { - TransferAutoPointer(cellPointer,vertexPointer); - return true; - } - else { - cellPointer.Reset(); - return false; + VertexAutoPointer vertexPointer; + if( this->GetVertex(featureId,vertexPointer) ) + { + TransferAutoPointer(cellPointer,vertexPointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - break; - } case 1: - { - EdgeAutoPointer edgePointer; - if( this->GetEdge(featureId,edgePointer) ) { - TransferAutoPointer(cellPointer,edgePointer); - return true; + EdgeAutoPointer edgePointer; + if( this->GetEdge(featureId,edgePointer) ) + { + TransferAutoPointer(cellPointer,edgePointer); + return true; + } + else + { + cellPointer.Reset(); + return false; + } + break; } - else + + default: { cellPointer.Reset(); return false; } - break; - } - - default: - { - cellPointer.Reset(); - return false; - } } return false; } @@ -146,7 +146,7 @@ TriangleCell< TCellInterface > ::SetPointIds(PointIdConstIterator first) { PointIdConstIterator ii(first); - for(unsigned int i=0; i < NumberOfPoints ; ++i, ++ii) + for(unsigned int i=0; i < NumberOfPoints; ++i, ++ii) { m_PointIds[i] = *ii; } @@ -302,8 +302,6 @@ TriangleCell< TCellInterface > return true; } - - /** Compute distance to finite line. Returns parametric coordinate t * and point location on line. */ template <typename TCellInterface> @@ -375,17 +373,8 @@ TriangleCell< TCellInterface > else { closestPoint = p1 + v21 * t; -// for(i=0;i<PointDimension;i++) -// { -// closest[i] = p1[i] + t*p21[i]; -// } } -// for(i=0;i<PointDimension;i++) -// { -// closestPoint[i] = closest[i]; -// } - return static_cast< double >( closestPoint.SquaredEuclideanDistanceTo(x) ); } @@ -415,7 +404,7 @@ TriangleCell< TCellInterface >::ComputeBarycenter( CoordRepType sum_weights(0.); unsigned int i(0); - for( ; i < 3; i++ ) + for(; i < 3; i++ ) { sum_weights += iWeights[i]; p[i] = iPoints->GetElement( m_PointIds[i] ); @@ -608,7 +597,7 @@ TriangleCell< TCellInterface > } return true; - } + } else { if (closestPoint) @@ -723,7 +712,7 @@ TriangleCell< TCellInterface > } //Just fall through to default return false; } - return false; //Default case that should never be reached. + return false; //Default case that should never be reached. } diff --git a/Utilities/ITK/Code/Common/itkTriangleCellTopology.cxx b/Utilities/ITK/Code/Common/itkTriangleCellTopology.cxx index 5e553b9698..fa267d9ebb 100644 --- a/Utilities/ITK/Code/Common/itkTriangleCellTopology.cxx +++ b/Utilities/ITK/Code/Common/itkTriangleCellTopology.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTriangleCellTopology.cxx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:28 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-03 15:11:07 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,6 +38,4 @@ TriangleCellTopology { } - } // end namespace itk - diff --git a/Utilities/ITK/Code/Common/itkTriangleCellTopology.h b/Utilities/ITK/Code/Common/itkTriangleCellTopology.h index b7833917e8..ccc1c7e69a 100644 --- a/Utilities/ITK/Code/Common/itkTriangleCellTopology.h +++ b/Utilities/ITK/Code/Common/itkTriangleCellTopology.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTriangleCellTopology.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:28 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:11:09 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -33,16 +33,15 @@ namespace itk class ITKCommon_EXPORT TriangleCellTopology { -protected: - - /** Triangle topology data. */ - static const int m_Edges[3][2]; - - public: TriangleCellTopology(); ~TriangleCellTopology(); +protected: + + /** Triangle topology data. */ + static const int m_Edges[3][2]; + }; } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkUnaryCorrespondenceMatrix.h b/Utilities/ITK/Code/Common/itkUnaryCorrespondenceMatrix.h index 3ce9f92450..a87fe7d88e 100644 --- a/Utilities/ITK/Code/Common/itkUnaryCorrespondenceMatrix.h +++ b/Utilities/ITK/Code/Common/itkUnaryCorrespondenceMatrix.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkUnaryCorrespondenceMatrix.h,v $ Language: C++ - Date: $Date: 2004-03-03 19:12:29 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:11:16 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,7 @@ namespace itk * * \ingroup * -*/ + */ template<typename TItemType> class UnaryCorrespondenceMatrix : public DataObject, public vnl_matrix<TItemType> { @@ -38,8 +38,8 @@ public: /** Standard class typedefs. */ typedef UnaryCorrespondenceMatrix Self; - typedef DataObject Superclass; - typedef SmartPointer<Self> Pointer; + typedef DataObject Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ diff --git a/Utilities/ITK/Code/Common/itkValarrayImageContainer.h b/Utilities/ITK/Code/Common/itkValarrayImageContainer.h index 935ad669fd..0d478edec7 100644 --- a/Utilities/ITK/Code/Common/itkValarrayImageContainer.h +++ b/Utilities/ITK/Code/Common/itkValarrayImageContainer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkValarrayImageContainer.h,v $ Language: C++ - Date: $Date: 2007-05-16 17:29:17 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-03-03 15:11:20 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -54,9 +54,9 @@ class ValarrayImageContainer: public: /** Standard class typedefs. */ typedef ValarrayImageContainer Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Save the template parameters. */ typedef TElementIdentifier ElementIdentifier; @@ -111,35 +111,35 @@ public: /** Get the number of elements currently stored in the container. */ unsigned long Size(void) const - { return static_cast<unsigned long>(this->ValarrayType::size()); }; + { return static_cast<unsigned long>(this->ValarrayType::size()); } /** Tell the container to allocate enough memory to allow at least * as many elements as the size given to be stored. This is NOT * guaranteed to actually allocate any memory, but is useful if the * implementation of the container allocates contiguous storage. */ void Reserve(ElementIdentifier num) - { this->ValarrayType::resize(num); }; + { this->ValarrayType::resize(num); } /** Tell the container to try to minimize its memory usage for storage of * the current number of elements. This is NOT guaranteed to decrease * memory usage. */ void Squeeze(void) - { this->ValarrayType::resize( this->ValarrayType::size() ); }; + { this->ValarrayType::resize( this->ValarrayType::size() ); } /** Tell the container to release any of its allocated memory. */ void Initialize(void) - { this->ValarrayType::resize( 0 ); }; + { this->ValarrayType::resize( 0 ); } /** Tell the container to release any of its allocated memory. */ void Fill(const TElement & value) - { this->ValarrayType::operator=( value ); }; + { this->ValarrayType::operator=( value ); } public: /** PrintSelf routine. Normally this is a protected internal method. It is * made public here so that Image can call this method. Users should not * call this method but should call Print() instead. */ virtual void PrintSelf(std::ostream& os, Indent indent) const - { + { Object::PrintSelf(os, indent); // Print out the pointer to bulk data memory. We use const_cast<> to // cast away the constness so we can call GetBufferPointer() @@ -148,7 +148,7 @@ public: << std::endl; os << indent << "Size: " << this->Size() << std::endl; - }; + } }; diff --git a/Utilities/ITK/Code/Common/itkVariableLengthVector.h b/Utilities/ITK/Code/Common/itkVariableLengthVector.h index ad36b41b41..d8c8a0ffe4 100644 --- a/Utilities/ITK/Code/Common/itkVariableLengthVector.h +++ b/Utilities/ITK/Code/Common/itkVariableLengthVector.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVariableLengthVector.h,v $ Language: C++ - Date: $Date: 2008-07-17 11:50:28 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-05-25 08:34:20 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,7 +27,7 @@ namespace itk * length can be defined at run-time. * * This class is templated over the data type. This data-type is meant - * to a scalar, such as float, double etc... + * to be a scalar, such as float, double etc... * * \note * ITK itself provides several classes that can serve as \c Arrays. @@ -70,10 +70,10 @@ class VariableLengthVector public: /** The element type stored at each location in the Array. */ - typedef TValueType ValueType; - typedef TValueType ComponentType; + typedef TValueType ValueType; + typedef TValueType ComponentType; typedef typename NumericTraits< ValueType >::RealType RealValueType; - typedef VariableLengthVector Self; + typedef VariableLengthVector Self; /** Typedef used to indicate the number of elements in the vector */ typedef unsigned int ElementIdentifier; @@ -112,7 +112,7 @@ public: * VariableLengthVector< float > vF( vI ); * or for instance vF = static_cast< VariableLengthVector< float > >( vI ); * \endcode - **/ + */ template< class T > VariableLengthVector(const VariableLengthVector< T > & v) { @@ -132,7 +132,7 @@ public: /** Set the all the elements of the array to the specified value */ void Fill (TValueType const& v); - /** Assignment operator **/ + /** Assignment operator */ template< class T > const VariableLengthVector< TValueType > & operator= (const VariableLengthVector< T > & v) @@ -150,14 +150,14 @@ public: return *this; } - /** Assignment operator **/ + /** Assignment operator */ const Self & operator=(const Self & v); /** Return the number of elements in the Array */ inline unsigned int Size (void ) const - { return m_NumElements; } + { return m_NumElements; } inline unsigned int GetNumberOfElements(void) const - { return m_NumElements; } + { return m_NumElements; } /** Return reference to the element at specified index. No range checking. */ TValueType & operator[](unsigned int i) { return this->m_Data[i]; } @@ -184,7 +184,7 @@ public: * The default is \c true. */ void SetSize(unsigned int sz, bool destroyExistingData=true); inline unsigned int GetSize(void) const - { return m_NumElements; } + { return m_NumElements; } /** Set the pointer from which the data is imported. * If "LetArrayManageMemory" is false, then the application retains @@ -234,7 +234,7 @@ public: // { // itkGenericExceptionMacro( << "Cannot add VariableLengthVector of length " // << m_NumElements " and " << v.GetSize() ); - // } + // } const ElementIdentifier length = v.Size(); Self result( length ); for( ElementIdentifier i=0; i< length; i++ ) @@ -250,7 +250,7 @@ public: // { // itkGenericExceptionMacro( << "Cannot add VariableLengthVector of length " // << m_NumElements " and " << v.GetSize() ); - // } + // } const ElementIdentifier length = v.Size(); Self result( length ); for( ElementIdentifier i=0; i< length; i++ ) @@ -315,18 +315,18 @@ public: } inline Self operator--(int) // postfix operator v--; { - Self tmp(*this); - --tmp; - return tmp; + Self tmp(*this); + --tmp; + return tmp; } inline Self operator++(int) // postfix operator v++; { - Self tmp(*this); - ++tmp; - return tmp; + Self tmp(*this); + ++tmp; + return tmp; } - template< class T > inline Self& operator-= - ( const VariableLengthVector< T > &v ) + template< class T > inline Self& operator-= + ( const VariableLengthVector< T > &v ) { for( ElementIdentifier i=0; i< m_NumElements; i++ ) { @@ -338,7 +338,7 @@ public: { for( ElementIdentifier i=0; i< m_NumElements; i++ ) { - m_Data[i] -= s ; + m_Data[i] -= s; } return *this; } @@ -373,7 +373,7 @@ public: { m_Data[i] = static_cast< ValueType >( static_cast< RealValueType >(m_Data[i]) / - static_cast< RealValueType >( s )); + static_cast< RealValueType >( s )); } return *this; } @@ -389,9 +389,8 @@ public: private: - bool m_LetArrayManageMemory; // if true, the array is responsible for memory - // of data - TValueType *m_Data; // Array to hold data + bool m_LetArrayManageMemory; // if true, the array is responsible for memory of data + TValueType * m_Data; // Array to hold data ElementIdentifier m_NumElements; }; diff --git a/Utilities/ITK/Code/Common/itkVariableLengthVector.txx b/Utilities/ITK/Code/Common/itkVariableLengthVector.txx index 83637ec502..e2f5b803b8 100644 --- a/Utilities/ITK/Code/Common/itkVariableLengthVector.txx +++ b/Utilities/ITK/Code/Common/itkVariableLengthVector.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVariableLengthVector.txx,v $ Language: C++ - Date: $Date: 2008-05-26 02:36:52 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-05 18:45:46 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,13 +14,15 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkVariableLengthVector_txx -#define _itkVariableLengthVector_txx +#ifndef __itkVariableLengthVector_txx +#define __itkVariableLengthVector_txx #include "itkVariableLengthVector.h" #include "itkNumericTraitsVariableLengthVectorPixel.h" #include "vnl/vnl_math.h" #include <cstring> +#include <stdlib.h> +#include <string.h> namespace itk { @@ -28,11 +30,10 @@ namespace itk /** Default constructor */ template < typename TValueType > VariableLengthVector<TValueType > -::VariableLengthVector() : - m_LetArrayManageMemory( true ), - m_Data( 0 ), - m_NumElements( 0 ) {} - +::VariableLengthVector() : m_LetArrayManageMemory( true ), + m_Data( 0 ), + m_NumElements( 0 ) +{} /** Constructor with size */ template < typename TValueType > @@ -50,7 +51,8 @@ VariableLengthVector<TValueType > ::VariableLengthVector( ValueType *datain, unsigned int sz, bool LetArrayManageMemory) : m_LetArrayManageMemory( LetArrayManageMemory ), m_Data( datain ), - m_NumElements( sz ) {} + m_NumElements( sz ) +{} /** Constructor with user specified data */ template < typename TValueType > @@ -78,7 +80,7 @@ VariableLengthVector<TValueType > } -/** Destructor*/ +/** Destructor */ template < typename TValueType > VariableLengthVector<TValueType > ::~VariableLengthVector() @@ -148,14 +150,14 @@ TValueType * VariableLengthVector< TValueType > * the responsibility of freeing the memory for this data. If * "LetArrayManageMemory" is true, then this class will free the * memory when this object is destroyed. Note that you need to explicitly - * set the number of elements.*/ + * set the number of elements. */ template < typename TValueType > void VariableLengthVector<TValueType > ::SetData(TValueType* datain,bool LetArrayManageMemory) { // Free any existing data if we manage its memory - if(m_LetArrayManageMemory && m_Data) + if(m_LetArrayManageMemory && m_Data) { delete [] m_Data; } @@ -234,7 +236,7 @@ void VariableLengthVector<TValueType > } } -/** Assignment operator **/ +/** Assignment operator */ template < typename TValueType > const VariableLengthVector< TValueType >& VariableLengthVector<TValueType > ::operator=(const Self & v) @@ -306,7 +308,7 @@ typename VariableLengthVector< TValueType >::RealValueType VariableLengthVector<TValueType > ::GetNorm( void ) const { - return (RealValueType)( vcl_sqrt(double(this->GetSquaredNorm()) )); + return (RealValueType)( vcl_sqrt(double(this->GetSquaredNorm()) )); } /** diff --git a/Utilities/ITK/Code/Common/itkVarianceImageFunction.h b/Utilities/ITK/Code/Common/itkVarianceImageFunction.h index f5ade1ec9d..daf07416f1 100644 --- a/Utilities/ITK/Code/Common/itkVarianceImageFunction.h +++ b/Utilities/ITK/Code/Common/itkVarianceImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVarianceImageFunction.h,v $ Language: C++ - Date: $Date: 2007-01-30 20:56:09 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-03 15:11:25 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -45,10 +45,10 @@ class ITK_EXPORT VarianceImageFunction : { public: /** Standard class typedefs. */ - typedef VarianceImageFunction Self; + typedef VarianceImageFunction Self; typedef ImageFunction<TInputImage, ITK_TYPENAME NumericTraits<typename TInputImage::PixelType>::RealType, - TCoordRep > Superclass; - typedef SmartPointer<Self> Pointer; + TCoordRep > Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ @@ -86,16 +86,16 @@ public: /** Evaluate the function at non-integer positions */ virtual RealType Evaluate( const PointType& point ) const { - IndexType index; - this->ConvertPointToNearestIndex( point, index ); - return this->EvaluateAtIndex( index ); + IndexType index; + this->ConvertPointToNearestIndex( point, index ); + return this->EvaluateAtIndex( index ); } virtual RealType EvaluateAtContinuousIndex( const ContinuousIndexType& cindex ) const { - IndexType index; - this->ConvertContinuousIndexToNearestIndex( cindex, index ); - return this->EvaluateAtIndex( index ) ; + IndexType index; + this->ConvertContinuousIndexToNearestIndex( cindex, index ); + return this->EvaluateAtIndex( index ); } /** Get/Set the radius of the neighborhood over which the @@ -135,4 +135,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Common/itkVarianceImageFunction.txx b/Utilities/ITK/Code/Common/itkVarianceImageFunction.txx index 1de8b5b635..f908f09616 100644 --- a/Utilities/ITK/Code/Common/itkVarianceImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkVarianceImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVarianceImageFunction.txx,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-03-03 15:11:31 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -90,8 +90,8 @@ VarianceImageFunction<TInputImage,TCoordRep> for (unsigned int i = 0; i < size; ++i) { const RealType value = static_cast<RealType>( it.GetPixel(i) ); - sum += value; - sumOfSquares += value * value; + sum += value; + sumOfSquares += value * value; } const double num = static_cast<double>( size ); diff --git a/Utilities/ITK/Code/Common/itkVector.cxx b/Utilities/ITK/Code/Common/itkVector.cxx index dbbc22aa6c..10342affe3 100644 --- a/Utilities/ITK/Code/Common/itkVector.cxx +++ b/Utilities/ITK/Code/Common/itkVector.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVector.cxx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:28 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:11:34 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -62,10 +62,4 @@ ITKCommon_EXPORT CrossProduct( const Vector<int,3> & a, const Vector<int,3> & b return c; } - - - - } // end namespace itk - - diff --git a/Utilities/ITK/Code/Common/itkVector.h b/Utilities/ITK/Code/Common/itkVector.h index 1f7ac30e90..0564c0b0f2 100644 --- a/Utilities/ITK/Code/Common/itkVector.h +++ b/Utilities/ITK/Code/Common/itkVector.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVector.h,v $ Language: C++ - Date: $Date: 2008-05-12 21:11:21 $ - Version: $Revision: 1.82 $ + Date: $Date: 2009-03-03 15:11:37 $ + Version: $Revision: 1.83 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,12 +59,12 @@ class Vector : public FixedArray<T,NVectorDimension> { public: /** Standard class typedefs. */ - typedef Vector Self; + typedef Vector Self; typedef FixedArray<T,NVectorDimension> Superclass; /** ValueType can be used to declare a variable that is the same type * as a data element held in an Vector. */ - typedef T ValueType; + typedef T ValueType; typedef typename NumericTraits< ValueType >::RealType RealValueType; /** Dimension of the vector space. */ @@ -216,13 +216,12 @@ public: * Casting is done with C-Like rules */ template < typename TCoordRepB > void CastFrom( const Vector<TCoordRepB,NVectorDimension> & pa ) - { + { for(unsigned int i=0; i<NVectorDimension; i++ ) { (*this)[i] = static_cast<T>( pa[i] ); } - } - + } }; /** Premultiply Operator for product of a vector and a scalar. diff --git a/Utilities/ITK/Code/Common/itkVector.txx b/Utilities/ITK/Code/Common/itkVector.txx index 608d7e78f9..006c41f6d0 100644 --- a/Utilities/ITK/Code/Common/itkVector.txx +++ b/Utilities/ITK/Code/Common/itkVector.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVector.txx,v $ Language: C++ - Date: $Date: 2007-04-14 11:54:34 $ - Version: $Revision: 1.51 $ + Date: $Date: 2009-03-03 15:11:38 $ + Version: $Revision: 1.52 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkVector_txx -#define _itkVector_txx +#ifndef __itkVector_txx +#define __itkVector_txx #include "itkVector.h" #include "itkNumericTraits.h" @@ -100,8 +100,6 @@ Vector<T, TVectorDimension> return result; } - - /** * Returns a temporary copy of a vector */ @@ -118,8 +116,6 @@ Vector<T, TVectorDimension> return result; } - - /** * Returns a temporary copy of a vector */ @@ -154,8 +150,6 @@ Vector<T, TVectorDimension> return sum; } - - /** * Returns vector's Euclidean Norm */ @@ -325,10 +319,6 @@ Vector<T, TVectorDimension> return value; } - - - } // end namespace itk - #endif diff --git a/Utilities/ITK/Code/Common/itkVectorContainer.h b/Utilities/ITK/Code/Common/itkVectorContainer.h index cff8d55ff3..c3127efa00 100644 --- a/Utilities/ITK/Code/Common/itkVectorContainer.h +++ b/Utilities/ITK/Code/Common/itkVectorContainer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorContainer.h,v $ Language: C++ - Date: $Date: 2007-12-23 17:59:29 $ - Version: $Revision: 1.58 $ + Date: $Date: 2009-03-03 15:11:39 $ + Version: $Revision: 1.59 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,9 +51,9 @@ class ITK_EXPORT VectorContainer: { public: /** Standard class typedefs. */ - typedef VectorContainer Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; + typedef VectorContainer Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Save the template parameters. */ @@ -62,7 +62,7 @@ public: private: /** Quick access to the STL vector type that was inherited. */ - typedef std::vector<Element> VectorType; + typedef std::vector<Element> VectorType; typedef typename VectorType::size_type size_type; typedef typename VectorType::iterator VectorIterator; typedef typename VectorType::const_iterator VectorConstIterator; @@ -79,14 +79,14 @@ protected: Object(), VectorType(n, x) {} VectorContainer(const Self& r): Object(), VectorType(r) {} - template <typename InputIterator> - VectorContainer(InputIterator first, InputIterator last): + template <typename TInputIterator> + VectorContainer(TInputIterator first, TInputIterator last): Object(), VectorType(first, last) {} public: /** This type is provided to Adapt this container as an STL container */ - typedef VectorType STLContainerType; + typedef VectorType STLContainerType; typedef typename VectorType::size_type VectorContainerSizeType; /** Method for creation through the object factory. */ @@ -111,72 +111,68 @@ public: friend class Iterator; friend class ConstIterator; - /** Simulate STL-map style iteration where dereferencing the iterator + /** \class Iterator + * Simulate STL-map style iteration where dereferencing the iterator * gives access to both the index and the value. */ class Iterator - { - public: - Iterator() {} - Iterator(size_type d, const VectorIterator& i): m_Pos(d), m_Iter(i) {} - - Iterator& operator* () { return *this; } - Iterator* operator-> () { return this; } - Iterator& operator++ () { ++m_Pos; ++m_Iter; return *this; } - Iterator operator++ (int) { Iterator temp(*this); ++m_Pos; ++m_Iter; return temp; } - Iterator& operator-- () { --m_Pos; --m_Iter; return *this; } - Iterator operator-- (int) { Iterator temp(*this); --m_Pos; --m_Iter; return temp; } - - bool operator == (const Iterator& r) const { return m_Iter == r.m_Iter; } - bool operator != (const Iterator& r) const { return m_Iter != r.m_Iter; } - bool operator == (const ConstIterator& r) const { return m_Iter == r.m_Iter; } - bool operator != (const ConstIterator& r) const { return m_Iter != r.m_Iter; } - - /** Get the index into the VectorContainer associated with this iterator. */ - ElementIdentifier Index(void) const { return static_cast<ElementIdentifier>( m_Pos ); } - - /** Get the value at this iterator's location in the VectorContainer. */ - Element& Value(void) const { return *m_Iter; } - - private: - size_type m_Pos; - VectorIterator m_Iter; - friend class ConstIterator; + { + public: + Iterator() {} + Iterator(size_type d, const VectorIterator& i): m_Pos(d), m_Iter(i) {} + Iterator& operator* () { return *this; } + Iterator* operator-> () { return this; } + Iterator& operator++ () { ++m_Pos; ++m_Iter; return *this; } + Iterator operator++ (int) { Iterator temp(*this); ++m_Pos; ++m_Iter; return temp; } + Iterator& operator-- () { --m_Pos; --m_Iter; return *this; } + Iterator operator-- (int) { Iterator temp(*this); --m_Pos; --m_Iter; return temp; } + bool operator == (const Iterator& r) const { return m_Iter == r.m_Iter; } + bool operator != (const Iterator& r) const { return m_Iter != r.m_Iter; } + bool operator == (const ConstIterator& r) const { return m_Iter == r.m_Iter; } + bool operator != (const ConstIterator& r) const { return m_Iter != r.m_Iter; } + + /** Get the index into the VectorContainer associated with this iterator. */ + ElementIdentifier Index(void) const { return static_cast<ElementIdentifier>( m_Pos ); } + + /** Get the value at this iterator's location in the VectorContainer. */ + Element& Value(void) const { return *m_Iter; } + + private: + size_type m_Pos; + VectorIterator m_Iter; + friend class ConstIterator; }; - /** Simulate STL-map style const iteration where dereferencing the iterator + /** \class ConstIterator + * Simulate STL-map style const iteration where dereferencing the iterator * gives read access to both the index and the value. */ class ConstIterator - { - public: - ConstIterator() {} - ConstIterator(size_type d, const VectorConstIterator& i): m_Pos(d), m_Iter(i) {} - ConstIterator(const Iterator& r) { m_Pos = r.m_Pos; m_Iter = r.m_Iter; } - - ConstIterator& operator* () { return *this; } - ConstIterator* operator-> () { return this; } - ConstIterator& operator++ () { ++m_Pos; ++m_Iter; return *this; } - ConstIterator operator++ (int) { ConstIterator temp(*this); ++m_Pos; ++m_Iter; return temp; } - ConstIterator& operator-- () { --m_Pos; --m_Iter; return *this; } - ConstIterator operator-- (int) { ConstIterator temp(*this); --m_Pos; --m_Iter; return temp; } - - ConstIterator& operator = (const Iterator& r) { m_Pos = r.m_Pos; m_Iter = r.m_Iter; return *this; } + { + public: + ConstIterator() {} + ConstIterator(size_type d, const VectorConstIterator& i): m_Pos(d), m_Iter(i) {} + ConstIterator(const Iterator& r) { m_Pos = r.m_Pos; m_Iter = r.m_Iter; } + ConstIterator& operator* () { return *this; } + ConstIterator* operator-> () { return this; } + ConstIterator& operator++ () { ++m_Pos; ++m_Iter; return *this; } + ConstIterator operator++ (int) { ConstIterator temp(*this); ++m_Pos; ++m_Iter; return temp; } + ConstIterator& operator-- () { --m_Pos; --m_Iter; return *this; } + ConstIterator operator-- (int) { ConstIterator temp(*this); --m_Pos; --m_Iter; return temp; } + ConstIterator& operator = (const Iterator& r) { m_Pos = r.m_Pos; m_Iter = r.m_Iter; return *this; } + bool operator == (const Iterator& r) const { return m_Iter == r.m_Iter; } + bool operator != (const Iterator& r) const { return m_Iter != r.m_Iter; } + bool operator == (const ConstIterator& r) const { return m_Iter == r.m_Iter; } + bool operator != (const ConstIterator& r) const { return m_Iter != r.m_Iter; } + + /** Get the index into the VectorContainer associated with this iterator. */ + ElementIdentifier Index(void) const { return static_cast<ElementIdentifier>( m_Pos ); } + /** Get the value at this iterator's location in the VectorContainer. */ + const Element& Value(void) const { return *m_Iter; } - bool operator == (const Iterator& r) const { return m_Iter == r.m_Iter; } - bool operator != (const Iterator& r) const { return m_Iter != r.m_Iter; } - bool operator == (const ConstIterator& r) const { return m_Iter == r.m_Iter; } - bool operator != (const ConstIterator& r) const { return m_Iter != r.m_Iter; } - - /** Get the index into the VectorContainer associated with this iterator. */ - ElementIdentifier Index(void) const { return static_cast<ElementIdentifier>( m_Pos ); } - - /** Get the value at this iterator's location in the VectorContainer. */ - const Element& Value(void) const { return *m_Iter; } - - private: - size_type m_Pos; - VectorConstIterator m_Iter; - friend class Iterator; - }; + private: + size_type m_Pos; + VectorConstIterator m_Iter; + friend class Iterator; + }; /* Declare the public interface routines. */ diff --git a/Utilities/ITK/Code/Common/itkVectorContainer.txx b/Utilities/ITK/Code/Common/itkVectorContainer.txx index d9b67f8bab..396bac0478 100644 --- a/Utilities/ITK/Code/Common/itkVectorContainer.txx +++ b/Utilities/ITK/Code/Common/itkVectorContainer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorContainer.txx,v $ Language: C++ - Date: $Date: 2008-01-07 13:33:59 $ - Version: $Revision: 1.43 $ + Date: $Date: 2009-03-03 15:11:40 $ + Version: $Revision: 1.44 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkVectorContainer_txx -#define _itkVectorContainer_txx +#ifndef __itkVectorContainer_txx +#define __itkVectorContainer_txx #include "itkVectorContainer.h" #include "itkNumericTraits.h" @@ -54,8 +54,6 @@ VectorContainer< TElementIdentifier , TElement > return this->VectorType::operator[](id); } - - /** * Get a reference to the element at the given index. * If the element location does not exist, it will be created with a @@ -137,8 +135,6 @@ VectorContainer< TElementIdentifier , TElement > && (identifier < this->VectorType::size())); } - - /** * Check if the given index is in range of the STL vector. If it is not, * return false. Otherwise, set the element through the pointer (if it isn't @@ -278,8 +274,6 @@ VectorContainer< TElementIdentifier , TElement > this->VectorType::clear(); } - - /** * Allocate memory for at the requested number of elements. */ diff --git a/Utilities/ITK/Code/Common/itkVectorImage.h b/Utilities/ITK/Code/Common/itkVectorImage.h index c606963fdb..157c276df4 100644 --- a/Utilities/ITK/Code/Common/itkVectorImage.h +++ b/Utilities/ITK/Code/Common/itkVectorImage.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorImage.h,v $ Language: C++ - Date: $Date: 2008-10-19 20:27:36 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-03-03 15:11:40 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -117,7 +117,8 @@ public: * DefaultVectorPixelAccessor */ typedef DefaultVectorPixelAccessorFunctor< Self > AccessorFunctorType; - /** Tyepdef for the functor used to access a neighborhood of pixel pointers.*/ + /** Typedef for the functor used to access a neighborhood of pixel + * pointers. */ typedef VectorImageNeighborhoodAccessorFunctor< Self > NeighborhoodAccessorFunctorType; @@ -155,7 +156,7 @@ public: typedef typename Superclass::PointType PointType; /** A pointer to the pixel container. */ - typedef typename PixelContainer::Pointer PixelContainerPointer; + typedef typename PixelContainer::Pointer PixelContainerPointer; typedef typename PixelContainer::ConstPointer PixelContainerConstPointer; /** Offset typedef (relative position between indices) */ @@ -175,7 +176,7 @@ public: this->SetLargestPossibleRegion(region); this->SetBufferedRegion(region); this->SetRequestedRegion(region); - }; + } void SetRegions(SizeType size) { @@ -183,7 +184,7 @@ public: this->SetLargestPossibleRegion(region); this->SetBufferedRegion(region); this->SetRequestedRegion(region); - }; + } /** Restore the data object to its initial state. This means releasing * memory. */ @@ -236,7 +237,7 @@ public: * For efficiency, this function does not check that the * image has actually been allocated yet. */ PixelType operator[](const IndexType &index) - { return this->GetPixel(index); } + { return this->GetPixel(index); } /** \brief Access a pixel. This version can only be an rvalue because the * pixel is converted on the fly to a VariableLengthVector. @@ -305,7 +306,7 @@ public: protected: VectorImage(); void PrintSelf( std::ostream& os, Indent indent ) const; - virtual ~VectorImage() {}; + virtual ~VectorImage() {} private: VectorImage( const Self & ); // purposely not implementated diff --git a/Utilities/ITK/Code/Common/itkVectorImage.txx b/Utilities/ITK/Code/Common/itkVectorImage.txx index 099f7dc025..cc01898299 100644 --- a/Utilities/ITK/Code/Common/itkVectorImage.txx +++ b/Utilities/ITK/Code/Common/itkVectorImage.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorImage.txx,v $ Language: C++ - Date: $Date: 2005-12-07 11:21:47 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:11:40 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,8 +17,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkVectorImage_txx -#define _itkVectorImage_txx +#ifndef __itkVectorImage_txx +#define __itkVectorImage_txx #include "itkVectorImage.h" #include "itkProcessObject.h" @@ -177,7 +177,7 @@ VectorImage<TPixel, VImageDimension> os << indent << "PixelContainer: " << std::endl; m_Buffer->Print(os, indent.GetNextIndent()); -// m_Origin and m_Spacing are printed in the Superclass + // m_Origin and m_Spacing are printed in the Superclass } } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkVectorImageNeighborhoodAccessorFunctor.h b/Utilities/ITK/Code/Common/itkVectorImageNeighborhoodAccessorFunctor.h index 33c6fca01b..a5fb985f30 100644 --- a/Utilities/ITK/Code/Common/itkVectorImageNeighborhoodAccessorFunctor.h +++ b/Utilities/ITK/Code/Common/itkVectorImageNeighborhoodAccessorFunctor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorImageNeighborhoodAccessorFunctor.h,v $ Language: C++ - Date: $Date: 2005-10-31 22:16:43 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:11:40 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -123,10 +123,10 @@ public: } private: - VectorLengthType m_VectorLength; - VectorLengthType m_OffsetMultiplier; // m_OffsetMultiplier = m_VectorLength-1 + VectorLengthType m_VectorLength; + VectorLengthType m_OffsetMultiplier; // m_OffsetMultiplier = m_VectorLength-1 // (precomputed for speedup). - InternalPixelType *m_Begin; // Begin of the buffer. + InternalPixelType *m_Begin; // Begin of the buffer. }; diff --git a/Utilities/ITK/Code/Common/itkVectorImageToImageAdaptor.h b/Utilities/ITK/Code/Common/itkVectorImageToImageAdaptor.h index dacce4d1d9..b586af632b 100644 --- a/Utilities/ITK/Code/Common/itkVectorImageToImageAdaptor.h +++ b/Utilities/ITK/Code/Common/itkVectorImageToImageAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorImageToImageAdaptor.h,v $ Language: C++ - Date: $Date: 2008-08-04 15:56:22 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-03 15:11:40 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -87,8 +87,6 @@ private: } // end namespace Accessor - - /** \class VectorImageToImageAdaptor * \brief Presents a VectorImage and extracts a component from it into an image. * @@ -113,12 +111,12 @@ class ITK_EXPORT VectorImageToImageAdaptor : public { public: /** Standard class typedefs. */ - typedef VectorImageToImageAdaptor Self; - typedef VectorImage< TPixelType, Dimension > VectorImageType; + typedef VectorImageToImageAdaptor Self; + typedef VectorImage< TPixelType, Dimension > VectorImageType; typedef ImageAdaptor< VectorImageType, Accessor::VectorImageToImagePixelAccessor< TPixelType > > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -128,8 +126,8 @@ public: /** PixelContainer typedef support. Used to construct a container for * the pixel data. */ - typedef typename Superclass::PixelContainer PixelContainer; - typedef typename Superclass::PixelContainerPointer PixelContainerPointer; + typedef typename Superclass::PixelContainer PixelContainer; + typedef typename Superclass::PixelContainerPointer PixelContainerPointer; typedef typename Superclass::PixelContainerConstPointer PixelContainerConstPointer; typedef typename Superclass::IOPixelType IOPixelType; @@ -148,11 +146,11 @@ public: return this->GetPixelAccessor().GetExtractComponentIdx(); } - protected: +protected: VectorImageToImageAdaptor() {} virtual ~VectorImageToImageAdaptor() {} - private: +private: VectorImageToImageAdaptor(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkVectorInterpolateImageFunction.h b/Utilities/ITK/Code/Common/itkVectorInterpolateImageFunction.h index 123ab282ca..c3136bd72e 100644 --- a/Utilities/ITK/Code/Common/itkVectorInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Common/itkVectorInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2008-05-14 09:26:05 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-03-03 15:11:40 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,17 +73,17 @@ public: typedef VectorInterpolateImageFunction Self; typedef ImageFunction<TInputImage, ITK_TYPENAME NumericTraits<typename TInputImage::PixelType>::RealType, - TCoordRep > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + TCoordRep > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(VectorInterpolateImageFunction, ImageFunction); /** InputImageType typedef support. */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename InputImageType::PixelType PixelType; - typedef typename PixelType::ValueType ValueType; + typedef typename Superclass::InputImageType InputImageType; + typedef typename InputImageType::PixelType PixelType; + typedef typename PixelType::ValueType ValueType; typedef typename NumericTraits<ValueType>::RealType RealType; /** Point typedef support. */ @@ -159,5 +159,3 @@ private: } // end namespace itk #endif - - diff --git a/Utilities/ITK/Code/Common/itkVectorLinearInterpolateImageFunction.h b/Utilities/ITK/Code/Common/itkVectorLinearInterpolateImageFunction.h index e3728c78aa..d8b9d0092d 100644 --- a/Utilities/ITK/Code/Common/itkVectorLinearInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Common/itkVectorLinearInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorLinearInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2008-05-13 15:32:37 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-03 15:11:41 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,10 +44,10 @@ class ITK_EXPORT VectorLinearInterpolateImageFunction : { public: /** Standard class typedefs. */ - typedef VectorLinearInterpolateImageFunction Self; + typedef VectorLinearInterpolateImageFunction Self; typedef VectorInterpolateImageFunction<TInputImage,TCoordRep> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); diff --git a/Utilities/ITK/Code/Common/itkVectorLinearInterpolateImageFunction.txx b/Utilities/ITK/Code/Common/itkVectorLinearInterpolateImageFunction.txx index a175f52a2e..522de396c2 100644 --- a/Utilities/ITK/Code/Common/itkVectorLinearInterpolateImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkVectorLinearInterpolateImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorLinearInterpolateImageFunction.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:36:59 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-05-07 14:03:49 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -74,22 +74,39 @@ VectorLinearInterpolateImageFunction< TInputImage, TCoordRep > */ signed long baseIndex[ImageDimension]; double distance[ImageDimension]; + long tIndex; for( dim = 0; dim < ImageDimension; dim++ ) { - baseIndex[dim] = (long) vcl_floor(index[dim] ); + // The following "if" block is equivalent to the following line without + // having to call floor. + // baseIndex[dim] = (long) vcl_floor(index[dim] ); + if (index[dim] >= 0.0) + { + baseIndex[dim] = (long) index[dim]; + } + else + { + tIndex = (long) index[dim]; + if (double(tIndex) != index[dim]) + { + tIndex--; + } + baseIndex[dim] = tIndex; + } distance[dim] = index[dim] - double( baseIndex[dim] ); } /** - * Interpolated value is the weight some of each of the surrounding - * neighbors. The weight for each neighbour is the fraction overlap + * Interpolated value is the weighted sum of each of the surrounding + * neighbors. The weight for each neighbor is the fraction overlap * of the neighbor pixel with respect to a pixel centered on point. */ OutputType output; output.Fill( 0.0 ); - RealType totalOverlap = 0.0; + typedef typename NumericTraits<PixelType>::ScalarRealType ScalarRealType; + ScalarRealType totalOverlap = NumericTraits<ScalarRealType>::Zero; for( unsigned int counter = 0; counter < m_Neighbors; counter++ ) { @@ -105,11 +122,27 @@ VectorLinearInterpolateImageFunction< TInputImage, TCoordRep > if ( upper & 1 ) { neighIndex[dim] = baseIndex[dim] + 1; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + // Take care of the case where the pixel is just + // in the outer upper boundary of the image grid. + if( neighIndex[dim] > this->m_EndIndex[dim] ) + { + neighIndex[dim] = this->m_EndIndex[dim]; + } +#endif overlap *= distance[dim]; } else { neighIndex[dim] = baseIndex[dim]; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + // Take care of the case where the pixel is just + // in the outer lower boundary of the image grid. + if( neighIndex[dim] < this->m_StartIndex[dim] ) + { + neighIndex[dim] = this->m_StartIndex[dim]; + } +#endif overlap *= 1.0 - distance[dim]; } diff --git a/Utilities/ITK/Code/Common/itkVectorMeanImageFunction.h b/Utilities/ITK/Code/Common/itkVectorMeanImageFunction.h index ed7d1fa983..c5effb105c 100644 --- a/Utilities/ITK/Code/Common/itkVectorMeanImageFunction.h +++ b/Utilities/ITK/Code/Common/itkVectorMeanImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorMeanImageFunction.h,v $ Language: C++ - Date: $Date: 2007-02-05 13:35:53 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-03 15:11:41 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -50,13 +50,13 @@ class ITK_EXPORT VectorMeanImageFunction : { public: /** Standard class typedefs. */ - typedef VectorMeanImageFunction Self; + typedef VectorMeanImageFunction Self; typedef ImageFunction<TInputImage, FixedArray< ITK_TYPENAME NumericTraits<typename TInputImage::PixelType::ValueType>::RealType, ::itk::GetVectorDimension<typename TInputImage::PixelType>::VectorDimension >, - TCoordRep > Superclass; - typedef SmartPointer<Self> Pointer; + TCoordRep > Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ @@ -96,16 +96,16 @@ public: /** Evaluate the function at non-integer positions */ virtual RealType Evaluate( const PointType& point ) const { - IndexType index; - this->ConvertPointToNearestIndex( point, index ); - return this->EvaluateAtIndex( index ); + IndexType index; + this->ConvertPointToNearestIndex( point, index ); + return this->EvaluateAtIndex( index ); } virtual RealType EvaluateAtContinuousIndex( const ContinuousIndexType& cindex ) const { - IndexType index; - this->ConvertContinuousIndexToNearestIndex( cindex, index ); - return this->EvaluateAtIndex( index ) ; + IndexType index; + this->ConvertContinuousIndexToNearestIndex( cindex, index ); + return this->EvaluateAtIndex( index ); } /** Get/Set the radius of the neighborhood over which the @@ -144,4 +144,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Common/itkVectorMeanImageFunction.txx b/Utilities/ITK/Code/Common/itkVectorMeanImageFunction.txx index e90c93a8a4..66c2e7b858 100644 --- a/Utilities/ITK/Code/Common/itkVectorMeanImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkVectorMeanImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorMeanImageFunction.txx,v $ Language: C++ - Date: $Date: 2006-02-06 22:01:58 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:11:44 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,8 +25,8 @@ namespace itk { /** - * Constructor - */ + * Constructor + */ template <class TInputImage, class TCoordRep> VectorMeanImageFunction<TInputImage,TCoordRep> ::VectorMeanImageFunction() @@ -36,8 +36,8 @@ VectorMeanImageFunction<TInputImage,TCoordRep> /** - * - */ + * + */ template <class TInputImage, class TCoordRep> void VectorMeanImageFunction<TInputImage,TCoordRep> diff --git a/Utilities/ITK/Code/Common/itkVectorNearestNeighborInterpolateImageFunction.h b/Utilities/ITK/Code/Common/itkVectorNearestNeighborInterpolateImageFunction.h index 202f377782..6bcaca66b6 100755 --- a/Utilities/ITK/Code/Common/itkVectorNearestNeighborInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Common/itkVectorNearestNeighborInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorNearestNeighborInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2008-05-13 15:32:37 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-03 15:11:45 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,10 +44,10 @@ class ITK_EXPORT VectorNearestNeighborInterpolateImageFunction : { public: /** Standard class typedefs. */ - typedef VectorNearestNeighborInterpolateImageFunction Self; + typedef VectorNearestNeighborInterpolateImageFunction Self; typedef VectorInterpolateImageFunction<TInputImage,TCoordRep> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -88,11 +88,11 @@ public: * calling the method. */ virtual OutputType EvaluateAtContinuousIndex( const ContinuousIndexType & index ) const - { - IndexType nindex; - this->ConvertContinuousIndexToNearestIndex(index, nindex); - return static_cast<OutputType>( this->GetInputImage()->GetPixel( nindex ) ); - } + { + IndexType nindex; + this->ConvertContinuousIndexToNearestIndex(index, nindex); + return static_cast<OutputType>( this->GetInputImage()->GetPixel( nindex ) ); + } protected: VectorNearestNeighborInterpolateImageFunction(){}; diff --git a/Utilities/ITK/Code/Common/itkVectorNeighborhoodInnerProduct.h b/Utilities/ITK/Code/Common/itkVectorNeighborhoodInnerProduct.h index 659e148d2a..2605f0cdad 100644 --- a/Utilities/ITK/Code/Common/itkVectorNeighborhoodInnerProduct.h +++ b/Utilities/ITK/Code/Common/itkVectorNeighborhoodInnerProduct.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorNeighborhoodInnerProduct.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:29 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-03 15:11:45 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,10 +48,10 @@ public: itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); /** Extract the pixel type and scalar type from the image template parameter. */ - typedef typename TImage::PixelType PixelType; + typedef typename TImage::PixelType PixelType; typedef typename PixelType::ValueType ScalarValueType; - typedef Neighborhood<PixelType, - itkGetStaticConstMacro(ImageDimension)> NeighborhoodType; + typedef Neighborhood<PixelType, itkGetStaticConstMacro(ImageDimension)> + NeighborhoodType; /** Extract the image and vector dimension from the image template parameter. */ itkStaticConstMacro(VectorDimension, unsigned int, @@ -70,7 +70,7 @@ public: PixelType operator()(const ConstNeighborhoodIterator<TImage> &it, const OperatorType &op) const { - return this->operator()(std::slice(0, it.Size(), 1), it, op); + return this->operator()(std::slice(0, it.Size(), 1), it, op); } PixelType operator()(const std::slice &s, const NeighborhoodType &N, diff --git a/Utilities/ITK/Code/Common/itkVectorNeighborhoodInnerProduct.txx b/Utilities/ITK/Code/Common/itkVectorNeighborhoodInnerProduct.txx index d6fc001ba9..777de88e7c 100644 --- a/Utilities/ITK/Code/Common/itkVectorNeighborhoodInnerProduct.txx +++ b/Utilities/ITK/Code/Common/itkVectorNeighborhoodInnerProduct.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorNeighborhoodInnerProduct.txx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:29 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-03 15:11:45 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkVectorNeighborhoodInnerProduct_txx -#define _itkVectorNeighborhoodInnerProduct_txx +#ifndef __itkVectorNeighborhoodInnerProduct_txx +#define __itkVectorNeighborhoodInnerProduct_txx #include "itkVectorNeighborhoodInnerProduct.h" @@ -80,7 +80,5 @@ VectorNeighborhoodInnerProduct<TImage> return sum; } - - }// end namespace itk #endif diff --git a/Utilities/ITK/Code/Common/itkVectorToRGBImageAdaptor.h b/Utilities/ITK/Code/Common/itkVectorToRGBImageAdaptor.h index 1872af7475..e3ced7f07b 100644 --- a/Utilities/ITK/Code/Common/itkVectorToRGBImageAdaptor.h +++ b/Utilities/ITK/Code/Common/itkVectorToRGBImageAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorToRGBImageAdaptor.h,v $ Language: C++ - Date: $Date: 2003-12-08 14:08:20 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:11:48 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,13 +40,13 @@ class ITK_EXPORT VectorToRGBImageAdaptor : public { public: /** Standard class typedefs. */ - typedef VectorToRGBImageAdaptor Self; + typedef VectorToRGBImageAdaptor Self; typedef ImageAdaptor<TImage, Accessor::VectorToRGBPixelAccessor< typename TImage::PixelType::ValueType > > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -56,15 +56,15 @@ public: /** PixelContainer typedef support. Used to construct a container for * the pixel data. */ - typedef typename Superclass::PixelContainer PixelContainer; - typedef typename Superclass::PixelContainerPointer PixelContainerPointer; + typedef typename Superclass::PixelContainer PixelContainer; + typedef typename Superclass::PixelContainerPointer PixelContainerPointer; typedef typename Superclass::PixelContainerConstPointer PixelContainerConstPointer; - protected: +protected: VectorToRGBImageAdaptor() {} virtual ~VectorToRGBImageAdaptor() {} - private: +private: VectorToRGBImageAdaptor(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkVectorToRGBPixelAccessor.h b/Utilities/ITK/Code/Common/itkVectorToRGBPixelAccessor.h index c67575c42c..9ce77f87ad 100644 --- a/Utilities/ITK/Code/Common/itkVectorToRGBPixelAccessor.h +++ b/Utilities/ITK/Code/Common/itkVectorToRGBPixelAccessor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorToRGBPixelAccessor.h,v $ Language: C++ - Date: $Date: 2003-12-12 14:20:58 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-03 15:11:49 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -76,4 +76,3 @@ private: } // end namespace itk #endif - diff --git a/Utilities/ITK/Code/Common/itkVersion.h b/Utilities/ITK/Code/Common/itkVersion.h index bdf86d7a5e..73b39a4110 100644 --- a/Utilities/ITK/Code/Common/itkVersion.h +++ b/Utilities/ITK/Code/Common/itkVersion.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVersion.h,v $ Language: C++ - Date: $Date: 2009-02-28 03:00:08 $ - Version: $Revision: 1.2956 $ + Date: $Date: 2009-05-26 02:00:07 $ + Version: $Revision: 1.3044 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -28,7 +28,7 @@ #define ITK_VERSION ITK_VERSION_TO_STRING(ITK_VERSION_MAJOR) "." \ ITK_VERSION_TO_STRING(ITK_VERSION_MINOR) "." \ ITK_VERSION_TO_STRING(ITK_VERSION_PATCH) -#define ITK_SOURCE_VERSION "itk version " ITK_VERSION ", itk source $Revision: 1.2956 $, $Date: 2009-02-28 03:00:08 $ (GMT)" +#define ITK_SOURCE_VERSION "itk version " ITK_VERSION ", itk source $Revision: 1.3044 $, $Date: 2009-05-26 02:00:07 $ (GMT)" namespace itk { @@ -48,9 +48,9 @@ class ITKCommon_EXPORT Version : public Object { public: /** Standard class typedefs. */ - typedef Version Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; + typedef Version Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ @@ -62,11 +62,11 @@ public: /** Return the version of itk this object is a part of. * A variety of methods are included. GetITKSourceVersion returns a string * with an identifier which timestamps a particular source tree. */ - static const char *GetITKVersion() { return ITK_VERSION; }; - static int GetITKMajorVersion() { return ITK_VERSION_MAJOR; }; - static int GetITKMinorVersion() { return ITK_VERSION_MINOR; }; - static int GetITKBuildVersion() { return ITK_VERSION_PATCH; }; - static const char *GetITKSourceVersion() { return ITK_SOURCE_VERSION; }; + static const char *GetITKVersion() { return ITK_VERSION; } + static int GetITKMajorVersion() { return ITK_VERSION_MAJOR; } + static int GetITKMinorVersion() { return ITK_VERSION_MINOR; } + static int GetITKBuildVersion() { return ITK_VERSION_PATCH; } + static const char *GetITKSourceVersion() { return ITK_SOURCE_VERSION; } protected: Version(); diff --git a/Utilities/ITK/Code/Common/itkVersorRigid3DTransform.h b/Utilities/ITK/Code/Common/itkVersorRigid3DTransform.h index cc0da221c8..9bec7cf580 100644 --- a/Utilities/ITK/Code/Common/itkVersorRigid3DTransform.h +++ b/Utilities/ITK/Code/Common/itkVersorRigid3DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVersorRigid3DTransform.h,v $ Language: C++ - Date: $Date: 2006-08-09 04:35:32 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-04-13 23:41:53 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -114,10 +114,6 @@ protected: void PrintSelf(std::ostream &os, Indent indent) const; - /** This method must be made protected here because it is not a safe way of - * initializing the Versor */ - virtual void SetRotationMatrix(const MatrixType & matrix) - { this->Superclass::SetRotationMatrix( matrix ); } private: VersorRigid3DTransform(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkVersorTransform.h b/Utilities/ITK/Code/Common/itkVersorTransform.h index e5936c1088..44cda470d1 100644 --- a/Utilities/ITK/Code/Common/itkVersorTransform.h +++ b/Utilities/ITK/Code/Common/itkVersorTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVersorTransform.h,v $ Language: C++ - Date: $Date: 2006-08-09 04:35:32 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-03-03 15:11:51 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ namespace itk { -/** +/** \class VersorTransform * * VersorTransform of a vector space (e.g. space coordinates) * @@ -44,7 +44,7 @@ namespace itk * * \ingroup Transforms * - **/ + */ template < class TScalarType=double >//Data type for scalars (float or double) class ITK_EXPORT VersorTransform : public Rigid3DTransform< TScalarType > { diff --git a/Utilities/ITK/Code/Common/itkVertexCell.txx b/Utilities/ITK/Code/Common/itkVertexCell.txx index 63d6d60964..41002fed8e 100644 --- a/Utilities/ITK/Code/Common/itkVertexCell.txx +++ b/Utilities/ITK/Code/Common/itkVertexCell.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVertexCell.txx,v $ Language: C++ - Date: $Date: 2007-05-17 21:00:09 $ - Version: $Revision: 1.38 $ + Date: $Date: 2009-03-03 15:11:51 $ + Version: $Revision: 1.39 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -125,7 +125,8 @@ VertexCell< TCellInterface > /** Standard CellInterface: - * Get a begin iterator to the list of point identifiers used by the cell.*/ + * Get a begin iterator to the list of point identifiers used by the + * cell. */ template <typename TCellInterface> typename VertexCell< TCellInterface >::PointIdIterator VertexCell< TCellInterface > diff --git a/Utilities/ITK/Code/Common/itkVolumeSplineKernelTransform.h b/Utilities/ITK/Code/Common/itkVolumeSplineKernelTransform.h index 31d06623ee..3086f64455 100644 --- a/Utilities/ITK/Code/Common/itkVolumeSplineKernelTransform.h +++ b/Utilities/ITK/Code/Common/itkVolumeSplineKernelTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVolumeSplineKernelTransform.h,v $ Language: C++ - Date: $Date: 2007-12-20 17:10:46 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-05-17 14:27:03 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -29,7 +29,8 @@ namespace itk * * \ingroup Transforms */ -template <class TScalarType, // Data type for scalars (float or double) +template <class TScalarType, // Data type for scalars (float or + // double) unsigned int NDimensions = 3> // Number of dimensions class ITK_EXPORT VolumeSplineKernelTransform : public KernelTransform< TScalarType, NDimensions> @@ -57,27 +58,28 @@ public: typedef typename Superclass::JacobianType JacobianType; /** Dimension of the domain space. */ - itkStaticConstMacro(SpaceDimension, unsigned int,Superclass::SpaceDimension); + itkStaticConstMacro(SpaceDimension, unsigned int, + Superclass::SpaceDimension); /** These (rather redundant) typedefs are needed because on SGI, typedefs * are not inherited */ - typedef typename Superclass::InputPointType InputPointType; - typedef typename Superclass::OutputPointType OutputPointType; - typedef typename Superclass::InputVectorType InputVectorType; - typedef typename Superclass::OutputVectorType OutputVectorType; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::OutputPointType OutputPointType; + typedef typename Superclass::InputVectorType InputVectorType; + typedef typename Superclass::OutputVectorType OutputVectorType; typedef typename Superclass::InputCovariantVectorType - InputCovariantVectorType; + InputCovariantVectorType; typedef typename Superclass::OutputCovariantVectorType - OutputCovariantVectorType; - typedef typename Superclass::PointsIterator PointsIterator; + OutputCovariantVectorType; + typedef typename Superclass::PointsIterator PointsIterator; protected: VolumeSplineKernelTransform() {}; virtual ~VolumeSplineKernelTransform() {} - /** These (rather redundant) typedefs are needed because on SGI, typedefs - * are not inherited. */ + /** These (rather redundant) typedefs are needed because on SGI, + * typedefs are not inherited. */ typedef typename Superclass::GMatrixType GMatrixType; /** Compute G(x) @@ -88,17 +90,22 @@ protected: * r(x) = Euclidean norm = sqrt[x1^2 + x2^2 + x3^2] * \f[ r(x) = \sqrt{ x_1^2 + x_2^2 + x_3^2 } \f] * I = identity matrix. */ - virtual void ComputeG(const InputVectorType& landmarkVector, GMatrixType & gmatrix) const; + virtual void ComputeG(const InputVectorType& landmarkVector, + GMatrixType & gmatrix) const; /** - * \deprecated in ITK 3.6, please use void ComputeG(vector,gmatrix) instead. + * \deprecated in ITK 3.6, please use void ComputeG(vector,gmatrix) + * instead. */ - itkLegacyMacro( virtual const GMatrixType & ComputeG(const InputVectorType& landmarkVector) const ); + itkLegacyMacro( virtual const GMatrixType & ComputeG( + const InputVectorType & landmarkVector + ) const ); - /** Compute the contribution of the landmarks weighted by the kernel funcion - to the global deformation of the space */ - virtual void ComputeDeformationContribution(const InputPointType & inputPoint, - OutputPointType & result ) const; + /** Compute the contribution of the landmarks weighted by the kernel + * funcion to the global deformation of the space */ + virtual void ComputeDeformationContribution( + const InputPointType & inputPoint, + OutputPointType & result ) const; private: VolumeSplineKernelTransform(const Self&); //purposely not implemented @@ -109,10 +116,12 @@ private: } // namespace itk // Define instantiation macro for this template. -#define ITK_TEMPLATE_VolumeSplineKernelTransform(_, EXPORT, x, y) namespace itk { \ - _(2(class EXPORT VolumeSplineKernelTransform< ITK_TEMPLATE_2 x >)) \ - namespace Templates { typedef VolumeSplineKernelTransform< ITK_TEMPLATE_2 x > \ - VolumeSplineKernelTransform##y; } \ +#define ITK_TEMPLATE_VolumeSplineKernelTransform(_, EXPORT, x, y) \ + namespace itk { \ + _(2(class EXPORT VolumeSplineKernelTransform< ITK_TEMPLATE_2 x >)) \ + namespace Templates { typedef \ + VolumeSplineKernelTransform< ITK_TEMPLATE_2 x > \ + VolumeSplineKernelTransform##y; } \ } #if ITK_TEMPLATE_EXPLICIT diff --git a/Utilities/ITK/Code/Common/itkWindowedSincInterpolateImageFunction.h b/Utilities/ITK/Code/Common/itkWindowedSincInterpolateImageFunction.h index 623e50a486..4b278422ff 100644 --- a/Utilities/ITK/Code/Common/itkWindowedSincInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Common/itkWindowedSincInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWindowedSincInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2006-03-19 04:36:59 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-06 00:05:54 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. diff --git a/Utilities/ITK/Code/Common/itkXMLFileOutputWindow.cxx b/Utilities/ITK/Code/Common/itkXMLFileOutputWindow.cxx index dd6e06ab2e..80a9dec8ab 100644 --- a/Utilities/ITK/Code/Common/itkXMLFileOutputWindow.cxx +++ b/Utilities/ITK/Code/Common/itkXMLFileOutputWindow.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkXMLFileOutputWindow.cxx,v $ Language: C++ - Date: $Date: 2008-05-26 00:24:36 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-03 15:11:51 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -80,7 +80,7 @@ XMLFileOutputWindow ::DisplayXML(const char* tag, const char* text) { char *xmlText; - + if(!text) { return; @@ -99,27 +99,39 @@ XMLFileOutputWindow switch (*s) { case '&': + { strcat(x, "&"); x += 5; break; + } case '"': + { strcat(x, """); x += 6; break; + } case '\'': + { strcat(x, "'"); x += 6; break; + } case '<': + { strcat(x, "<"); x += 4; break; + } case '>': + { strcat(x, ">"); x += 4; break; + } default: + { *x = *s; x++; *x = '\0'; // explicitly terminate the new string + } } s++; } - + if (!m_Stream) { this->Initialize(); diff --git a/Utilities/ITK/Code/Common/itkXMLFilterWatcher.h b/Utilities/ITK/Code/Common/itkXMLFilterWatcher.h index e0f4e54251..295df121c5 100644 --- a/Utilities/ITK/Code/Common/itkXMLFilterWatcher.h +++ b/Utilities/ITK/Code/Common/itkXMLFilterWatcher.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkXMLFilterWatcher.h,v $ Language: C++ - Date: $Date: 2007-08-22 15:52:31 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-03 15:11:53 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,74 +35,73 @@ public: protected: -/** Callback method to show the ProgressEvent */ -virtual void ShowProgress() -{ - if (this->GetProcess()) + /** Callback method to show the ProgressEvent */ + virtual void ShowProgress() { - int steps = this->GetSteps(); - steps++; - this->SetSteps(steps); + if (this->GetProcess()) + { + int steps = this->GetSteps(); + steps++; + this->SetSteps(steps); + if (!this->GetQuiet()) + { + std::cout << "<filter-progress>" + << this->GetProcess()->GetProgress() + << "</filter-progress>" + << std::endl; + std::cout << std::flush; + } + } + } + + /** Callback method to show the StartEvent */ + virtual void StartFilter() + { + this->SetSteps(0); + this->SetIterations(0); + this->GetTimeProbe().Start(); if (!this->GetQuiet()) { - std::cout << "<filter-progress>" - << this->GetProcess()->GetProgress() - << "</filter-progress>" + std::cout << "<filter-start>" + << std::endl; + std::cout << "<filter-name>" + << (this->GetProcess() + ? this->GetProcess()->GetNameOfClass() : "None") + << "</filter-name>" + << std::endl; + std::cout << "<filter-comment>" + << " \"" << this->GetComment() << "\" " + << "</filter-comment>" + << std::endl; + std::cout << "</filter-start>" << std::endl; std::cout << std::flush; } } -} - -/** Callback method to show the StartEvent */ -virtual void StartFilter() -{ - this->SetSteps(0); - this->SetIterations(0); - this->GetTimeProbe().Start(); - if (!this->GetQuiet()) + + /** Callback method to show the EndEvent */ + virtual void EndFilter() { - std::cout << "<filter-start>" - << std::endl; - std::cout << "<filter-name>" - << (this->GetProcess() - ? this->GetProcess()->GetNameOfClass() : "None") - << "</filter-name>" - << std::endl; - std::cout << "<filter-comment>" - << " \"" << this->GetComment() << "\" " - << "</filter-comment>" - << std::endl; - std::cout << "</filter-start>" - << std::endl; - std::cout << std::flush; - } -} - -/** Callback method to show the EndEvent */ -virtual void EndFilter() -{ #if 0 - this-GetTimeProbe().Stop(); - if (!this->GetQuiet()) - { - std::cout << "<filter-end>" - << std::endl; - std::cout << "<filter-name>" - << (this->GetProcess() - ? this->GetProcess()->GetNameOfClass() : "None") - << "</filter-name>" - << std::endl; - std::cout << "<filter-time>" - << this->GetTimeProbe().GetMeanTime() - << "</filter-time>" - << std::endl; - std::cout << "</filter-end>"; - std::cout << std::flush; - } + this-GetTimeProbe().Stop(); + if (!this->GetQuiet()) + { + std::cout << "<filter-end>" + << std::endl; + std::cout << "<filter-name>" + << (this->GetProcess() + ? this->GetProcess()->GetNameOfClass() : "None") + << "</filter-name>" + << std::endl; + std::cout << "<filter-time>" + << this->GetTimeProbe().GetMeanTime() + << "</filter-time>" + << std::endl; + std::cout << "</filter-end>"; + std::cout << std::flush; + } #endif -} - + } }; } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itk_hashtable.h b/Utilities/ITK/Code/Common/itk_hashtable.h index 3e9dc57836..624670ea20 100644 --- a/Utilities/ITK/Code/Common/itk_hashtable.h +++ b/Utilities/ITK/Code/Common/itk_hashtable.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itk_hashtable.h,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:15 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-04-05 10:56:47 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -1136,7 +1136,7 @@ void hashtable_base<Value, Alloc>::copy_from(const hashtable_base<Value, Alloc>& // A few compatability fixes. Placed here for automatic include in // both the hash_set and the hash_map sources. -# if defined(VCL_SUNPRO_CC) || defined (_MSC_VER) || defined(__BORLANDC__) || ((defined(__ICC)||defined(__ECC)) && defined(linux)) +# if defined (_MSC_VER) || defined(__BORLANDC__) || ((defined(__ICC)||defined(__ECC)) && defined(linux)) namespace std { template <class T> diff --git a/Utilities/ITK/Code/IO/CMakeLists.txt b/Utilities/ITK/Code/IO/CMakeLists.txt index fd93770777..104b0c012d 100644 --- a/Utilities/ITK/Code/IO/CMakeLists.txt +++ b/Utilities/ITK/Code/IO/CMakeLists.txt @@ -82,16 +82,16 @@ IF (APPLE) ENDIF (APPLE) IF( OTB_USE_EXTERNAL_EXPAT ) - TARGET_LINK_LIBRARIES(ITKIO - ITKNrrdIO - ${ITK_GDCM_LIBRARIES} - ${ITK_PNG_LIBRARIES} - ${ITK_TIFF_LIBRARIES} - ITKSpatialObject - ITKMetaIO - ITKDICOMParser +TARGET_LINK_LIBRARIES(ITKIO +ITKNrrdIO +${ITK_GDCM_LIBRARIES} +${ITK_PNG_LIBRARIES} +${ITK_TIFF_LIBRARIES} +ITKSpatialObject +ITKMetaIO +ITKDICOMParser expat - ITKniftiio) +ITKniftiio) ELSE( OTB_USE_EXTERNAL_EXPAT ) TARGET_LINK_LIBRARIES(ITKIO ITKNrrdIO @@ -127,13 +127,13 @@ ENDIF(SUN_COMPILER) # itkTestDriver is built even when BUILD_TESTING is FALSE to: # + allow to run WrapITK tests without the other of the ITK tests # + be used by external code like contributions to the insight journal -ADD_EXECUTABLE(itkTestDriver itkTestDriver.cxx) +ADD_EXECUTABLE(itkTestDriver itkTestDriver.cxx) TARGET_LINK_LIBRARIES(itkTestDriver ITKIO) IF(NOT ITK_INSTALL_NO_DEVELOPMENT) INSTALL(TARGETS itkTestDriver RUNTIME DESTINATION ${ITK_INSTALL_BIN_DIR_CM24} COMPONENT Development) ENDIF(NOT ITK_INSTALL_NO_DEVELOPMENT) -SET(ITK_TEST_DRIVER "${EXECUTABLE_OUTPUT_PATH}/itkTestDriver" +SET(ITK_TEST_DRIVER "${EXECUTABLE_OUTPUT_PATH}/itkTestDriver" CACHE INTERNAL "itkTestDriver path to be used by subprojects") IF(ITK_LIBRARY_PROPERTIES) diff --git a/Utilities/ITK/Code/IO/itkAnalyzeImageIO.cxx b/Utilities/ITK/Code/IO/itkAnalyzeImageIO.cxx index 3588e694a7..cea43d104a 100644 --- a/Utilities/ITK/Code/IO/itkAnalyzeImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkAnalyzeImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnalyzeImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-02-22 05:53:41 $ - Version: $Revision: 1.94 $ + Date: $Date: 2009-04-30 23:08:50 $ + Version: $Revision: 1.99 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,6 +23,7 @@ #include "itkByteSwapper.h" #include "itkMetaDataObject.h" #include "itkSpatialOrientationAdapter.h" +#include "itkRGBPixel.h" #include <itksys/SystemTools.hxx> #include "itkMacro.h" #include "itk_zlib.h" @@ -44,7 +45,8 @@ const char *const ANALYZE_GLMIN = "ANALYZE_GLMIN"; const char *const ANALYZE_AUX_FILE_NAME = "ANALYZE_AUX_FILE_NAME"; const char *const ANALYZE_CALIBRATIONUNITS = "ANALYZE_CALIBRATIONUNITS"; //An array of the Analyze v7.5 known DataTypes -const char DataTypes[12][10]= { +const char DataTypes[12][10]= +{ "UNKNOWN","BINARY","CHAR","SHORT", "INT","FLOAT", "COMPLEX", "DOUBLE","RGB","ALL","USHORT","UINT" }; @@ -54,7 +56,8 @@ const char DataTypes[12][10]= { const short int DataTypeSizes[12]={0,1,8,16,32,32,64,64,24,0,16,32}; //An array with Data type key sizes -const short int DataTypeKey[12]={ +const short int DataTypeKey[12] = +{ ANALYZE_DT_UNKNOWN, ANALYZE_DT_BINARY, ANALYZE_DT_UNSIGNED_CHAR, @@ -96,8 +99,8 @@ GetRootName( const std::string& filename ) // Create a base filename // i.e Image.hdr --> Image if( fileExt.length() > 0 //Ensure that an extension was found - && filename.length() > fileExt.length() //Ensure that the filename does not contain only the extension - ) + && filename.length() > fileExt.length() //Ensure that the filename does not contain only the extension + ) { const std::string::size_type it = filename.find_last_of( fileExt ); const std::string baseName( filename, 0, it-(fileExt.length()-1) ); @@ -275,61 +278,61 @@ AnalyzeImageIO::SwapHeaderBytesIfNecessary( struct dsr * const imageheader ) // swapped, the SwapFromBigEndianToSystem is equivalent to // SwapFromSystemToBigEndian. ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->hk.sizeof_hdr); + &imageheader->hk.sizeof_hdr); ByteSwapper<int >::SwapFromSystemToLittleEndian( - &imageheader->hk.extents ); + &imageheader->hk.extents ); ByteSwapper<short int>::SwapFromSystemToLittleEndian( - &imageheader->hk.session_error ); + &imageheader->hk.session_error ); ByteSwapper<short int>::SwapRangeFromSystemToLittleEndian( - &imageheader->dime.dim[0], 8 ); + &imageheader->dime.dim[0], 8 ); ByteSwapper<short int>::SwapFromSystemToLittleEndian( - &imageheader->dime.unused1 ); + &imageheader->dime.unused1 ); ByteSwapper<short int>::SwapFromSystemToLittleEndian( - &imageheader->dime.datatype ); + &imageheader->dime.datatype ); ByteSwapper<short int>::SwapFromSystemToLittleEndian( - &imageheader->dime.bitpix ); + &imageheader->dime.bitpix ); ByteSwapper<short int>::SwapFromSystemToLittleEndian( - &imageheader->dime.dim_un0 ); + &imageheader->dime.dim_un0 ); ByteSwapper<float>::SwapRangeFromSystemToLittleEndian( - &imageheader->dime.pixdim[0],8 ); + &imageheader->dime.pixdim[0],8 ); ByteSwapper<float>::SwapFromSystemToLittleEndian( - &imageheader->dime.vox_offset ); + &imageheader->dime.vox_offset ); ByteSwapper<float>::SwapFromSystemToLittleEndian( - &imageheader->dime.roi_scale ); + &imageheader->dime.roi_scale ); ByteSwapper<float>::SwapFromSystemToLittleEndian( - &imageheader->dime.funused1 ); + &imageheader->dime.funused1 ); ByteSwapper<float>::SwapFromSystemToLittleEndian( - &imageheader->dime.funused2 ); + &imageheader->dime.funused2 ); ByteSwapper<float>::SwapFromSystemToLittleEndian( - &imageheader->dime.cal_max ); + &imageheader->dime.cal_max ); ByteSwapper<float>::SwapFromSystemToLittleEndian( - &imageheader->dime.cal_min ); + &imageheader->dime.cal_min ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->dime.compressed ); + &imageheader->dime.compressed ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->dime.verified ); + &imageheader->dime.verified ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->dime.glmax ); + &imageheader->dime.glmax ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->dime.glmin ); + &imageheader->dime.glmin ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->hist.views ); + &imageheader->hist.views ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->hist.vols_added ); + &imageheader->hist.vols_added ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->hist.start_field ); + &imageheader->hist.start_field ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->hist.field_skip ); + &imageheader->hist.field_skip ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->hist.omax ); + &imageheader->hist.omax ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->hist.omin ); + &imageheader->hist.omin ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->hist.smax ); + &imageheader->hist.smax ); ByteSwapper<int>::SwapFromSystemToLittleEndian( - &imageheader->hist.smin ); + &imageheader->hist.smin ); } else if ( m_ByteOrder == BigEndian ) { @@ -337,62 +340,62 @@ AnalyzeImageIO::SwapHeaderBytesIfNecessary( struct dsr * const imageheader ) // swapped, the SwapFromBigEndianToSystem is equivalent to // SwapFromSystemToLittleEndian. ByteSwapper<int >::SwapFromSystemToBigEndian( - &imageheader->hk.sizeof_hdr ); + &imageheader->hk.sizeof_hdr ); ByteSwapper<int >::SwapFromSystemToBigEndian( - &imageheader->hk.extents ); + &imageheader->hk.extents ); ByteSwapper<short int>::SwapFromSystemToBigEndian( - &imageheader->hk.session_error ); + &imageheader->hk.session_error ); ByteSwapper<short int>::SwapRangeFromSystemToBigEndian( - &imageheader->dime.dim[0], 8 ); + &imageheader->dime.dim[0], 8 ); ByteSwapper<short int>::SwapFromSystemToBigEndian( - &imageheader->dime.unused1 ); + &imageheader->dime.unused1 ); ByteSwapper<short int>::SwapFromSystemToBigEndian( - &imageheader->dime.datatype ); + &imageheader->dime.datatype ); ByteSwapper<short int>::SwapFromSystemToBigEndian( - &imageheader->dime.bitpix ); + &imageheader->dime.bitpix ); ByteSwapper<short int>::SwapFromSystemToBigEndian( - &imageheader->dime.dim_un0 ); + &imageheader->dime.dim_un0 ); ByteSwapper<float>::SwapRangeFromSystemToBigEndian( - &imageheader->dime.pixdim[0],8 ); + &imageheader->dime.pixdim[0],8 ); ByteSwapper<float>::SwapFromSystemToBigEndian( - &imageheader->dime.vox_offset ); + &imageheader->dime.vox_offset ); ByteSwapper<float>::SwapFromSystemToBigEndian( - &imageheader->dime.roi_scale ); + &imageheader->dime.roi_scale ); ByteSwapper<float>::SwapFromSystemToBigEndian( - &imageheader->dime.funused1 ); + &imageheader->dime.funused1 ); ByteSwapper<float>::SwapFromSystemToBigEndian( - &imageheader->dime.funused2 ); + &imageheader->dime.funused2 ); ByteSwapper<float>::SwapFromSystemToBigEndian( - &imageheader->dime.cal_max ); + &imageheader->dime.cal_max ); ByteSwapper<float>::SwapFromSystemToBigEndian( - &imageheader->dime.cal_min ); + &imageheader->dime.cal_min ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->dime.compressed ); + &imageheader->dime.compressed ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->dime.verified ); + &imageheader->dime.verified ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->dime.glmax ); + &imageheader->dime.glmax ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->dime.glmin ); + &imageheader->dime.glmin ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->hist.views ); + &imageheader->hist.views ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->hist.vols_added ); + &imageheader->hist.vols_added ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->hist.start_field ); + &imageheader->hist.start_field ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->hist.field_skip ); + &imageheader->hist.field_skip ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->hist.omax ); + &imageheader->hist.omax ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->hist.omin ); + &imageheader->hist.omin ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->hist.smax ); + &imageheader->hist.smax ); ByteSwapper<int>::SwapFromSystemToBigEndian( - &imageheader->hist.smin ); + &imageheader->hist.smin ); } else { @@ -487,7 +490,7 @@ AnalyzeImageIO::AnalyzeImageIO() this->m_Hdr.dime.cal_max=0.0f; // specify range of calibration values this->m_Hdr.dime.cal_min=0.0f; // specify range of calibration values this->m_Hdr.dime.compressed=0; // specify that the data file with extension - // .img is not compressed + // .img is not compressed this->m_Hdr.dime.verified=0; this->m_Hdr.dime.glmax=0; // max value for all of the data set this->m_Hdr.dime.glmin=0; // min value for all of the data set @@ -592,7 +595,15 @@ void AnalyzeImageIO::DefineHeaderObjectDataType() { case CHAR: case UCHAR: - eNewType=ANALYZE_DT_INDEX_UNSIGNED_CHAR; + if(this->GetPixelType() == RGB) + { + eNewType = ANALYZE_DT_INDEX_RGB; + this->SetNumberOfComponents(3); + } + else + { + eNewType=ANALYZE_DT_INDEX_UNSIGNED_CHAR; + } break; case SHORT: eNewType=ANALYZE_DT_INDEX_SIGNED_SHORT; @@ -634,35 +645,35 @@ void AnalyzeImageIO::DefineHeaderObjectDataType() strcpy(m_Hdr.hk.data_type,DataTypes[eNewType]); switch(m_Hdr.dime.datatype) { - case ANALYZE_DT_INDEX_BINARY: + case ANALYZE_DT_BINARY: m_Hdr.dime.glmax=1; /*max value for all of the data set*/ m_Hdr.dime.glmin=0; /*min value for all of the data set*/ break; - case ANALYZE_DT_INDEX_UNSIGNED_CHAR: + case ANALYZE_DT_UNSIGNED_CHAR: m_Hdr.dime.glmax=255;/*max value for all of the data set*/ m_Hdr.dime.glmin=0; /*min value for all of the data set*/ break; - case ANALYZE_DT_INDEX_SIGNED_SHORT: + case ANALYZE_DT_SIGNED_SHORT: //m_Hdr.dime.glmax=0;/*max value for all of the data set*/ //m_Hdr.dime.glmin=0;/*min value for all of the data set*/ break; - case ANALYZE_DT_INDEX_FLOAT: + case ANALYZE_DT_FLOAT: //m_Hdr.dime.glmax=0;/*max value for all of the data set*/ //m_Hdr.dime.glmin=0;/*min value for all of the data set*/ break; - case ANALYZE_DT_INDEX_DOUBLE: + case ANALYZE_DT_DOUBLE: //m_Hdr.dime.glmax=0;/*max value for all of the data set*/ //m_Hdr.dime.glmin=0;/*min value for all of the data set*/ break; - case ANALYZE_DT_INDEX_RGB: + case ANALYZE_DT_RGB: m_Hdr.dime.glmax=255;/*max value for all of the data set*/ m_Hdr.dime.glmin=0;/*min value for all of the data set*/ break; default: m_Hdr.dime.glmax=0; /*max value for all of the - data set*/ + data set*/ m_Hdr.dime.glmin=0; /*min value for all of - the data set*/ + the data set*/ break; } } @@ -740,9 +751,9 @@ bool AnalyzeImageIO::CanReadFile( const char* FileNameToRead ) // we check that the correct extension is given by the user std::string filenameext = GetExtension(filename); if(filenameext != std::string(".hdr") - && filenameext != std::string(".img.gz") - && filenameext != std::string(".img") - ) + && filenameext != std::string(".img.gz") + && filenameext != std::string(".img") + ) { return false; } @@ -751,14 +762,14 @@ bool AnalyzeImageIO::CanReadFile( const char* FileNameToRead ) std::ifstream local_InputStream; local_InputStream.open( HeaderFileName.c_str(), - std::ios::in | std::ios::binary ); + std::ios::in | std::ios::binary ); if( local_InputStream.fail() ) { return false; } if( ! this->ReadBufferAsBinary( local_InputStream, - (void *)&(this->m_Hdr), - sizeof(struct dsr) ) ) + (void *)&(this->m_Hdr), + sizeof(struct dsr) ) ) { local_InputStream.close(); return false; @@ -824,6 +835,23 @@ void AnalyzeImageIO::ReadImageInformation() // m_Hdr.dime.dim[3] = 1; // m_Hdr.dime.dim[4] = 1; unsigned int numberOfDimensions = this->m_Hdr.dime.dim[0]; + if (numberOfDimensions == 0) + { + // If the dimension is 0, it may still contain valid dimension + // values. Let's try to compute the number of dimensions from + // other values. We will output a warning, but we may not want + // to throw an exception already. + const unsigned int maxNumberOfDimensions = 4; + for (unsigned int idx = 1; + (idx <= maxNumberOfDimensions) && (this->m_Hdr.dime.dim[idx]); + idx++) + { + if (this->m_Hdr.dime.dim[idx] > 0) + { + numberOfDimensions++; + } + } + } if (numberOfDimensions == 0) { @@ -843,6 +871,7 @@ void AnalyzeImageIO::ReadImageInformation() } this->SetNumberOfDimensions(numberOfDimensions); + this->SetNumberOfComponents(1); // default switch( this->m_Hdr.dime.datatype ) { case ANALYZE_DT_BINARY: @@ -880,6 +909,9 @@ void AnalyzeImageIO::ReadImageInformation() case ANALYZE_DT_RGB: // DEBUG -- Assuming this is a triple, not quad //image.setDataType( uiig::DATA_RGBQUAD ); + m_ComponentType = UCHAR; + m_PixelType = RGB; + this->SetNumberOfComponents(3); break; default: break; @@ -897,223 +929,223 @@ void AnalyzeImageIO::ReadImageInformation() //Get Dictionary Information //Insert Orientation. + // char temp[348]; + //Important hk fields. + itk::MetaDataDictionary &thisDic=this->GetMetaDataDictionary(); + std::string classname(this->GetNameOfClass()); + itk::EncapsulateMetaData<std::string>(thisDic,ITK_InputFilterName, classname); + + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_ImageFileBaseName,std::string(this->m_Hdr.hk.db_name,18)); + + //Important dime fields + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_VoxelUnits,std::string(this->m_Hdr.dime.vox_units,4)); + itk::EncapsulateMetaData<std::string> + (thisDic,ANALYZE_CALIBRATIONUNITS, + std::string(this->m_Hdr.dime.cal_units,8)); + itk::EncapsulateMetaData<short int> + (thisDic,ITK_OnDiskBitPerPixel,this->m_Hdr.dime.bitpix); + itk::EncapsulateMetaData<float> + (thisDic,SPM_ROI_SCALE,this->m_Hdr.dime.roi_scale); + itk::EncapsulateMetaData<float>(thisDic,ANALYZE_CAL_MAX, + this->m_Hdr.dime.cal_max); + itk::EncapsulateMetaData<float>(thisDic,ANALYZE_CAL_MIN, + this->m_Hdr.dime.cal_min); + itk::EncapsulateMetaData<int>(thisDic,ANALYZE_GLMAX,this->m_Hdr.dime.glmax); + itk::EncapsulateMetaData<int>(thisDic,ANALYZE_GLMIN,this->m_Hdr.dime.glmin); + + for (dim=this->GetNumberOfDimensions(); dim>0; dim--) { - // char temp[348]; - //Important hk fields. - itk::MetaDataDictionary &thisDic=this->GetMetaDataDictionary(); - std::string classname(this->GetNameOfClass()); - itk::EncapsulateMetaData<std::string>(thisDic,ITK_InputFilterName, classname); - - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_ImageFileBaseName,std::string(this->m_Hdr.hk.db_name,18)); - - //Important dime fields - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_VoxelUnits,std::string(this->m_Hdr.dime.vox_units,4)); - itk::EncapsulateMetaData<std::string> - (thisDic,ANALYZE_CALIBRATIONUNITS, - std::string(this->m_Hdr.dime.cal_units,8)); - itk::EncapsulateMetaData<short int> - (thisDic,ITK_OnDiskBitPerPixel,this->m_Hdr.dime.bitpix); - itk::EncapsulateMetaData<float> - (thisDic,SPM_ROI_SCALE,this->m_Hdr.dime.roi_scale); - itk::EncapsulateMetaData<float>(thisDic,ANALYZE_CAL_MAX, - this->m_Hdr.dime.cal_max); - itk::EncapsulateMetaData<float>(thisDic,ANALYZE_CAL_MIN, - this->m_Hdr.dime.cal_min); - itk::EncapsulateMetaData<int>(thisDic,ANALYZE_GLMAX,this->m_Hdr.dime.glmax); - itk::EncapsulateMetaData<int>(thisDic,ANALYZE_GLMIN,this->m_Hdr.dime.glmin); - - for (dim=this->GetNumberOfDimensions(); dim>0; dim--) + if (m_Hdr.dime.dim[dim] != 1) { - if (m_Hdr.dime.dim[dim] != 1) - { - break; - } + break; } - itk::EncapsulateMetaData<int>(thisDic,ITK_NumberOfDimensions,dim); + } + itk::EncapsulateMetaData<int>(thisDic,ITK_NumberOfDimensions,dim); - switch( this->m_Hdr.dime.datatype) - { - case ANALYZE_DT_BINARY: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName,std::string(typeid(char).name())); - break; - case ANALYZE_DT_UNSIGNED_CHAR: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(unsigned char).name())); - break; - case ANALYZE_DT_SIGNED_SHORT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(short).name())); - break; - case SPMANALYZE_DT_UNSIGNED_SHORT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(unsigned short).name())); - break; - case ANALYZE_DT_SIGNED_INT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(long).name())); - break; - case SPMANALYZE_DT_UNSIGNED_INT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(unsigned long).name())); - break; - case ANALYZE_DT_FLOAT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(float).name())); - break; - case ANALYZE_DT_DOUBLE: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(double).name())); - break; - case ANALYZE_DT_RGB: - // DEBUG -- Assuming this is a triple, not quad - //image.setDataType( uiig::DATA_RGBQUAD ); - break; - default: - break; - } + switch(this->m_Hdr.dime.datatype) + { + case ANALYZE_DT_BINARY: + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OnDiskStorageTypeName,std::string(typeid(char).name())); + break; + case ANALYZE_DT_UNSIGNED_CHAR: + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OnDiskStorageTypeName, + std::string(typeid(unsigned char).name())); + break; + case ANALYZE_DT_SIGNED_SHORT: + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OnDiskStorageTypeName, + std::string(typeid(short).name())); + break; + case SPMANALYZE_DT_UNSIGNED_SHORT: + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OnDiskStorageTypeName, + std::string(typeid(unsigned short).name())); + break; + case ANALYZE_DT_SIGNED_INT: + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OnDiskStorageTypeName, + std::string(typeid(long).name())); + break; + case SPMANALYZE_DT_UNSIGNED_INT: + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OnDiskStorageTypeName, + std::string(typeid(unsigned long).name())); + break; + case ANALYZE_DT_FLOAT: + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OnDiskStorageTypeName, + std::string(typeid(float).name())); + break; + case ANALYZE_DT_DOUBLE: + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OnDiskStorageTypeName, + std::string(typeid(double).name())); + break; + case ANALYZE_DT_RGB: + // DEBUG -- Assuming this is a triple, not quad + //image.setDataType( uiig::DATA_RGBQUAD ); + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OnDiskStorageTypeName, + std::string(typeid(itk::RGBPixel<unsigned char>).name())); + break; + default: + break; + } - //Important hist fields - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_FileNotes, - std::string(this->m_Hdr.hist.descrip,80)); - itk::EncapsulateMetaData<std::string> - (thisDic,ANALYZE_AUX_FILE_NAME, - std::string(this->m_Hdr.hist.aux_file,24)); + //Important hist fields + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_FileNotes, + std::string(this->m_Hdr.hist.descrip,80)); + itk::EncapsulateMetaData<std::string> + (thisDic,ANALYZE_AUX_FILE_NAME, + std::string(this->m_Hdr.hist.aux_file,24)); + + itk::AnalyzeImageIO::ValidAnalyzeOrientationFlags temporient + = static_cast<itk::AnalyzeImageIO::ValidAnalyzeOrientationFlags> + (this->m_Hdr.hist.orient); + itk::SpatialOrientation::ValidCoordinateOrientationFlags coord_orient; + switch (temporient) + { + case itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RPI_TRANSVERSE: + coord_orient = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RPI; + break; + case itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_PIR_SAGITTAL: + coord_orient = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_PIR; + break; + case itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RIP_CORONAL: + coord_orient = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP; + break; + default: + coord_orient = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP; + itkWarningMacro( "Unknown orientation in file " << m_FileName ); + } + // An error was encountered in code that depends upon the + // valid coord_orientation. + typedef SpatialOrientationAdapter OrientAdapterType; + SpatialOrientationAdapter::DirectionType dir = + OrientAdapterType().ToDirectionCosines(coord_orient); + unsigned dims = this->GetNumberOfDimensions(); + // always have at least 3 dimensions for the purposes of + // setting directions +#define itkAnalzyeImageIO_MINDIMS_IS_THREE ( (dims < 3) ? 3 : dims) + std::vector<double> dirx( itkAnalzyeImageIO_MINDIMS_IS_THREE,0), + diry( itkAnalzyeImageIO_MINDIMS_IS_THREE,0), + dirz( itkAnalzyeImageIO_MINDIMS_IS_THREE,0); +#undef itkAnalzyeImageIO_MINDIMS_IS_THREE + dirx[0] = dir[0][0]; + dirx[1] = dir[1][0]; + dirx[2] = dir[2][0]; + diry[0] = dir[0][1]; + diry[1] = dir[1][1]; + diry[2] = dir[2][1]; + dirz[0] = dir[0][2]; + dirz[1] = dir[1][2]; + dirz[2] = dir[2][2]; + for(unsigned i = 3; i < dims; i++) + { + dirx[i] = diry[i] = dirz[i] = 0; + } + this->SetDirection(0,dirx); + this->SetDirection(1,diry); + if(numberOfDimensions > 2) + { + this->SetDirection(2,dirz); + } + else + { + // + // don't allow degenerate direction cosines + // This is a pure punt; it will prevent the exception being + // thrown, but doesn't do the right thing at all -- replacing e.g + // [0, 0, -1] with [0, 1] doesn't make any real sense. + // On the other hand, programs that depend on 2D Direction Cosines + // are pretty much guaranteed to be disappointed if they expect anything + // meaningful in the direction cosines anyway. + if(dirx[0] == 0.0 && dirx[1] == 0.0) { - itk::AnalyzeImageIO::ValidAnalyzeOrientationFlags temporient - = static_cast<itk::AnalyzeImageIO::ValidAnalyzeOrientationFlags> - (this->m_Hdr.hist.orient); - itk::SpatialOrientation::ValidCoordinateOrientationFlags coord_orient; - switch (temporient) + if(diry[0] != 0) { - case itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RPI_TRANSVERSE: - coord_orient = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RPI; - break; - case itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_PIR_SAGITTAL: - coord_orient = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_PIR; - break; - case itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RIP_CORONAL: - coord_orient = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP; - break; - default: - coord_orient = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP; - itkWarningMacro( "Unknown orientation in file " << m_FileName ); + dirx[1] = 1.0; } - // An error was encountered in code that depends upon the - // valid coord_orientation. - typedef SpatialOrientationAdapter OrientAdapterType; - SpatialOrientationAdapter::DirectionType dir = - OrientAdapterType().ToDirectionCosines(coord_orient); - unsigned dims = this->GetNumberOfDimensions(); - // always have at least 3 dimensions for the purposes of - // setting directions -#define itkAnalzyeImageIO_MINDIMS_IS_THREE ( (dims < 3) ? 3 : dims) - std::vector<double> dirx( itkAnalzyeImageIO_MINDIMS_IS_THREE,0), - diry( itkAnalzyeImageIO_MINDIMS_IS_THREE,0), - dirz( itkAnalzyeImageIO_MINDIMS_IS_THREE,0); -#undef itkAnalzyeImageIO_MINDIMS_IS_THREE - - dirx[0] = dir[0][0]; - dirx[1] = dir[1][0]; - dirx[2] = dir[2][0]; - diry[0] = dir[0][1]; - diry[1] = dir[1][1]; - diry[2] = dir[2][1]; - dirz[0] = dir[0][2]; - dirz[1] = dir[1][2]; - dirz[2] = dir[2][2]; - for(unsigned i = 3; i < dims; i++) + else { - dirx[i] = diry[i] = dirz[i] = 0; + dirx[0] = 1.0; } - this->SetDirection(0,dirx); - this->SetDirection(1,diry); - if(numberOfDimensions > 2) + } + else if(diry[0] == 0.0 && diry[1] == 0.0) + { + if(dirx[0] != 0) { - this->SetDirection(2,dirz); + diry[1] = 1.0; } else { - // - // don't allow degenerate direction cosines - // This is a pure punt; it will prevent the exception being - // thrown, but doesn't do the right thing at all -- replacing e.g - // [0, 0, -1] with [0, 1] doesn't make any real sense. - // On the other hand, programs that depend on 2D Direction Cosines - // are pretty much guaranteed to be disappointed if they expect anything - // meaningful in the direction cosines anyway. - if(dirx[0] == 0.0 && dirx[1] == 0.0) - { - if(diry[0] != 0) - { - dirx[1] = 1.0; - } - else - { - dirx[0] = 1.0; - } - } - else if(diry[0] == 0.0 && diry[1] == 0.0) - { - if(dirx[0] != 0) - { - diry[1] = 1.0; - } - else - { - diry[0] = 1.0; - } - } + diry[0] = 1.0; } -#if defined(ITKIO_DEPRECATED_METADATA_ORIENTATION) - itk::EncapsulateMetaData - <itk::SpatialOrientation::ValidCoordinateOrientationFlags> - (thisDic,ITK_CoordinateOrientation, coord_orient); -#endif } - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_FileOriginator, - std::string(this->m_Hdr.hist.originator,10)); - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OriginationDate, - std::string(this->m_Hdr.hist.generated,10)); - itk::EncapsulateMetaData<std::string> - (thisDic,ANALYZE_ScanNumber, - std::string(this->m_Hdr.hist.scannum,10)); - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_PatientID, - std::string(this->m_Hdr.hist.patient_id,10)); - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_ExperimentDate, - std::string(this->m_Hdr.hist.exp_date,10)); - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_ExperimentTime, - std::string(this->m_Hdr.hist.exp_date,10)); - - itk::EncapsulateMetaData<int> - (thisDic,ANALYZE_O_MAX, - this->m_Hdr.hist.omax); - itk::EncapsulateMetaData<int> - (thisDic,ANALYZE_O_MIN, - this->m_Hdr.hist.omin); - itk::EncapsulateMetaData<int> - (thisDic,ANALYZE_S_MAX, - this->m_Hdr.hist.smax); - itk::EncapsulateMetaData<int> - (thisDic,ANALYZE_S_MIN, - this->m_Hdr.hist.smin); } +#if defined(ITKIO_DEPRECATED_METADATA_ORIENTATION) + itk::EncapsulateMetaData + <itk::SpatialOrientation::ValidCoordinateOrientationFlags> + (thisDic,ITK_CoordinateOrientation, coord_orient); +#endif + + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_FileOriginator, + std::string(this->m_Hdr.hist.originator,10)); + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_OriginationDate, + std::string(this->m_Hdr.hist.generated,10)); + itk::EncapsulateMetaData<std::string> + (thisDic,ANALYZE_ScanNumber, + std::string(this->m_Hdr.hist.scannum,10)); + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_PatientID, + std::string(this->m_Hdr.hist.patient_id,10)); + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_ExperimentDate, + std::string(this->m_Hdr.hist.exp_date,10)); + itk::EncapsulateMetaData<std::string> + (thisDic,ITK_ExperimentTime, + std::string(this->m_Hdr.hist.exp_date,10)); + + itk::EncapsulateMetaData<int> + (thisDic,ANALYZE_O_MAX, + this->m_Hdr.hist.omax); + itk::EncapsulateMetaData<int> + (thisDic,ANALYZE_O_MIN, + this->m_Hdr.hist.omin); + itk::EncapsulateMetaData<int> + (thisDic,ANALYZE_S_MAX, + this->m_Hdr.hist.smax); + itk::EncapsulateMetaData<int> + (thisDic,ANALYZE_S_MIN, + this->m_Hdr.hist.smin); return; } @@ -1125,10 +1157,21 @@ AnalyzeImageIO ::WriteImageInformation(void) { unsigned int dim; - if(this->GetNumberOfComponents() > 1) + if(this->GetPixelType() == RGB) { - itkExceptionMacro(<< "More than one component per pixel not supported"); + if(this->GetComponentType() != UCHAR) + { + itkExceptionMacro(<< "Only unsigned char RGB files supported"); + } + } + else + { + if(this->GetNumberOfComponents() > 1) + { + itkExceptionMacro(<< "More than one component per pixel not supported"); + } } + const std::string HeaderFileName = GetHeaderFileName( m_FileName ); std::ofstream local_OutputStream; local_OutputStream.open( HeaderFileName.c_str(), @@ -1137,255 +1180,178 @@ AnalyzeImageIO { itkExceptionMacro(<< "File cannot be written"); } - { - std::string temp; - //Important hk fields. - itk::MetaDataDictionary &thisDic=this->GetMetaDataDictionary(); - - switch( this->m_Hdr.dime.datatype) - { - case ANALYZE_DT_BINARY: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(char).name())); - break; - case ANALYZE_DT_UNSIGNED_CHAR: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(unsigned char).name())); - break; - case ANALYZE_DT_SIGNED_SHORT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(short).name())); - break; - case SPMANALYZE_DT_UNSIGNED_SHORT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(unsigned short).name())); - break; - case ANALYZE_DT_SIGNED_INT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(long).name())); - break; - case SPMANALYZE_DT_UNSIGNED_INT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(unsigned long).name())); - break; - case ANALYZE_DT_FLOAT: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(float).name())); - break; - case ANALYZE_DT_DOUBLE: - itk::EncapsulateMetaData<std::string> - (thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(double).name())); - break; - case ANALYZE_DT_RGB: - // DEBUG -- Assuming this is a triple, not quad - //image.setDataType( uiig::DATA_RGBQUAD ); - break; - default: - break; - } - - itk::ExposeMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,temp); - if (temp==std::string(typeid(char).name())) - { - strncpy(this->m_Hdr.hk.data_type,"BINARY",10); - } - else if (temp==std::string(typeid(unsigned char).name())) - { - strncpy(this->m_Hdr.hk.data_type,"CHAR",10); - } - else if (temp==std::string(typeid(short).name())) - { - strncpy(this->m_Hdr.hk.data_type,"SHORT",10); - } - else if (temp==std::string(typeid(unsigned short).name())) - { - strncpy(this->m_Hdr.hk.data_type,"USHORT",10); - } - else if (temp==std::string(typeid(long).name())) - { - strncpy(this->m_Hdr.hk.data_type,"INT",10); - } - else if (temp==std::string(typeid(unsigned long).name())) - { - strncpy(this->m_Hdr.hk.data_type,"UINT",10); - } - else if (temp==std::string(typeid(float).name())) - { - strncpy(this->m_Hdr.hk.data_type,"FLOAT",10); - } - else if (temp==std::string(typeid(double).name())) - { - strncpy(this->m_Hdr.hk.data_type,"DOUBLE",10); - } - else - { - strncpy(this->m_Hdr.hk.data_type,"UNKNOWN",10); - } + std::string temp; + // + // most likely NONE of this below does anything useful because + // the MetaDataDictionary is basically not set with any of these fields + // except by the image file reader. + //Important hk fields. + itk::MetaDataDictionary &thisDic=this->GetMetaDataDictionary(); - if(itk::ExposeMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,temp)) - { - strncpy(this->m_Hdr.hk.data_type,temp.c_str(),10); - } + if(itk::ExposeMetaData<std::string>(thisDic,ITK_ImageFileBaseName,temp)) + { + strncpy(this->m_Hdr.hk.db_name,temp.c_str(),18); + } + //Important dime fields + if(itk::ExposeMetaData<std::string>(thisDic,ITK_VoxelUnits,temp)) + { + strncpy(this->m_Hdr.dime.vox_units,temp.c_str(),4); + } - if(itk::ExposeMetaData<std::string>(thisDic,ITK_ImageFileBaseName,temp)) - { - strncpy(this->m_Hdr.hk.db_name,temp.c_str(),18); - } - //Important dime fields - if(itk::ExposeMetaData<std::string>(thisDic,ITK_VoxelUnits,temp)) - { - strncpy(this->m_Hdr.dime.vox_units,temp.c_str(),4); - } + if(itk::ExposeMetaData<std::string>(thisDic,ANALYZE_CALIBRATIONUNITS,temp)) + { + strncpy(this->m_Hdr.dime.cal_units,temp.c_str(),8); + } - if(itk::ExposeMetaData<std::string>(thisDic,ANALYZE_CALIBRATIONUNITS,temp)) - { - strncpy(this->m_Hdr.dime.cal_units,temp.c_str(),8); - } + itk::ExposeMetaData<short int> + (thisDic,ITK_OnDiskBitPerPixel, + this->m_Hdr.dime.bitpix); + itk::ExposeMetaData<float> + (thisDic,SPM_ROI_SCALE, + this->m_Hdr.dime.roi_scale); + itk::ExposeMetaData<float> + (thisDic,ANALYZE_CAL_MAX, + this->m_Hdr.dime.cal_max); + itk::ExposeMetaData<float> + (thisDic,ANALYZE_CAL_MIN, + this->m_Hdr.dime.cal_min); + itk::ExposeMetaData<int> + (thisDic,ANALYZE_GLMAX, + this->m_Hdr.dime.glmax); + itk::ExposeMetaData<int> + (thisDic,ANALYZE_GLMIN, + this->m_Hdr.dime.glmin); + //Important hist fields + if(itk::ExposeMetaData<std::string>(thisDic,ITK_FileNotes,temp)) + { + strncpy(this->m_Hdr.hist.descrip,temp.c_str(),80); + } - itk::ExposeMetaData<short int> - (thisDic,ITK_OnDiskBitPerPixel, - this->m_Hdr.dime.bitpix); - itk::ExposeMetaData<float> - (thisDic,SPM_ROI_SCALE, - this->m_Hdr.dime.roi_scale); - itk::ExposeMetaData<float> - (thisDic,ANALYZE_CAL_MAX, - this->m_Hdr.dime.cal_max); - itk::ExposeMetaData<float> - (thisDic,ANALYZE_CAL_MIN, - this->m_Hdr.dime.cal_min); - itk::ExposeMetaData<int> - (thisDic,ANALYZE_GLMAX, - this->m_Hdr.dime.glmax); - itk::ExposeMetaData<int> - (thisDic,ANALYZE_GLMIN, - this->m_Hdr.dime.glmin); - //Important hist fields - if(itk::ExposeMetaData<std::string>(thisDic,ITK_FileNotes,temp)) - { - strncpy(this->m_Hdr.hist.descrip,temp.c_str(),80); - } + if(itk::ExposeMetaData<std::string>(thisDic,ANALYZE_AUX_FILE_NAME,temp)) + { + strncpy(this->m_Hdr.hist.aux_file,temp.c_str(),24); + } - if(itk::ExposeMetaData<std::string>(thisDic,ANALYZE_AUX_FILE_NAME,temp)) + itk::SpatialOrientation::ValidCoordinateOrientationFlags coord_orient = + itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_INVALID; +#if defined(ITKIO_DEPRECATED_METADATA_ORIENTATION) + if ( !itk::ExposeMetaData + <itk::SpatialOrientation::ValidCoordinateOrientationFlags> + (thisDic,ITK_CoordinateOrientation, coord_orient) ) + { +#endif + typedef itk::SpatialOrientationAdapter::DirectionType DirectionType; + DirectionType dir; + unsigned int dims = this->GetNumberOfDimensions(); + std::vector<double> dirx = this->GetDirection(0); + std::vector<double> diry = this->GetDirection(1); + std::vector<double> dirz; + if(dims > 2) { - strncpy(this->m_Hdr.hist.aux_file,temp.c_str(),24); + dirz = this->GetDirection(2); } - - itk::SpatialOrientation::ValidCoordinateOrientationFlags coord_orient = - itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_INVALID; -#if defined(ITKIO_DEPRECATED_METADATA_ORIENTATION) - if ( !itk::ExposeMetaData - <itk::SpatialOrientation::ValidCoordinateOrientationFlags> - (thisDic,ITK_CoordinateOrientation, coord_orient) ) + else { -#endif - typedef itk::SpatialOrientationAdapter::DirectionType DirectionType; - DirectionType dir; + for(unsigned i = 0; i < 3; i++) { - unsigned int dims = this->GetNumberOfDimensions(); - std::vector<double> dirx = this->GetDirection(0), - diry = this->GetDirection(1); - std::vector<double> dirz; - if(dims > 2) - { - dirz = this->GetDirection(2); - } - else - { - for(unsigned i = 0; i < 3; i++) - { - dirz.push_back(0.0); - } - } - unsigned int i; - for(i = 0; i < dims; i++) - { - dir[i][0] = dirx[i]; - dir[i][1] = diry[i]; - dir[i][2] = dirz[i]; - } - for(; i < 3; i++) - { - dir[i][0] = - dir[i][1] = - dir[i][2] = 0; - } + dirz.push_back(0.0); } - coord_orient = - itk::SpatialOrientationAdapter().FromDirectionCosines(dir); -#if defined(ITKIO_DEPRECATED_METADATA_ORIENTATION) } -#endif - switch (coord_orient) + unsigned int i; + for(i = 0; i < dims; i++) { - case itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RPI: - this->m_Hdr.hist.orient = - itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RPI_TRANSVERSE; - break; - case itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_PIR: - this->m_Hdr.hist.orient = - itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_PIR_SAGITTAL; - break; - case itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP: - this->m_Hdr.hist.orient = - itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RIP_CORONAL; - break; - default: - this->m_Hdr.hist.orient = - itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RIP_CORONAL; - itkWarningMacro( "ERROR: Analyze 7.5 File Format" - " Only Allows RPI, PIR, and RIP Orientation " ); + dir[i][0] = dirx[i]; + dir[i][1] = diry[i]; + dir[i][2] = dirz[i]; } - - if(itk::ExposeMetaData<std::string>(thisDic,ITK_FileOriginator,temp)) + for(; i < 3; i++) { - strncpy(this->m_Hdr.hist.originator,temp.c_str(),10); + dir[i][0] = + dir[i][1] = + dir[i][2] = 0; } + coord_orient = + itk::SpatialOrientationAdapter().FromDirectionCosines(dir); +#if defined(ITKIO_DEPRECATED_METADATA_ORIENTATION) + } +#endif + switch (coord_orient) + { + case itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RPI: + this->m_Hdr.hist.orient = + itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RPI_TRANSVERSE; + break; + case itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_PIR: + this->m_Hdr.hist.orient = + itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_PIR_SAGITTAL; + break; + case itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP: + this->m_Hdr.hist.orient = + itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RIP_CORONAL; + break; + default: + this->m_Hdr.hist.orient = + itk::AnalyzeImageIO::ITK_ANALYZE_ORIENTATION_RIP_CORONAL; + itkWarningMacro( "ERROR: Analyze 7.5 File Format" + " Only Allows RPI, PIR, and RIP Orientation " ); + } - if(itk::ExposeMetaData<std::string>(thisDic,ITK_OriginationDate,temp)) - { - strncpy(this->m_Hdr.hist.generated,temp.c_str(),10); - } + if(itk::ExposeMetaData<std::string>(thisDic,ITK_FileOriginator,temp)) + { + strncpy(this->m_Hdr.hist.originator,temp.c_str(),10); + } - if(itk::ExposeMetaData<std::string>(thisDic,ANALYZE_ScanNumber,temp)) - { - strncpy(this->m_Hdr.hist.scannum,temp.c_str(),10); - } + if(itk::ExposeMetaData<std::string>(thisDic,ITK_OriginationDate,temp)) + { + strncpy(this->m_Hdr.hist.generated,temp.c_str(),10); + } - if(itk::ExposeMetaData<std::string>(thisDic,ITK_PatientID,temp)) - { - strncpy(this->m_Hdr.hist.patient_id,temp.c_str(),10); - } + if(itk::ExposeMetaData<std::string>(thisDic,ANALYZE_ScanNumber,temp)) + { + strncpy(this->m_Hdr.hist.scannum,temp.c_str(),10); + } - if(itk::ExposeMetaData<std::string>(thisDic,ITK_ExperimentDate,temp)) - { - strncpy(this->m_Hdr.hist.exp_date,temp.c_str(),10); - } + if(itk::ExposeMetaData<std::string>(thisDic,ITK_PatientID,temp)) + { + strncpy(this->m_Hdr.hist.patient_id,temp.c_str(),10); + } - if(itk::ExposeMetaData<std::string>(thisDic,ITK_ExperimentTime,temp)) - { - strncpy(this->m_Hdr.hist.exp_date,temp.c_str(),10); - } + if(itk::ExposeMetaData<std::string>(thisDic,ITK_ExperimentDate,temp)) + { + strncpy(this->m_Hdr.hist.exp_date,temp.c_str(),10); + } - itk::ExposeMetaData<int>(thisDic,ANALYZE_O_MAX,this->m_Hdr.hist.omax); - itk::ExposeMetaData<int>(thisDic,ANALYZE_O_MIN,this->m_Hdr.hist.omin); - itk::ExposeMetaData<int>(thisDic,ANALYZE_S_MAX,this->m_Hdr.hist.smax); - itk::ExposeMetaData<int>(thisDic,ANALYZE_S_MIN,this->m_Hdr.hist.smin); + if(itk::ExposeMetaData<std::string>(thisDic,ITK_ExperimentTime,temp)) + { + strncpy(this->m_Hdr.hist.exp_date,temp.c_str(),10); } + itk::ExposeMetaData<int>(thisDic,ANALYZE_O_MAX,this->m_Hdr.hist.omax); + itk::ExposeMetaData<int>(thisDic,ANALYZE_O_MIN,this->m_Hdr.hist.omin); + itk::ExposeMetaData<int>(thisDic,ANALYZE_S_MAX,this->m_Hdr.hist.smax); + itk::ExposeMetaData<int>(thisDic,ANALYZE_S_MIN,this->m_Hdr.hist.smin); + + // Check for image dimensions to be smaller enough to fit in + // a short int. First generate the number that is the maximum allowable. + typedef itk::Size<3>::SizeValueType SizeValueType; + const SizeValueType maximumNumberOfPixelsAllowedInOneDimension = + itk::NumericTraits<unsigned short>::max() - 1; + for( dim=0; dim< this->GetNumberOfDimensions(); dim++ ) { + const SizeValueType numberOfPixelsAlongThisDimension = m_Dimensions[ dim ]; + + if( numberOfPixelsAlongThisDimension >= maximumNumberOfPixelsAllowedInOneDimension ) + { + itkExceptionMacro("Number of pixels along dimension " << dim + << " is " << numberOfPixelsAlongThisDimension << + " which exceeds maximum allowable dimension of " << + maximumNumberOfPixelsAllowedInOneDimension ); + } + //NOTE: Analyze dim[0] are the number of dims, and dim[1..7] are // the actual dims. - this->m_Hdr.dime.dim[dim+1] = m_Dimensions[ dim ]; + this->m_Hdr.dime.dim[dim+1] = numberOfPixelsAlongThisDimension; } //DEBUG--HACK It seems that analyze 7.5 requires 4 dimensions. @@ -1425,6 +1391,10 @@ AnalyzeImageIO ::GetDirection( unsigned int k ) const { std::vector<double> correctedDirection = this->ImageIOBase::GetDirection(k); + if( this->m_Dimensions.size() == correctedDirection.size() ) + { + return correctedDirection; + } // Apply corrections for 2D cases std::vector<double> direction0 = this->ImageIOBase::GetDirection(0); @@ -1548,73 +1518,15 @@ AnalyzeImageIO throw exception; } -#ifdef __OMIT_UNTIL_RGB_IS_NEEEDED - if ( image.getDataType() == uiig::DATA_RGBTRIPLE ) + if(::gzwrite(file_p,p, + static_cast< unsigned >(this->GetImageSizeInBytes())) == -1) { - // Analyze RGB images are stored in channels, where all the red - // components are stored first, followed by the green and blue components - // for each plane of the volume. This is stored in an image of RGBTRIPLE - // data structures, which are in memory stored as (red,green,blue). The - // triples need to be converted to channels for each plane when writing - // out the image. - - // NOTE: Do NOT change this. The math here is necessary for CImageStrided to - // read files correctly - for( register unsigned int l=0; l<tempT; l++ ) - { - unsigned int volumeOffset = l*m_uiVolumeOffset; - for( register unsigned int k=0; k<tempZ; k++ ) - { - unsigned int planeVolOffset = k*m_uiPlaneOffset + volumeOffset; - - // Reading the red channel - { - for( register unsigned int j=0; j<tempY; j++ ) - { - unsigned int rowOffset = j*m_uiRowOffset; - for ( register unsigned int i=0; i<tempX; i++ ) - { - ::gzwrite( file_p, - &(static_cast<unsigned char *>(data)[(m_uiInitialOffset+planeVolOffset+rowOffset)*m_dataSize]) + (i*3), sizeof(unsigned char) ); - } - } - } - - // Reading the green channel - { - for( register unsigned int j=0; j<tempY; j++ ) - { - unsigned int rowOffset = j*m_uiRowOffset; - for ( register unsigned int i=0; i<tempX; i++ ) - { - //NOTE: unsigned char * is used to do byte wise offsets The offsets are computed - //in bytes - ::gzwrite( file_p, &(static_cast<unsigned char *>(data)[(m_uiInitialOffset+planeVolOffset+rowOffset)*m_dataSize]) + (i*3) + 1, sizeof(unsigned char) ); - } - } - } - - // Reading the blue channel - { - for( register unsigned int j=0; j<tempY; j++ ) - { - unsigned int rowOffset = j*m_uiRowOffset; - for ( register unsigned int i=0; i<tempX; i++ ) - { - //NOTE: unsigned char * is used to do byte wise offsets The offsets are computed - //in bytes - ::gzwrite( file_p, &(static_cast<unsigned char *>(data)[(m_uiInitialOffset+planeVolOffset+rowOffset)*m_dataSize]) + (i*3) + 2, sizeof(unsigned char) ); - } - } - } - - } - } - } - else -#endif - { - ::gzwrite( file_p,p, static_cast< unsigned >( this->GetImageSizeInBytes() ) ); + ExceptionObject exception(__FILE__, __LINE__); + std::string ErrorMessage="Error, Can not write compressed image file for "; + ErrorMessage += m_FileName; + exception.SetDescription(ErrorMessage.c_str()); + exception.SetLocation(ITK_LOCATION); + throw exception; } ::gzclose( file_p ); //RemoveFile FileNameToRead.img so that it does not get confused with @@ -1664,4 +1576,5 @@ AnalyzeImageIO itksys::SystemTools::RemoveFile(unusedbaseimgname.c_str()); } } + } // end namespace itk diff --git a/Utilities/ITK/Code/IO/itkBMPImageIO.cxx b/Utilities/ITK/Code/IO/itkBMPImageIO.cxx index fee7d5b483..2877c1ad9d 100644 --- a/Utilities/ITK/Code/IO/itkBMPImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkBMPImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBMPImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-10-03 16:09:47 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-05-26 23:45:03 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -877,10 +877,17 @@ BMPImageIO // The specification calls for a signed integer, but // here we force it to be an unsigned integer to avoid // dealing with directions in a subterraneous way. +#ifdef ITK_USE_PORTABLE_ROUND + const unsigned int horizontalResolution = + static_cast<unsigned int>( Math::Round( 1000.0 / m_Spacing[0] ) ); + const unsigned int verticalResolution = + static_cast<unsigned int>( Math::Round( 1000.0 / m_Spacing[1] ) ); +#else const unsigned int horizontalResolution = static_cast<unsigned int>( vnl_math_rnd( 1000.0 / m_Spacing[0] ) ); const unsigned int verticalResolution = static_cast<unsigned int>( vnl_math_rnd( 1000.0 / m_Spacing[1] ) ); +#endif this->Write32BitsInteger( horizontalResolution ); this->Write32BitsInteger( verticalResolution ); diff --git a/Utilities/ITK/Code/IO/itkBrains2HeaderBase.cxx b/Utilities/ITK/Code/IO/itkBrains2HeaderBase.cxx index 58f889942e..264a888c08 100644 --- a/Utilities/ITK/Code/IO/itkBrains2HeaderBase.cxx +++ b/Utilities/ITK/Code/IO/itkBrains2HeaderBase.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBrains2HeaderBase.cxx,v $ Language: C++ - Date: $Date: 2008-05-26 00:35:16 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-05 10:56:47 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,7 +21,7 @@ #include "itkBrains2HeaderBase.h" #include "itkBrains2HeaderFactory.h" #include <iostream> -#include <cstdlib> +#include <stdlib.h> namespace itk { Brains2HeaderBase::Brains2HeaderBase() diff --git a/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.h b/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.h index 6871a32093..714a4a4ddd 100644 --- a/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.h +++ b/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDICOMSeriesFileNames.h,v $ Language: C++ - Date: $Date: 2007-03-29 18:39:27 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-04-25 12:25:41 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -97,7 +97,7 @@ public: /** The sorting order can be ascending or descending. The default * sort order is ascending. */ itkSetMacro(Ascending, bool); - itkGetMacro(Ascending, bool); + itkGetConstMacro(Ascending, bool); itkBooleanMacro(Ascending); /** Returns a vector containing the UIDs for each series in the diff --git a/Utilities/ITK/Code/IO/itkGDCMImageIO.cxx b/Utilities/ITK/Code/IO/itkGDCMImageIO.cxx index dfc3cb5ee8..8ac89de051 100644 --- a/Utilities/ITK/Code/IO/itkGDCMImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkGDCMImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGDCMImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-02-19 01:02:39 $ - Version: $Revision: 1.149 $ + Date: $Date: 2009-04-29 22:31:37 $ + Version: $Revision: 1.159 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,6 +42,8 @@ #include "gdcmDictSet.h" // access to dictionary #else #include "gdcmImageHelper.h" +#include "gdcmDataSetHelper.h" +#include "gdcmStringFilter.h" #include "gdcmImageApplyLookupTable.h" #include "gdcmImageChangePlanarConfiguration.h" #include "gdcmUnpacker12Bits.h" @@ -70,8 +72,27 @@ public: }; // Initialize static members -bool GDCMImageIO::m_LoadSequencesDefault = false; -bool GDCMImageIO::m_LoadPrivateTagsDefault = false; +/* + * m_LoadPrivateTagsDefault: + * When this flag is set to false, GDCM will try to use the value stored in each private Group Length attribute value. + * This is a modest optimization feature that can be found in some ACR-NEMA file and/or DICOM pre-2008 file. + * Because it is required by the standard that DICOM file reader can read file where Group Length attribute value + * would be invalid, turning this flag to off, on the one hand might lead to some speed improvement, but on the + * other hand will make your DICOM implementation non-standard. + * Technically Group Length value could be incorrect and GDCM might even skipped over some public element and not + * just the desired current group of attributes. Do not turn this option to false unless you understand the + * consequences. + * + * m_LoadSequencesDefault: + * Following the same idea (modest speed improvement), one can use a feature from DICOM and use the Value Length + * of a Sequence attribute to 'seek' over a large number of nested attributes. + * Again this feature can lead to some modest speed improvement, but seek'ing over public sequence is not + * a good idea. For instance you could be reading some new Enhanced MR Image Storage, where the Pixel Spacing + * is stored within a Sequence attribute, therefore Pixel Spacing would not be correct after a call to + * ExecuteInformation. + */ +bool GDCMImageIO::m_LoadSequencesDefault = true; +bool GDCMImageIO::m_LoadPrivateTagsDefault = true; #if GDCM_MAJOR_VERSION < 2 @@ -580,7 +601,10 @@ void GDCMImageIO::Read(void* buffer) gdcm::File *header = this->m_DICOMHeader->m_Header; if( !header->IsReadable() ) { - itkExceptionMacro( "Cannot read the file"); + itkExceptionMacro(<< "Could not read file: " + << m_FileName << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } gdcm::FileHelper gfile(header); @@ -745,7 +769,10 @@ void GDCMImageIO::InternalReadImageInformation(std::ifstream& file) //read header if ( ! this->OpenGDCMFileForReading(file, m_FileName.c_str()) ) { - itkExceptionMacro(<< "Cannot read requested file"); + itkExceptionMacro(<< "Could not read file: " + << m_FileName << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } gdcm::File *header = new gdcm::File; @@ -758,11 +785,17 @@ void GDCMImageIO::InternalReadImageInformation(std::ifstream& file) bool headerLoaded = header->Load(); if ( !headerLoaded ) { - itkExceptionMacro(<< "Cannot read requested file"); + itkExceptionMacro(<< "Could not load header from file: " + << m_FileName << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } if( !header->IsReadable() ) { - itkExceptionMacro(<< "Cannot read requested file"); + itkExceptionMacro(<< "Could not read header from file: " + << m_FileName << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } // We don't need to positionate the Endian related stuff (by using @@ -1000,6 +1033,18 @@ void GDCMImageIO::InternalReadImageInformation(std::ifstream& file) } #else + +// TODO: this function was not part of gdcm::Tag API as of gdcm 2.0.10: +std::string PrintAsPipeSeparatedString(const gdcm::Tag& tag) +{ + itksys_ios::ostringstream os; + os << std::hex << std::setw( 4 ) << std::setfill( '0' ) + << tag[0] << '|' << std::setw( 4 ) << std::setfill( '0' ) + << tag[1]; + std::string ret = os.str(); + return ret; +} + void GDCMImageIO::InternalReadImageInformation(std::ifstream& file) { //read header @@ -1019,7 +1064,8 @@ void GDCMImageIO::InternalReadImageInformation(std::ifstream& file) itkExceptionMacro(<< "Cannot read requested file"); } const gdcm::Image &image = reader.GetImage(); - //const gdcm::DataSet &ds = reader.GetFile().GetDataSet(); + const gdcm::File &f = reader.GetFile(); + const gdcm::DataSet &ds = f.GetDataSet(); const unsigned int *dims = image.GetDimensions(); const gdcm::PixelFormat &pixeltype = image.GetPixelFormat(); @@ -1128,6 +1174,83 @@ void GDCMImageIO::InternalReadImageInformation(std::ifstream& file) this->SetDirection(1, columnDirection); this->SetDirection(2, sliceDirection); + //Now copying the gdcm dictionary to the itk dictionary: + MetaDataDictionary & dico = this->GetMetaDataDictionary(); + + gdcm::StringFilter sf; + sf.SetFile( f ); + gdcm::DataSet::ConstIterator it = ds.Begin(); + + // Copy of the header->content + for(; it != ds.End(); ++it) + { + const gdcm::DataElement &ref = *it; + const gdcm::Tag &tag = ref.GetTag(); + // Compute VR from the toplevel file, and the currently processed dataset: + gdcm::VR vr = gdcm::DataSetHelper::ComputeVR(f, ds, tag); + + // Process binary field and encode them as mime64: only when we do not know of any better + // representation. VR::US is binary, but user want ASCII representation. + if ( vr & (gdcm::VR::OB | gdcm::VR::OF | gdcm::VR::OW | gdcm::VR::SQ | gdcm::VR::UN) ) + { + // assert( vr & gdcm::VR::VRBINARY ); + /* + * Old bahavior was to skip SQ, Pixel Data element. I decided that it is not safe to mime64 + * VR::UN element. There used to be a bug in gdcm 1.2.0 and VR:UN element. + */ + if ( tag.IsPublic() && vr != gdcm::VR::SQ && tag != gdcm::Tag(0x7fe0,0x0010) /* && vr != gdcm::VR::UN*/ ) + { + const gdcm::ByteValue *bv = ref.GetByteValue(); + if( bv ) + { + // base64 streams have to be a multiple of 4 bytes long + int encodedLengthEstimate = 2 * bv->GetLength(); + encodedLengthEstimate = ((encodedLengthEstimate / 4) + 1) * 4; + + char *bin = new char[encodedLengthEstimate]; + unsigned int encodedLengthActual = static_cast<unsigned int>( + itksysBase64_Encode( + (const unsigned char *) bv->GetPointer(), + static_cast< unsigned long>( bv->GetLength() ), + (unsigned char *) bin, + static_cast< int >( 0 ) )); + std::string encodedValue(bin, encodedLengthActual); + EncapsulateMetaData<std::string>(dico, PrintAsPipeSeparatedString(tag), encodedValue); + delete []bin; + } + } + } + else /* if ( vr & gdcm::VR::VRASCII ) */ + { + // Only copying field from the public DICOM dictionary + if( tag.IsPublic() ) + { + EncapsulateMetaData<std::string>(dico, PrintAsPipeSeparatedString(tag), sf.ToString( tag ) ); + } + } + + } + + + // Now is a good time to fill in the class member: + char name[512]; + this->GetPatientName(name); + this->GetPatientID(name); + this->GetPatientSex(name); + this->GetPatientAge(name); + this->GetStudyID(name); + this->GetPatientDOB(name); + this->GetStudyDescription(name); + this->GetBodyPart(name); + this->GetNumberOfSeriesInStudy(name); + this->GetNumberOfStudyRelatedSeries(name); + this->GetStudyDate(name); + this->GetModality(name); + this->GetManufacturer(name); + this->GetInstitution(name); + this->GetModel(name); + this->GetScanOptions(name); + } #endif @@ -1473,8 +1596,20 @@ void GDCMImageIO::Write(const void* buffer) break; //Disabling INT and UINT for now... - //case ImageIOBase::INT: - //case ImageIOBase::UINT: + case ImageIOBase::INT: + bitsAllocated = "32"; // Bits Allocated + bitsStored = "32"; // Bits Stored + highBit = "31"; // High Bit + pixelRep = "1"; // Pixel Representation + break; + + case ImageIOBase::UINT: + bitsAllocated = "32"; // Bits Allocated + bitsStored = "32"; // Bits Stored + highBit = "31"; // High Bit + pixelRep = "0"; // Pixel Representation + break; + case ImageIOBase::FLOAT: case ImageIOBase::DOUBLE: // Disable that mode for now as we would need to compute on the fly the min/max of the image to @@ -1543,6 +1678,14 @@ void GDCMImageIO::Write(const void* buffer) { m_InternalComponentType = SHORT; } + else if( type == "32U") + { + m_InternalComponentType = UINT; + } + else if( type == "32S") + { + m_InternalComponentType = INT; + } else { itkExceptionMacro(<<"Unrecognized type:" << type << " in file " << m_FileName); @@ -1723,21 +1866,14 @@ void GDCMImageIO::Write(const void* buffer) if ( b /*tag != gdcm::Tag(0xffff,0xffff)*/ /*dictEntry*/) { const gdcm::DictEntry &dictEntry = pubdict.GetDictEntry(tag); - if (dictEntry.GetVR() != gdcm::VR::OB && dictEntry.GetVR() != gdcm::VR::OW) + gdcm::VR::VRType vrtype = dictEntry.GetVR(); + if ( dictEntry.GetVR() == gdcm::VR::SQ ) { - // TODO, should we keep: - // (0028,0106) US/SS 0 # 2, 1 SmallestImagePixelValue - // (0028,0107) US/SS 4095 # 2, 1 LargestImagePixelValue - if(!tag.IsGroupLength()) // Get rid of group length, they are not useful - { - gdcm::DataElement de( tag ); - de.SetByteValue( value.c_str(), value.size() ); - de.SetVR( dictEntry.GetVR() ); - header.Insert( de ); //value, tag.GetGroup(), tag.GetElement()); - } + // How did we reach here ? } - else + else if ( vrtype & (gdcm::VR::OB | gdcm::VR::OF | gdcm::VR::OW /*| gdcm::VR::SQ*/ | gdcm::VR::UN) ) { + // Custom VR::VRBINARY // convert value from Base64 uint8_t *bin = new uint8_t[value.size()]; unsigned int decodedLengthActual = static_cast<unsigned int>( @@ -1746,7 +1882,7 @@ void GDCMImageIO::Write(const void* buffer) static_cast<unsigned long>( 0 ), (unsigned char *) bin, static_cast<unsigned long>( value.size()))); - if(tag.GetGroup() != 0 || tag.GetElement() != 0) // ? + if( /*tag.GetGroup() != 0 ||*/ tag.GetElement() != 0) // ? { gdcm::DataElement de( tag ); de.SetByteValue( (char*)bin, decodedLengthActual ); @@ -1755,6 +1891,19 @@ void GDCMImageIO::Write(const void* buffer) } delete []bin; } + else // VRASCII + { + // TODO, should we keep: + // (0028,0106) US/SS 0 # 2, 1 SmallestImagePixelValue + // (0028,0107) US/SS 4095 # 2, 1 LargestImagePixelValue + if(!tag.IsGroupLength()) // Get rid of group length, they are not useful + { + gdcm::DataElement de( tag ); + de.SetByteValue( value.c_str(), value.size() ); + de.SetVR( dictEntry.GetVR() ); + header.Insert( de ); //value, tag.GetGroup(), tag.GetElement()); + } + } } else { @@ -1830,9 +1979,13 @@ void GDCMImageIO::Write(const void* buffer) case ImageIOBase::USHORT: pixeltype = gdcm::PixelFormat::UINT16; break; - //Disabling INT and UINT for now... - //case ImageIOBase::INT: - //case ImageIOBase::UINT: + case ImageIOBase::INT: + pixeltype = gdcm::PixelFormat::INT32; + break; + case ImageIOBase::UINT: + pixeltype = gdcm::PixelFormat::UINT32; + break; + //Disabling FLOAT and DOUBLE for now... //case ImageIOBase::FLOAT: //case ImageIOBase::DOUBLE: default: @@ -1859,18 +2012,12 @@ void GDCMImageIO::Write(const void* buffer) image.SetPixelFormat( pixeltype ); unsigned long len = image.GetBufferLength(); - gdcm::ByteValue *bv = new gdcm::ByteValue(); // (char*)data->GetScalarPointer(), len ); - bv->SetLength( len ); // allocate ! - size_t numberOfBytes = this->GetImageSizeInBytes(); assert( len == numberOfBytes ); - // only do a straight copy: - char *pointer = (char*)bv->GetPointer(); - memcpy(pointer, buffer, numberOfBytes); - gdcm::DataElement pixeldata( gdcm::Tag(0x7fe0,0x0010) ); - pixeldata.SetValue( *bv ); + // only do a straight copy: + pixeldata.SetByteValue( (char*)buffer, numberOfBytes ); image.SetDataElement( pixeldata ); if( !m_KeepOriginalUID ) @@ -2062,8 +2209,7 @@ bool GDCMImageIO::GetLabelFromTag( const std::string & tag, std::string & labelId ) { gdcm::Tag t; - t.ReadFromPipeSeparatedString( tag.c_str() ); - if( t.IsPublic() ) + if( t.ReadFromPipeSeparatedString( tag.c_str() ) && t.IsPublic() ) { const gdcm::Global &g = gdcm::Global::GetInstance(); const gdcm::Dicts &dicts = g.GetDicts(); diff --git a/Utilities/ITK/Code/IO/itkGDCMImageIO.h b/Utilities/ITK/Code/IO/itkGDCMImageIO.h index 629036e542..780d8fecc5 100644 --- a/Utilities/ITK/Code/IO/itkGDCMImageIO.h +++ b/Utilities/ITK/Code/IO/itkGDCMImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGDCMImageIO.h,v $ Language: C++ - Date: $Date: 2008-11-25 13:32:34 $ - Version: $Revision: 1.36 $ + Date: $Date: 2009-04-25 12:25:42 $ + Version: $Revision: 1.39 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -29,27 +29,37 @@ namespace itk /** \class GDCMImageIO * - * \brief ImageIO class for reading and writing DICOM V3.0 and ACR/NEMA (V1.0 & V2.0) images - * This class is only an adaptor to the gdcm library (currently gdcm 1.2.x is used): + * \brief ImageIO class for reading and writing DICOM V3.0 and ACR/NEMA 1&2 uncompressed images + * This class is only an adaptor to the gdcm library (currently gdcm 1.2.x is used by default): * + * GDCM 1.2 can be found at: * http://creatis-www.insa-lyon.fr/Public/Gdcm/ * * CREATIS INSA - Lyon 2003-2008 * http://www.creatis.insa-lyon.fr * + * Using the CMake variable: ITK_USE_SYSTEM_GDCM it is now possible to use a system installed + * GDCM 2.x release. GDCM 2.x is now being developped on sourceforge.net : + * + * http://gdcm.sourceforge.net + * + * Documentation: + * - http://apps.sourceforge.net/mediawiki/gdcm/index.php?title=ITK_USE_SYSTEM_GDCM + * - http://apps.sourceforge.net/mediawiki/gdcm/index.php?title=GDCM_Release_2.0 + * * \warning There are several restrictions to this current writer: - * - Basically you always need a DICOM as input to write a proper DICOM image file - * (As of 12/10/2004 this restriction is solved in GDCM CVS repository) * - Eventhough during the writing process you pass in a DICOM file as input * The output file may not contains ALL DICOM field from the input file. * In particular: * - The SeQuence DICOM field (SQ). - * - Fields from Private Dictionary with unresolved Name (= unknown at runtime) - * - As of 01/15 the binary fields are properly passed. + * - Fields from Private Dictionary * - Some very long (>0xfff) binary fields are not loaded (typically 0029|0010), * you need to explicitely set the maximum length of elements to load to be bigger * (see Get/SetMaxSizeLoadEntry) * - GDCMImageIO was not handling rescale slope/intercept properly. This is fixed as of 11/12/2007 + * - In DICOM some field are stored directly using there binary representation. When loaded into + * the MetaDataDict some fields are converted to ASCII (only VR: OB/OW/OF and UN are encoded as + * mime64). * * \ingroup IOFilters * @@ -98,8 +108,8 @@ public: /** Macro to access Rescale Slope and Rescale Intercept. Which are * needed to rescale properly image when needed. User then need to * Always check those value when access value from the DICOM header */ - itkGetMacro(RescaleSlope, double); - itkGetMacro(RescaleIntercept, double); + itkGetConstMacro(RescaleSlope, double); + itkGetConstMacro(RescaleIntercept, double); /** Macro to access the DICOM UID prefix. By default this is the ITK * root id. This default can be overriden if the exam is for example @@ -116,12 +126,15 @@ public: /** Preserve the original DICOM UID of the input files */ itkSetMacro(KeepOriginalUID,bool); - itkGetMacro(KeepOriginalUID,bool); + itkGetConstMacro(KeepOriginalUID,bool); itkBooleanMacro(KeepOriginalUID); /** Convenience methods to query patient information and scanner * information. These methods are here for compatibility with the - * DICOMImageIO2 class. */ + * DICOMImageIO2 class and as such should not be used in any new code. + * They rely on properly preallocated buffer, which is not a good practice. + * Instead user are encourage to use directly the GetValueFromTag function + */ void GetPatientName(char* name); void GetPatientID(char* id); void GetPatientSex(char* sex); @@ -168,7 +181,7 @@ public: * sequences are not needed. */ itkSetMacro(LoadSequences, bool); - itkGetMacro(LoadSequences, bool); + itkGetConstMacro(LoadSequences, bool); itkBooleanMacro(LoadSequences); /** Parse any private tags in the DICOM file. Defaults to the value @@ -176,7 +189,7 @@ public: * private tags are not needed. */ itkSetMacro(LoadPrivateTags, bool); - itkGetMacro(LoadPrivateTags, bool); + itkGetConstMacro(LoadPrivateTags, bool); itkBooleanMacro(LoadPrivateTags); /** Global method to define the default value for diff --git a/Utilities/ITK/Code/IO/itkGDCMSeriesFileNames.h b/Utilities/ITK/Code/IO/itkGDCMSeriesFileNames.h index 5542d5066c..bf2326ebbb 100644 --- a/Utilities/ITK/Code/IO/itkGDCMSeriesFileNames.h +++ b/Utilities/ITK/Code/IO/itkGDCMSeriesFileNames.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGDCMSeriesFileNames.h,v $ Language: C++ - Date: $Date: 2007-08-24 13:35:59 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-25 12:25:42 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -112,7 +112,7 @@ public: /** Recursively parse the input directory */ itkSetMacro(Recursive, bool); - itkGetMacro(Recursive, bool); + itkGetConstMacro(Recursive, bool); itkBooleanMacro(Recursive); /** Use additional series information such as ProtocolName @@ -163,7 +163,7 @@ public: * sequences are not needed. */ itkSetMacro(LoadSequences, bool); - itkGetMacro(LoadSequences, bool); + itkGetConstMacro(LoadSequences, bool); itkBooleanMacro(LoadSequences); /** Parse any private tags in the DICOM file. Defaults to false @@ -171,7 +171,7 @@ public: * private tags are not needed. */ itkSetMacro(LoadPrivateTags, bool); - itkGetMacro(LoadPrivateTags, bool); + itkGetConstMacro(LoadPrivateTags, bool); itkBooleanMacro(LoadPrivateTags); protected: diff --git a/Utilities/ITK/Code/IO/itkGE4ImageIO.cxx b/Utilities/ITK/Code/IO/itkGE4ImageIO.cxx index 93e39e641b..38c81c638e 100644 --- a/Utilities/ITK/Code/IO/itkGE4ImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkGE4ImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGE4ImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-01-01 17:26:50 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-04-05 16:18:30 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,10 +24,13 @@ #include "itkMvtSunf.h" #include "itkDirectory.h" #include <itksys/SystemTools.hxx> +#include <string.h> #include <string> #include <iostream> #include <fstream> #include <vector> +#include <stdio.h> +#include <stdlib.h> //From uiig library "The University of Iowa Imaging Group-UIIG" namespace itk diff --git a/Utilities/ITK/Code/IO/itkGiplImageIO.cxx b/Utilities/ITK/Code/IO/itkGiplImageIO.cxx index 06136ab064..6ba5c02dc6 100644 --- a/Utilities/ITK/Code/IO/itkGiplImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkGiplImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGiplImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-01-25 00:00:06 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-05 10:56:48 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,7 +19,7 @@ #include "itkByteSwapper.h" #include <iostream> #include <list> -#include <string> +#include <string.h> #include <math.h> #include "itk_zlib.h" diff --git a/Utilities/ITK/Code/IO/itkIOCommon.cxx b/Utilities/ITK/Code/IO/itkIOCommon.cxx index 795885ef36..3523809640 100644 --- a/Utilities/ITK/Code/IO/itkIOCommon.cxx +++ b/Utilities/ITK/Code/IO/itkIOCommon.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIOCommon.cxx,v $ Language: C++ - Date: $Date: 2009-02-21 20:36:26 $ - Version: $Revision: 1.28 $ + Date: $Date: 2009-04-05 10:56:48 $ + Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,6 +17,7 @@ #include "itkIOCommon.h" #include <sys/stat.h> #include <cstring> +#include <string.h> namespace itk diff --git a/Utilities/ITK/Code/IO/itkImageFileReader.txx b/Utilities/ITK/Code/IO/itkImageFileReader.txx index 9dd2fe4620..c4d91f4fcf 100644 --- a/Utilities/ITK/Code/IO/itkImageFileReader.txx +++ b/Utilities/ITK/Code/IO/itkImageFileReader.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageFileReader.txx,v $ Language: C++ - Date: $Date: 2009-02-22 05:53:41 $ - Version: $Revision: 1.84 $ + Date: $Date: 2009-05-19 19:26:25 $ + Version: $Revision: 1.85 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -245,7 +245,7 @@ ImageFileReader<TOutputImage, ConvertPixelTraits> typedef typename TOutputImage::AccessorFunctorType AccessorFunctorType; AccessorFunctorType::SetVectorLength( output, m_ImageIO->GetNumberOfComponents() ); } - + output->SetLargestPossibleRegion(region); } @@ -294,12 +294,6 @@ ImageFileReader<TOutputImage, ConvertPixelTraits> typename TOutputImage::Pointer out = dynamic_cast<TOutputImage*>(output); typename TOutputImage::RegionType largestRegion = out->GetLargestPossibleRegion(); - if (!m_UseStreaming) - { - m_ImageIO->SetUseStreamedReading(m_UseStreaming); - out->SetRequestedRegionToLargestPossibleRegion(); - } - // Delegate to the ImageIO the computation of how much the // requested region must be enlarged. @@ -312,15 +306,27 @@ ImageFileReader<TOutputImage, ConvertPixelTraits> ImageIORegion ioRequestedRegion( TOutputImage::ImageDimension ); typedef ImageIORegionAdaptor< TOutputImage::ImageDimension > ImageIOAdaptor; - + ImageIOAdaptor::Convert( imageRequestedRegion, ioRequestedRegion, largestRegion.GetIndex() ); // Tell the IO if we should use streaming while reading m_ImageIO->SetUseStreamedReading(m_UseStreaming); - + ImageIORegion ioStreamableRegion = m_ImageIO->GenerateStreamableReadRegionFromRequestedRegion( ioRequestedRegion ); + // if the ImageIO must read a higher dimension, we can't read the file + if (ioStreamableRegion.GetImageDimension() > TOutputImage::ImageDimension ) + { + ::itk::OStringStream message; + message << "ImageIO returns IO region that does is not fully contain by the largest possible region\n" + << "Largest region: " << largestRegion + << "StreamableRegion region: " << ioStreamableRegion; + InvalidRequestedRegionError e(__FILE__, __LINE__); + e.SetLocation(ITK_LOCATION); + e.SetDescription(message.str().c_str()); + throw e; + } ImageIOAdaptor::Convert( ioStreamableRegion, this->m_StreamableRegion, largestRegion.GetIndex() ); @@ -332,7 +338,8 @@ ImageFileReader<TOutputImage, ConvertPixelTraits> itkExceptionMacro( << "ImageIO returns IO region that does not fully contain the requested region" << "Requested region: " << imageRequestedRegion - << "StreamableRegion region: " << this->m_StreamableRegion); + << "StreamableRegion region: " << this->m_StreamableRegion + ); } itkDebugMacro (<< "StreamableRegion set to =" << this->m_StreamableRegion ); @@ -353,8 +360,7 @@ void ImageFileReader<TOutputImage, ConvertPixelTraits> << "Allocating the buffer with the StreamableRegion \n" << this->m_StreamableRegion << "\n"); - output->SetBufferedRegion( this->m_StreamableRegion ); - output->Allocate(); + this->AllocateOutputs(); // Test if the file exist and if it can be open. // and exception will be thrown otherwise. diff --git a/Utilities/ITK/Code/IO/itkImageIOBase.cxx b/Utilities/ITK/Code/IO/itkImageIOBase.cxx index e1e16358e4..362726419c 100644 --- a/Utilities/ITK/Code/IO/itkImageIOBase.cxx +++ b/Utilities/ITK/Code/IO/itkImageIOBase.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageIOBase.cxx,v $ Language: C++ - Date: $Date: 2009-02-22 05:53:41 $ - Version: $Revision: 1.83 $ + Date: $Date: 2009-05-19 19:26:25 $ + Version: $Revision: 1.85 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -965,8 +965,8 @@ ImageIOBase::GetActualNumberOfSplitsForWritingCanStreamWrite(unsigned int number // determine the actual number of pieces that will be generated ImageIORegion::SizeType::value_type range = regionSize[splitAxis]; - int valuesPerPiece = (int)::ceil(range/double(numberOfRequestedSplits)); - int maxPieceUsed = (int)::ceil(range/double(valuesPerPiece)) - 1; + int valuesPerPiece = (int)vcl_ceil(range/double(numberOfRequestedSplits)); + int maxPieceUsed = (int)vcl_ceil(range/double(valuesPerPiece)) - 1; return maxPieceUsed+1; } @@ -1024,8 +1024,8 @@ ImageIOBase::GetSplitRegionForWritingCanStreamWrite(unsigned int ithPiece, // determine the actual number of pieces that will be generated ImageIORegion::SizeType::value_type range = regionSize[splitAxis]; - int valuesPerPiece = (int)::ceil(range/(double)numberOfActualSplits); - int maxPieceUsed = (int)::ceil(range/(double)valuesPerPiece) - 1; + int valuesPerPiece = (int)vcl_ceil(range/(double)numberOfActualSplits); + int maxPieceUsed = (int)vcl_ceil(range/(double)valuesPerPiece) - 1; // Split the region if ((int) ithPiece < maxPieceUsed) @@ -1073,29 +1073,45 @@ ImageIOBase { // // The default implementations determines that the streamable region is - // equal to the largest possible region of the image. + // equal to the minimal size of the image in the file. That is two + // say the return ImageIORegion::GetImageSizeInPixels() is equal to + // the number in the file. // - // Since the image in the file may have a dimension lower - // than the image type over which the ImageFileReader/Writer is - // being instantiated, we must fill in the co-dimensions in a - // consistent way. + // Since the image in the file may have a lower or higher dimension + // than the image type over which the ImageFileReader is + // being instantiated we must choose an image dimension which will + // represent all the pixels. That is we can trim trailing 1s. + + unsigned int minIODimension = this->m_NumberOfDimensions; + while (minIODimension) + { + if (this->m_Dimensions[minIODimension-1] == 1) + { + --minIODimension; + } + else + { + break; + } + } + + // dimension size we use to represent the region + unsigned int maxDimension = + minIODimension > requested.GetImageDimension() ? minIODimension : requested.GetImageDimension(); - // First: allocate with the image IO number of dimensions - ImageIORegion streamableRegion( requested.GetImageDimension() ); + // First: allocate with the correct dimensions + ImageIORegion streamableRegion( maxDimension ); - // Second: copy only the number of dimension that the image has. - unsigned int maxDimensionToCopy = - this->m_NumberOfDimensions > requested.GetImageDimension() ? - requested.GetImageDimension() : this->m_NumberOfDimensions; - for( unsigned int i=0; i < maxDimensionToCopy; i++ ) + // Second: copy only the number of dimension that the file has. + for( unsigned int i=0; i < minIODimension; i++ ) { streamableRegion.SetSize( i, this->m_Dimensions[i] ); streamableRegion.SetIndex( i, 0 ); } // Third: set the rest to the default : start = 0, size = 1 - for( unsigned int j=maxDimensionToCopy; j<requested.GetImageDimension(); j++ ) + for( unsigned int j=minIODimension; j<streamableRegion.GetImageDimension(); j++ ) { streamableRegion.SetSize( j, 1 ); streamableRegion.SetIndex( j, 0 ); diff --git a/Utilities/ITK/Code/IO/itkImageIOBase.h b/Utilities/ITK/Code/IO/itkImageIOBase.h index 1a09e8a7fd..c05956cc6c 100644 --- a/Utilities/ITK/Code/IO/itkImageIOBase.h +++ b/Utilities/ITK/Code/IO/itkImageIOBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageIOBase.h,v $ Language: C++ - Date: $Date: 2009-02-22 05:53:41 $ - Version: $Revision: 1.51 $ + Date: $Date: 2009-05-19 19:26:25 $ + Version: $Revision: 1.53 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -172,17 +172,17 @@ public: /** Set/Get a boolean to use the compression or not. */ itkSetMacro(UseCompression,bool); - itkGetMacro(UseCompression,bool); + itkGetConstMacro(UseCompression,bool); itkBooleanMacro(UseCompression); /** Set/Get a boolean to use streaming while reading or not. */ itkSetMacro(UseStreamedReading,bool); - itkGetMacro(UseStreamedReading,bool); + itkGetConstMacro(UseStreamedReading,bool); itkBooleanMacro(UseStreamedReading); /** Set/Get a boolean to use streaming while writing or not. */ itkSetMacro(UseStreamedWriting,bool); - itkGetMacro(UseStreamedWriting,bool); + itkGetConstMacro(UseStreamedWriting,bool); itkBooleanMacro(UseStreamedWriting); @@ -322,8 +322,15 @@ public: /** Method for supporting streaming. Given a requested region, determine what * could be the region that we can read from the file. This is called the - * streamable region, which will be smaller than the LargestPossibleRegion and - * greater or equal to the RequestedRegion */ + * streamable region, which will be equal or smaller than the + * LargestPossibleRegion (unless it was dimensionaly clipped) and + * greater or equal to the RequestedRegion + * + * the resulting IORegion may be a greater dimensions the the + * requested IORegion, if the the derived class is unable to read + * the requested region. For example if the file has a size of [ 10, + * 10, 10] but the requested region is [10, 10] the return may be 3 dimensions. + */ virtual ImageIORegion GenerateStreamableReadRegionFromRequestedRegion( const ImageIORegion & requested ) const; @@ -337,9 +344,11 @@ public: * If pasted is enabled and is not support or does not work with the file, * then an excepetion should be thrown. * - * The default implementation depends on CanStreamWrite. + * The default implementation depends on CanStreamWrite. * If false then 1 is returned (unless pasting is indicated), so that the whole file will be updated in one region. - * If true then its assumed that any arbitrary region can be writen to any file. So the users request will be respected. If a derived class has more restictive conditions then they should be checked + * If true then its assumed that any arbitrary region can be writen + * to any file. So the users request will be respected. If a derived + * class has more restictive conditions then they should be checked */ virtual unsigned int GetActualNumberOfSplitsForWriting(unsigned int numberOfRequestedSplits, const ImageIORegion &pasteRegion, diff --git a/Utilities/ITK/Code/IO/itkImageIORegion.cxx b/Utilities/ITK/Code/IO/itkImageIORegion.cxx index 47a290b189..bdd3c5dbea 100644 --- a/Utilities/ITK/Code/IO/itkImageIORegion.cxx +++ b/Utilities/ITK/Code/IO/itkImageIORegion.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageIORegion.cxx,v $ Language: C++ - Date: $Date: 2009-02-27 14:02:55 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-05-18 15:22:16 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -194,7 +194,9 @@ ImageIORegion ::IsInside(const IndexType &index) const { if (m_ImageDimension != index.size()) - return false; + { + return false; + } for(unsigned int i=0; i<m_ImageDimension; i++) { if( index[i] < m_Index[i] ) diff --git a/Utilities/ITK/Code/IO/itkImageSeriesReader.h b/Utilities/ITK/Code/IO/itkImageSeriesReader.h index 336ac754b7..e424ca7f26 100755 --- a/Utilities/ITK/Code/IO/itkImageSeriesReader.h +++ b/Utilities/ITK/Code/IO/itkImageSeriesReader.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSeriesReader.h,v $ Language: C++ - Date: $Date: 2009-02-20 23:32:06 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-25 12:25:42 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -113,7 +113,7 @@ public: /** ReverseOrderOn changes the order of travesal of the file names * from last to first */ itkSetMacro(ReverseOrder,bool); - itkGetMacro(ReverseOrder,bool); + itkGetConstMacro(ReverseOrder,bool); itkBooleanMacro(ReverseOrder); /** Set/Get the ImageIO helper class. By default, the diff --git a/Utilities/ITK/Code/IO/itkImageSeriesReader.txx b/Utilities/ITK/Code/IO/itkImageSeriesReader.txx index c14ae288e0..22518ea992 100755 --- a/Utilities/ITK/Code/IO/itkImageSeriesReader.txx +++ b/Utilities/ITK/Code/IO/itkImageSeriesReader.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSeriesReader.txx,v $ Language: C++ - Date: $Date: 2009-02-27 16:07:26 $ - Version: $Revision: 1.34 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.35 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -215,7 +215,7 @@ void ImageSeriesReader<TOutputImage> { interSliceSpacing += vnl_math_sqr(position2[j] - position1[j]); } - interSliceSpacing = static_cast<float>(::sqrt(interSliceSpacing)); + interSliceSpacing = static_cast<float>(vcl_sqrt(interSliceSpacing)); if (interSliceSpacing == 0.0f) { diff --git a/Utilities/ITK/Code/IO/itkImageSeriesWriter.h b/Utilities/ITK/Code/IO/itkImageSeriesWriter.h index a6d924a70d..45728724af 100755 --- a/Utilities/ITK/Code/IO/itkImageSeriesWriter.h +++ b/Utilities/ITK/Code/IO/itkImageSeriesWriter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSeriesWriter.h,v $ Language: C++ - Date: $Date: 2007-04-19 13:58:17 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-05-11 19:26:54 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -136,12 +136,12 @@ public: /** Use this method to set the starting index of the series. * The default value is 1. */ itkSetMacro(StartIndex,unsigned long); - itkGetMacro(StartIndex,unsigned long); + itkGetConstMacro(StartIndex,unsigned long); /** Set the increment of the index of the series. The * default value is 1. */ itkSetMacro(IncrementIndex,unsigned long); - itkGetMacro(IncrementIndex,unsigned long); + itkGetConstMacro(IncrementIndex,unsigned long); /** The format string used to generate each filename in the * series. The filename is built with sprintf(filename, SeriesFormat, @@ -227,6 +227,12 @@ private: /** Array of MetaDataDictionary used for passing information to each slice */ DictionaryArrayRawPointer m_MetaDataDictionaryArray; + + // These two methods provide now a common implementation for the + // GenerateNumericFileNamesAndWrite() and avoid the duplication of code that + // was leaving one of the code branches out of date. + void GenerateNumericFileNames(void); + void WriteFiles(); }; diff --git a/Utilities/ITK/Code/IO/itkImageSeriesWriter.txx b/Utilities/ITK/Code/IO/itkImageSeriesWriter.txx index 6a8014dea8..e999d886f6 100755 --- a/Utilities/ITK/Code/IO/itkImageSeriesWriter.txx +++ b/Utilities/ITK/Code/IO/itkImageSeriesWriter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSeriesWriter.txx,v $ Language: C++ - Date: $Date: 2008-01-27 18:30:01 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-05-11 19:26:54 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,7 +27,7 @@ #include "itkImageRegionConstIterator.h" #include "itkMetaDataObject.h" #include "itkArray.h" - +#include "vnl/algo/vnl_determinant.h" #include <stdio.h> namespace itk { @@ -131,106 +131,45 @@ void ImageSeriesWriter<TInputImage,TOutputImage> ::GenerateNumericFileNamesAndWrite(void) { + itkWarningMacro("This functionality has been DEPRECATED. Use NumericSeriesFileName for generating the filenames"); + this->GenerateNumericFileNames(); + this->WriteFiles(); +} - itkWarningMacro("This functionality has been DEPRECATED. NumericSeriesFileName for generating the filenames"); - +//--------------------------------------------------------- +template <class TInputImage,class TOutputImage> +void +ImageSeriesWriter<TInputImage,TOutputImage> +::GenerateNumericFileNames(void) +{ const InputImageType * inputImage = this->GetInput(); if( !inputImage ) { itkExceptionMacro(<<"Input image is NULL"); } + + m_FileNames.clear(); // We need two regions. One for the input, one for the output. ImageRegion<TInputImage::ImageDimension> inRegion = inputImage->GetRequestedRegion(); - ImageRegion<TOutputImage::ImageDimension> outRegion; - - typename OutputImageType::Pointer outputImage = OutputImageType::New(); - // Set the origin, spacing and direction of the output - double spacing[TOutputImage::ImageDimension]; - double origin[TOutputImage::ImageDimension]; - typename TOutputImage::DirectionType direction; - for ( unsigned int i=0; i < TOutputImage::ImageDimension; i++ ) - { - origin[i] = inputImage->GetOrigin()[i]; - spacing[i] = inputImage->GetSpacing()[i]; - outRegion.SetSize(i,inputImage->GetRequestedRegion().GetSize()[i]); - for ( unsigned int j=0; j < TOutputImage::ImageDimension; j++ ) - { - direction[j][i] = inputImage->GetDirection()[j][i]; - } - } - outputImage->SetOrigin(origin); - outputImage->SetSpacing(spacing); - outputImage->SetDirection(direction); - - // Allocate an image for output and create an iterator for it - outputImage->SetRegions(outRegion); - outputImage->Allocate(); - ImageRegionIterator<OutputImageType> ot (outputImage, outRegion ); - - unsigned long fileNumber = m_StartIndex; + unsigned long fileNumber = this->m_StartIndex; char fileName[IOCommon::ITK_MAXPATHLEN+1]; - Index<TInputImage::ImageDimension> inIndex; - unsigned long pixelsPerFile = outputImage->GetRequestedRegion().GetNumberOfPixels(); // Compute the number of files to be generated unsigned int numberOfFiles = 1; - for (unsigned int n = TOutputImage::ImageDimension; - n < TInputImage::ImageDimension; - n++) + for (unsigned int n = TOutputImage::ImageDimension; n < TInputImage::ImageDimension; n++) { numberOfFiles *= inRegion.GetSize(n); } - itkDebugMacro( <<"Number of files to write = " << numberOfFiles ); - - ProgressReporter progress(this, 0, - numberOfFiles, - numberOfFiles); - - // For each "slice" in the input, copy the region to the output, - // build a filename and write the file. - - typename InputImageType::OffsetValueType offset = 0; for (unsigned int slice=0; slice < numberOfFiles; slice++) { - // Select a "slice" of the image. - inIndex = inputImage->ComputeIndex(offset); - inRegion.SetIndex(inIndex); - ImageRegionConstIterator<InputImageType> it (inputImage, - inRegion); - - // Copy the selected "slice" into the output image. - ot.GoToBegin(); - while (!ot.IsAtEnd()) - { - ot.Set(it.Get()); - ++it; - ++ot; - } - - // Mark the image as 'Modified' - outputImage->Modified(); - - typename WriterType::Pointer writer = WriterType::New(); - writer->SetInput(outputImage); - if (m_ImageIO) - { - writer->SetImageIO(m_ImageIO); - } sprintf (fileName, m_SeriesFormat.c_str(), fileNumber); - - writer->SetUseCompression(m_UseCompression); - writer->SetFileName(fileName); - writer->Update(); - - progress.CompletedPixel(); - fileNumber += m_IncrementIndex; - offset += pixelsPerFile; + m_FileNames.push_back( fileName ); + fileNumber += this->m_IncrementIndex; } - } //--------------------------------------------------------- @@ -248,6 +187,15 @@ ImageSeriesWriter<TInputImage,TOutputImage> return; } + this->WriteFiles(); +} + +//--------------------------------------------------------- +template <class TInputImage,class TOutputImage> +void +ImageSeriesWriter<TInputImage,TOutputImage> +::WriteFiles() +{ const InputImageType * inputImage = this->GetInput(); if( !inputImage ) @@ -286,6 +234,19 @@ ImageSeriesWriter<TInputImage,TOutputImage> direction[j][i] = inputImage->GetDirection()[j][i]; } } + + // + // Address the fact that when taking a 2x2 sub-matrix from + // the direction matrix we may obtain a singular matrix. + // A 2x2 orientation can't represent a 3x3 orientation and + // therefore, replacing the orientation with an identity + // is as arbitrary as any other choice. + // + if ( vnl_determinant( direction.GetVnlMatrix() ) == 0.0 ) + { + direction.SetIdentity(); + } + outputImage->SetOrigin( origin ); outputImage->SetSpacing( spacing ); outputImage->SetDirection( direction ); @@ -302,9 +263,7 @@ ImageSeriesWriter<TInputImage,TOutputImage> } unsigned int expectedNumberOfFiles = 1; - for( unsigned int n = TOutputImage::ImageDimension; - n < TInputImage::ImageDimension; - n++ ) + for( unsigned int n = TOutputImage::ImageDimension; n < TInputImage::ImageDimension; n++ ) { expectedNumberOfFiles *= inRegion.GetSize(n); } @@ -333,8 +292,7 @@ ImageSeriesWriter<TInputImage,TOutputImage> inRegion.SetIndex( inIndex ); inRegion.SetSize( inSize ); - ImageRegionConstIterator<InputImageType> it (inputImage, - inRegion); + ImageRegionConstIterator<InputImageType> it (inputImage, inRegion); // Copy the selected "slice" into the output image. it.GoToBegin(); diff --git a/Utilities/ITK/Code/IO/itkJPEGImageIO.cxx b/Utilities/ITK/Code/IO/itkJPEGImageIO.cxx index 9132f0e1a2..883303fc7c 100644 --- a/Utilities/ITK/Code/IO/itkJPEGImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkJPEGImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkJPEGImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-10-24 16:21:55 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-23 15:21:52 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -33,6 +33,10 @@ extern "C" #include <setjmp.h> } +#ifndef itk_secret_symbol_mangled_jpeg8 +#error Sorry something went wrong with your configuration, you are using a system jpeglib.h instead of the special mangled one +#endif + // create an error handler for jpeg that // can longjmp out of the jpeg library diff --git a/Utilities/ITK/Code/IO/itkJPEGImageIO.h b/Utilities/ITK/Code/IO/itkJPEGImageIO.h index 73a2efbea6..edd294a020 100644 --- a/Utilities/ITK/Code/IO/itkJPEGImageIO.h +++ b/Utilities/ITK/Code/IO/itkJPEGImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkJPEGImageIO.h,v $ Language: C++ - Date: $Date: 2007-03-29 18:39:28 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:25:42 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,11 +49,11 @@ public: /** Set/Get the level of quality for the output images. */ itkSetMacro(Quality, int); - itkGetMacro(Quality, int); + itkGetConstMacro(Quality, int); /** */ itkSetMacro(Progressive, bool); - itkGetMacro(Progressive, bool); + itkGetConstMacro(Progressive, bool); /*-------- This part of the interface deals with reading data. ------ */ diff --git a/Utilities/ITK/Code/IO/itkMetaArrayWriter.h b/Utilities/ITK/Code/IO/itkMetaArrayWriter.h index 904526e1e1..ad2669cb5a 100755 --- a/Utilities/ITK/Code/IO/itkMetaArrayWriter.h +++ b/Utilities/ITK/Code/IO/itkMetaArrayWriter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaArrayWriter.h,v $ Language: C++ - Date: $Date: 2007-03-22 14:28:51 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-25 12:25:44 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -63,7 +63,7 @@ public: itkSetMacro(Binary, bool); /** Returns true if the file to be produced will store the data in binary * (instead of ascii) format */ - itkGetMacro(Binary, bool); + itkGetConstMacro(Binary, bool); /** Set the input itk Array to write */ template <typename TValueType> @@ -148,7 +148,7 @@ public: /** Set/Get the precision of the writing */ itkSetMacro(Precision, unsigned int); - itkGetMacro(Precision, unsigned int); + itkGetConstMacro(Precision, unsigned int); /** Set the data type written to the file */ void ConvertTo(MET_ValueEnumType _metaElementType); diff --git a/Utilities/ITK/Code/IO/itkMetaImageIO.cxx b/Utilities/ITK/Code/IO/itkMetaImageIO.cxx index bf21d6c172..96a6a81c55 100644 --- a/Utilities/ITK/Code/IO/itkMetaImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkMetaImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-02-24 03:54:35 $ - Version: $Revision: 1.94 $ + Date: $Date: 2009-05-20 12:16:44 $ + Version: $Revision: 1.100 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,6 +19,7 @@ #endif #include <string> +#include <stdlib.h> #include "itkMetaImageIO.h" #include "itkExceptionObject.h" #include "itkSpatialOrientation.h" @@ -88,9 +89,11 @@ void MetaImageIO::ReadImageInformation() { if(!m_MetaImage.Read(m_FileName.c_str(), false)) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("File cannot be read"); - throw exception; + itkExceptionMacro("File cannot be read: " + << this->GetFileName() << " for reading." + << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } if(m_MetaImage.BinaryData()) @@ -352,6 +355,19 @@ void MetaImageIO::ReadImageInformation() this->SetNumberOfComponents(m_NumberOfComponents * m_NumberOfComponents); break; } + + // BUG: 8732 + // The above use to MET_*_ARRAY may not be correct, as this MetaIO + // ElementType was not designed to indicate vectors, but something + // else + // + // if the file has multiple components then we default to a vector + // pixel type, support could be added to MetaIO format to define + // different pixel types + if ( m_MetaImage.ElementNumberOfChannels() > 1 ) + { + this->SetPixelType( VECTOR ); + } this->SetNumberOfDimensions(m_MetaImage.NDims()); @@ -830,28 +846,36 @@ void MetaImageIO::ReadImageInformation() void MetaImageIO::Read(void* buffer) { const unsigned int nDims = this->GetNumberOfDimensions(); - const unsigned int ioDims = this->m_IORegion.GetImageDimension(); - - const unsigned int minDimension = ( nDims > ioDims ) ? ioDims : nDims; - - // this is a check to see if we are actually streaming - // we initialize with m_IORegion to match dimensions - ImageIORegion largestRegion(minDimension); - for(unsigned int i=0; i<minDimension; i++) + // this will check to see if we are actually streaming + // we initialize with the dimensions of the file, since if + // largestRegion and ioRegion don't match, we'll use the streaming + // path since the comparison will fail + ImageIORegion largestRegion(nDims); + for(unsigned int i=0; i<nDims; i++) { largestRegion.SetIndex(i, 0); largestRegion.SetSize(i, this->GetDimensions(i)); } + if(largestRegion != m_IORegion) { - int* indexMin = new int[minDimension]; - int* indexMax = new int[minDimension]; - for(unsigned int i=0;i<minDimension;i++) + int* indexMin = new int[nDims]; + int* indexMax = new int[nDims]; + for(unsigned int i=0;i<nDims;i++) { - indexMin[i] = m_IORegion.GetIndex()[i]; - indexMax[i] = indexMin[i] + m_IORegion.GetSize()[i] - 1; + if ( i < m_IORegion.GetImageDimension() ) + { + indexMin[i] = m_IORegion.GetIndex()[i]; + indexMax[i] = indexMin[i] + m_IORegion.GetSize()[i] - 1; + } + else + { + indexMin[i] = 0; + // this is zero since this is a (size - 1) + indexMax[i] = 0; + } } if (!m_MetaImage.ReadROI(indexMin, indexMax, @@ -860,19 +884,23 @@ void MetaImageIO::Read(void* buffer) { delete [] indexMin; delete [] indexMax; - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("File ROI cannot be read"); - throw exception; + itkExceptionMacro("File cannot be read: " + << this->GetFileName() << " for reading." + << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } - + delete [] indexMin; delete [] indexMax; } else if(!m_MetaImage.Read(m_FileName.c_str(), true, buffer)) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("File cannot be read"); - throw exception; + itkExceptionMacro("File cannot be read: " + << this->GetFileName() << " for reading." + << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } m_MetaImage.ElementByteOrderFix(); @@ -1336,6 +1364,9 @@ MetaImageIO int* indexMax = new int[nDims]; for( unsigned int k=0; k<nDims; k++ ) { + // the dimensions of m_IORegion should match out requested + // dimensions, but ImageIORegion will throw an + // exception if out of bounds indexMin[k] = m_IORegion.GetIndex()[k]; indexMax[k] = m_IORegion.GetIndex()[k] + m_IORegion.GetSize()[k] - 1; } @@ -1344,9 +1375,11 @@ MetaImageIO { delete [] indexMin; delete [] indexMax; - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("File ROI cannot be written"); - throw exception; + itkExceptionMacro("File ROI cannot be written: " + << this->GetFileName() + << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } delete [] indexMin; @@ -1356,9 +1389,11 @@ MetaImageIO { if ( !m_MetaImage.Write( m_FileName.c_str() ) ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("File cannot be written"); - throw exception; + itkExceptionMacro("File cannot be written: " + << this->GetFileName() + << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } } @@ -1459,9 +1494,14 @@ MetaImageIO::GetActualNumberOfSplitsForWriting(unsigned int numberOfRequestedSpl errorMessage = "File is compressed: " + m_FileName; } // 2)pixel type - else if (headerImageIOReader->GetPixelType() != this->GetPixelType() || - headerImageIOReader->GetNumberOfComponents() != this->GetNumberOfComponents() || - headerImageIOReader->GetComponentType() != this->GetComponentType()) + // this->GetPixelType() is not verified becasue the metaio file format + // stores all multi-component types as arrays, so it does not + // distinguish between pixel types. Also as long as the compoent + // and number of compoents match we should be able to paste, that + // is the numbers should be the same it is just the interpretation + // that is not matching + else if ( headerImageIOReader->GetNumberOfComponents() != this->GetNumberOfComponents() || + headerImageIOReader->GetComponentType() != this->GetComponentType() ) { errorMessage = "Component type does not match in file: " + m_FileName; } @@ -1495,6 +1535,12 @@ MetaImageIO::GetActualNumberOfSplitsForWriting(unsigned int numberOfRequestedSpl { itkExceptionMacro("Unable to paste because pasting file exists and is different. " << errorMessage); } + else if ( headerImageIOReader->GetPixelType() != this->GetPixelType() ) + { + // since there is currently poor support for pixel types in + // MetaIO we will just warn when it does not match + itkWarningMacro("Pixel types does not match file, but component type and number of components do."); + } } else if (numberOfRequestedSplits != 1) { diff --git a/Utilities/ITK/Code/IO/itkMetaImageIO.h b/Utilities/ITK/Code/IO/itkMetaImageIO.h index db78d780b6..fa0a6bca96 100644 --- a/Utilities/ITK/Code/IO/itkMetaImageIO.h +++ b/Utilities/ITK/Code/IO/itkMetaImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaImageIO.h,v $ Language: C++ - Date: $Date: 2009-01-30 22:33:53 $ - Version: $Revision: 1.36 $ + Date: $Date: 2009-04-25 12:25:44 $ + Version: $Revision: 1.37 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -147,7 +147,7 @@ public: * we want a coarse version of the image/ * \Warning this is only used when streaming is on. */ itkSetMacro(SubSamplingFactor,unsigned int); - itkGetMacro(SubSamplingFactor,unsigned int); + itkGetConstMacro(SubSamplingFactor,unsigned int); protected: MetaImageIO(); diff --git a/Utilities/ITK/Code/IO/itkNiftiImageIO.cxx b/Utilities/ITK/Code/IO/itkNiftiImageIO.cxx index 28ec0f1560..f7c10c0305 100644 --- a/Utilities/ITK/Code/IO/itkNiftiImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkNiftiImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNiftiImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-06-27 15:14:50 $ - Version: $Revision: 1.71 $ + Date: $Date: 2009-04-30 15:37:01 $ + Version: $Revision: 1.84 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,6 +21,7 @@ #include "itkByteSwapper.h" #include "itkMetaDataObject.h" #include "itkSpatialOrientationAdapter.h" +#include "itkNumericTraits.h" #include <itksys/SystemTools.hxx> #include <vnl/vnl_math.h> #include "itk_zlib.h" @@ -240,6 +241,97 @@ static void dumpdata(const void *x) #define dumpdata(x) #endif // #if defined(__USE_VERY_VERBOSE_NIFTI_DEBUGGING__) +// returns an ordering array for converting upper triangular symmetric matrix +// to lower triangular symmetric matrix +int * +UpperToLowerOrder(int dim) +{ + int **mat = new int *[dim]; + for(int i = 0; i < dim; i++) + { + mat[i] = new int[dim]; + } + // fill in + int index(0); + for(int i = 0; i < dim; i++) + { + for(int j = i; j < dim; j++) + { + mat[i][j] = index; + mat[j][i] = index; + index++; + } + } + int *rval = new int[index+1]; + int index2(0); + for(int i = 0; i < dim; i++) + { + for(int j = 0; j <= i; j++,index2++) + { + rval[index2] = mat[i][j]; + } + } + rval[index2] = -1; + for(int i = 0; i < dim; i++) + { + delete [] mat[i]; + } + delete [] mat; + return rval; +} +// returns an ordering array for converting lower triangular symmetric matrix +// to upper triangular symmetric matrix +int * +LowerToUpperOrder(int dim) +{ + int **mat = new int *[dim]; + for(int i = 0; i < dim; i++) + { + mat[i] = new int[dim]; + } + // fill in + int index(0); + for(int i = 0; i < dim; i++) + { + for(int j = 0; j <= i; j++,index++) + { + mat[i][j] = index; + mat[j][i] = index; + } + } + int *rval = new int[index+1]; + int index2(0); + for(int i = 0; i < dim; i++) + { + for(int j = i; j < dim; j++,index2++) + { + rval[index2] = mat[i][j]; + } + } + rval[index2] = -1; + for(int i = 0; i < dim; i++) + { + delete [] mat[i]; + } + delete [] mat; + return rval; +} +// compute the rank of the symmetric matrix from +// the count of the triangular matrix elements +int SymMatDim(int count) +{ + int dim = 0; + int row = 1; + while(count > 0) + { + count -= row; + dim++; + row++; + } + return dim; +} + + ImageIORegion NiftiImageIO ::GenerateStreamableReadRegionFromRequestedRegion(const ImageIORegion & requestedRegion ) const @@ -297,9 +389,9 @@ NiftiImageIO bool NiftiImageIO::MustRescale() { - return vcl_abs(m_RescaleSlope) > vcl_numeric_limits<double>::epsilon() && - (vcl_abs(m_RescaleSlope-1.0) > vcl_numeric_limits<double>::epsilon() || - vcl_abs(m_RescaleIntercept) > vcl_numeric_limits<double>::epsilon()); + return vcl_abs(this->m_RescaleSlope) > vcl_numeric_limits<double>::epsilon() && + (vcl_abs(this->m_RescaleSlope-1.0) > vcl_numeric_limits<double>::epsilon() || + vcl_abs(this->m_RescaleIntercept) > vcl_numeric_limits<double>::epsilon()); } // Internal function to rescale pixel according to Rescale Slope/Intercept @@ -415,12 +507,12 @@ void NiftiImageIO::Read(void* buffer) // before doing the rescale. // if(this->MustRescale() && - m_ComponentType != m_OnDiskComponentType) + this->m_ComponentType != this->m_OnDiskComponentType) { - pixelSize = + pixelSize = static_cast< unsigned int >( this->GetNumberOfComponents() ) * static_cast< unsigned int >( sizeof(float) ); - + // Deal with correct management of 64bits platforms const size_t imageSizeInComponents = static_cast< size_t >( this->GetImageSizeInComponents() ); @@ -431,7 +523,7 @@ void NiftiImageIO::Read(void* buffer) float *_data = static_cast<float *> (malloc( imageSizeInComponents * sizeof(float))); - switch(m_OnDiskComponentType) + switch(this->m_OnDiskComponentType) { case CHAR: CastCopy<char>(_data,data, imageSizeInComponents); @@ -477,7 +569,10 @@ void NiftiImageIO::Read(void* buffer) } // // if single or complex, nifti layout == itk layout - if(numComponents == 1 || this->GetPixelType() == COMPLEX) + if(numComponents == 1 || + this->GetPixelType() == COMPLEX || + this->GetPixelType() == RGB || + this->GetPixelType() == RGBA) { const size_t NumBytes= numElts * pixelSize; memcpy(buffer, data, NumBytes); @@ -493,52 +588,51 @@ void NiftiImageIO::Read(void* buffer) { // otherwise nifti is x y z t vec l m 0, itk is // vec x y z t l m o - - const char *frombuf = (const char *)data; - char *tobuf = (char *)buffer; + const char *niftibuf = (const char *)data; + char *itkbuf = (char *)buffer; + const unsigned int rowdist=this->m_NiftiImage->dim[1]; + const unsigned int slicedist=rowdist*this->m_NiftiImage->dim[2]; + const unsigned int volumedist=slicedist*this->m_NiftiImage->dim[3]; + const unsigned int seriesdist=volumedist*this->m_NiftiImage->dim[4]; // - // we're reassembling images with vector pixes from - // vector of scalar image. - // scalarPtr are pointers to each of the scalar images - const char **scalarPtr = new const char *[numComponents]; - // - // have to accommodate last two slowest looking dims if - // > 1 - unsigned lStride = - _size[4] * _size[3] * - _size[2] * _size[1] * - _size[0] * pixelSize; - unsigned mStride = _size[5] * lStride; - - for(int m = 0; m < _size[6]; m++) + // as per ITK bug 0007485 + // NIfTI is lower triangular, ITK is upper triangular. + int *vecOrder; + if(this->GetPixelType() == ImageIOBase::DIFFUSIONTENSOR3D || + this->GetPixelType() == ImageIOBase::SYMMETRICSECONDRANKTENSOR) { - for(int l = 0; l < _size[5]; l++) +// vecOrder = LowerToUpperOrder(SymMatDim(numComponents)); + vecOrder = UpperToLowerOrder(SymMatDim(numComponents)); + } + else + { + vecOrder = new int[numComponents]; + for(i = 0; i < numComponents; i++) { - // distance between start of scalar images - // scalarPtr[0] = start of first scalar image - // scalarPtr[1] = start of second scalar image etc - unsigned vecStride = _size[0] * _size[1] * - _size[2] * _size[3]; - for(unsigned ii = 0; ii < numComponents; ii++) - { - scalarPtr[ii] = - frombuf + - (l * lStride) + - (m * mStride) + - (vecStride * pixelSize * ii); - } - char *to = tobuf + (l * lStride) + - (m * mStride); - for(unsigned ii = 0; ii < (vecStride * numComponents); ii++) + vecOrder[i] = i; + } + } + for(int t = 0; t < this->m_NiftiImage->dim[4]; t++) + { + for(int z = 0; z < this->m_NiftiImage->dim[3]; z++) + { + for(int y = 0; y < this->m_NiftiImage->dim[2]; y++) { - memcpy(to, - scalarPtr[ii % numComponents],pixelSize); - to += pixelSize; - scalarPtr[ii % numComponents] += pixelSize; + for(int x = 0; x < this->m_NiftiImage->dim[1]; x++) + { + for(unsigned int c=0;c< numComponents; c++) + { + const unsigned int nifti_index=(c*seriesdist+volumedist*t + slicedist*z + rowdist*y + x)*pixelSize; + const unsigned int itk_index=((volumedist*t + slicedist*z + rowdist*y + x)*numComponents + vecOrder[c])*pixelSize; + memcpy(itkbuf+itk_index,niftibuf+nifti_index,pixelSize); + } + } } } } - delete [] scalarPtr; + delete [] vecOrder; + dumpdata(data); + dumpdata(buffer); // if read_subregion was called it allocates a buffer that needs to be // freed. if(data != this->m_NiftiImage->data) @@ -546,71 +640,69 @@ void NiftiImageIO::Read(void* buffer) free(data); } } - // dumpdata(data); - dumpdata(buffer); // If the scl_slope field is nonzero, then rescale each voxel value in the // dataset. // Complete description of can be found in nifti1.h under "DATA SCALING" if(this->MustRescale()) { - switch(m_ComponentType) + switch(this->m_ComponentType) { case CHAR: RescaleFunction(static_cast<char *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; case UCHAR: RescaleFunction(static_cast<unsigned char *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; case SHORT: RescaleFunction(static_cast<short *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; case USHORT: RescaleFunction(static_cast<unsigned short *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; case INT: RescaleFunction(static_cast<int *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; case UINT: RescaleFunction(static_cast<unsigned int *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; case LONG: RescaleFunction(static_cast<long *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; case ULONG: RescaleFunction(static_cast<unsigned long *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; case FLOAT: RescaleFunction(static_cast<float *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; case DOUBLE: RescaleFunction(static_cast<double *>(buffer), - m_RescaleSlope, - m_RescaleIntercept,numElts); + this->m_RescaleSlope, + this->m_RescaleIntercept,numElts); break; default: if(this->GetPixelType() == SCALAR) { itkExceptionMacro(<< "Datatype: " - << this->GetComponentTypeAsString(m_ComponentType) + << this->GetComponentTypeAsString(this->m_ComponentType) << " not supported"); } } @@ -661,96 +753,241 @@ NiftiImageIO { itkExceptionMacro(<< this->GetFileName() << " is not recognized as a NIFTI file"); } - this->SetNumberOfDimensions(this->m_NiftiImage->ndim); + //Check the intent code, it is a vector image, or matrix image, then this is not true. + // + if(this->m_NiftiImage->intent_code == NIFTI_INTENT_VECTOR || + this->m_NiftiImage->intent_code == NIFTI_INTENT_SYMMATRIX) + { + if(this->m_NiftiImage->dim[4] > 1) + { + this->SetNumberOfDimensions(4); + } + else if(this->m_NiftiImage->dim[3] > 1) + { + this->SetNumberOfDimensions(3); + } + else if(this->m_NiftiImage->dim[2] > 1) + { + this->SetNumberOfDimensions(2); + } + else + { + this->SetNumberOfDimensions(1); + } + } + else if(this->m_NiftiImage->intent_code == NIFTI_INTENT_GENMATRIX) + { //TODO: NEED TO DEAL WITH CASE WHERE NIFTI_INTENT_MATRIX + itkExceptionMacro(<< this->GetFileName() << " has an intent code of NIFTI_INTENT_GENMATRIX which is not yet implemented in ITK"); + } + else + { //Simple Scalar Image + // + // this->SetNumberOfDimensions(this->m_NiftiImage->dim[0]); + // HACK ALERT KW + // Apparently some straight-from-the-scanner files report as 4D + // with T = 1; this causes ImageFileReader to erroneously ignore the reported + // direction cosines. + unsigned realdim; + for(realdim = this->m_NiftiImage->dim[0]; + this->m_NiftiImage->dim[realdim] == 1 && realdim > 3; + realdim--) + { + } + this->SetNumberOfDimensions(realdim); + this->SetNumberOfComponents(1); + } + + if(this->m_NiftiImage->intent_code == NIFTI_INTENT_VECTOR || + this->m_NiftiImage->intent_code == NIFTI_INTENT_SYMMATRIX) + { + this->SetNumberOfComponents(this->m_NiftiImage->dim[5]); + } + else if(this->m_NiftiImage->intent_code == NIFTI_INTENT_GENMATRIX) + { //TODO: NEED TO DEAL WITH CASE WHERE NIFTI_INTENT_MATRIX + itkExceptionMacro(<< this->GetFileName() << " has an intent code of NIFTI_INTENT_GENMATRIX which is not yet implemented in ITK"); + } + //TODO: Dealing with NIFTI_INTENT_VECTOR or NIFTI_INTENT_GENMATRIX with data type of NIFTI_TYPE_COMPLEX64 NIFTI_TYPE_COMPLEX128 NIFTI_TYPE_RGB24 not supported. switch( this->m_NiftiImage->datatype ) { case NIFTI_TYPE_INT8: - m_ComponentType = CHAR; - m_PixelType = SCALAR; + this->m_ComponentType = CHAR; + this->m_PixelType = SCALAR; break; case NIFTI_TYPE_UINT8: - m_ComponentType = UCHAR; - m_PixelType = SCALAR; + this->m_ComponentType = UCHAR; + this->m_PixelType = SCALAR; break; case NIFTI_TYPE_INT16: - m_ComponentType = SHORT; - m_PixelType = SCALAR; + this->m_ComponentType = SHORT; + this->m_PixelType = SCALAR; break; case NIFTI_TYPE_UINT16: - m_ComponentType = USHORT; - m_PixelType = SCALAR; + this->m_ComponentType = USHORT; + this->m_PixelType = SCALAR; break; case NIFTI_TYPE_INT32: - m_ComponentType = INT; - m_PixelType = SCALAR; + this->m_ComponentType = INT; + this->m_PixelType = SCALAR; break; case NIFTI_TYPE_UINT32: - m_ComponentType = UINT; - m_PixelType = SCALAR; + this->m_ComponentType = UINT; + this->m_PixelType = SCALAR; break; case NIFTI_TYPE_FLOAT32: - m_ComponentType = FLOAT; - m_PixelType = SCALAR; + this->m_ComponentType = FLOAT; + this->m_PixelType = SCALAR; break; case NIFTI_TYPE_FLOAT64: - m_ComponentType = DOUBLE; - m_PixelType = SCALAR; + this->m_ComponentType = DOUBLE; + this->m_PixelType = SCALAR; break; case NIFTI_TYPE_COMPLEX64: - m_ComponentType = FLOAT; - m_PixelType = COMPLEX; + this->m_ComponentType = FLOAT; + this->m_PixelType = COMPLEX; this->SetNumberOfComponents(2); break; case NIFTI_TYPE_COMPLEX128: - m_ComponentType = DOUBLE; - m_PixelType = COMPLEX; + this->m_ComponentType = DOUBLE; + this->m_PixelType = COMPLEX; this->SetNumberOfComponents(2); break; case NIFTI_TYPE_RGB24: - m_ComponentType = UCHAR; - m_PixelType = RGB; + this->m_ComponentType = UCHAR; + this->m_PixelType = RGB; this->SetNumberOfComponents(3); + //TODO: Need to be able to read/write RGB images into ITK. // case DT_RGB: // DEBUG -- Assuming this is a triple, not quad //image.setDataType( uiig::DATA_RGBQUAD ); - // break; + break; + case NIFTI_TYPE_RGBA32: + this->m_ComponentType = UCHAR; + this->m_PixelType = RGBA; + this->SetNumberOfComponents(4); + break; default: break; } - + // there are a wide variety of intents we ignore + // but a few wee need to care about + switch(this->m_NiftiImage->intent_code) + { + case NIFTI_INTENT_NONE: + break; + case NIFTI_INTENT_CORREL: + break; + case NIFTI_INTENT_TTEST: + break; + case NIFTI_INTENT_FTEST: + break; + case NIFTI_INTENT_ZSCORE: + break; + case NIFTI_INTENT_CHISQ: + break; + case NIFTI_INTENT_BETA: + break; + case NIFTI_INTENT_BINOM: + break; + case NIFTI_INTENT_GAMMA: + break; + case NIFTI_INTENT_POISSON: + break; + case NIFTI_INTENT_NORMAL: + break; + case NIFTI_INTENT_FTEST_NONC: + break; + case NIFTI_INTENT_CHISQ_NONC: + break; + case NIFTI_INTENT_LOGISTIC: + break; + case NIFTI_INTENT_LAPLACE: + break; + case NIFTI_INTENT_UNIFORM: + break; + case NIFTI_INTENT_TTEST_NONC: + break; + case NIFTI_INTENT_WEIBULL: + break; + case NIFTI_INTENT_CHI: + break; + case NIFTI_INTENT_INVGAUSS: + break; + case NIFTI_INTENT_EXTVAL: + break; + case NIFTI_INTENT_PVAL: + break; + case NIFTI_INTENT_LOGPVAL: + break; + case NIFTI_INTENT_LOG10PVAL: + break; + case NIFTI_INTENT_ESTIMATE: + break; + case NIFTI_INTENT_LABEL: + break; + case NIFTI_INTENT_NEURONAME: + break; + case NIFTI_INTENT_GENMATRIX: + break; + case NIFTI_INTENT_SYMMATRIX: + this->SetPixelType(SYMMETRICSECONDRANKTENSOR); + break; + case NIFTI_INTENT_DISPVECT: + break; + case NIFTI_INTENT_VECTOR: + this->SetPixelType(VECTOR); + break; + case NIFTI_INTENT_POINTSET: + break; + case NIFTI_INTENT_TRIANGLE: + break; + case NIFTI_INTENT_QUATERNION: + break; + case NIFTI_INTENT_DIMLESS: + break; + case NIFTI_INTENT_TIME_SERIES: + break; + case NIFTI_INTENT_NODE_INDEX: + break; + case NIFTI_INTENT_RGB_VECTOR: + break; + case NIFTI_INTENT_RGBA_VECTOR: + break; + case NIFTI_INTENT_SHAPE: + break; + } // set slope/intercept if(this->m_NiftiImage->qform_code == 0 && this->m_NiftiImage->sform_code == 0) { - m_RescaleSlope = 1; - m_RescaleIntercept = 0; + this->m_RescaleSlope = 1; + this->m_RescaleIntercept = 0; } else { - if((m_RescaleSlope = this->m_NiftiImage->scl_slope) == 0) + if((this->m_RescaleSlope = this->m_NiftiImage->scl_slope) == 0) { - m_RescaleSlope = 1; + this->m_RescaleSlope = 1; } - m_RescaleIntercept = this->m_NiftiImage->scl_inter; + this->m_RescaleIntercept = this->m_NiftiImage->scl_inter; } - m_OnDiskComponentType = m_ComponentType; + this->m_OnDiskComponentType = this->m_ComponentType; // // if rescale is necessary, promote type reported // to ImageFileReader to float if(this->MustRescale()) { - if(m_ComponentType == CHAR || - m_ComponentType == UCHAR || - m_ComponentType == SHORT || - m_ComponentType == USHORT || - m_ComponentType == INT || - m_ComponentType == UINT || - m_ComponentType == LONG || - m_ComponentType == ULONG) + if(this->m_ComponentType == CHAR || + this->m_ComponentType == UCHAR || + this->m_ComponentType == SHORT || + this->m_ComponentType == USHORT || + this->m_ComponentType == INT || + this->m_ComponentType == UINT || + this->m_ComponentType == LONG || + this->m_ComponentType == ULONG) { - m_ComponentType = FLOAT; + this->m_ComponentType = FLOAT; } } // @@ -781,24 +1018,21 @@ NiftiImageIO timingscale=1e-6; break; } - int dims=this->GetNumberOfDimensions(); - // - // dims > 4 have sto skip dim[5] because it's the # - // of vector elements + const int dims=this->GetNumberOfDimensions(); switch(dims) { case 7: - this->SetDimensions(5,this->m_NiftiImage->nw); + this->SetDimensions(6,this->m_NiftiImage->nw); //NOTE: Scaling is not defined in this dimension - this->SetSpacing(5,this->m_NiftiImage->dw); + this->SetSpacing(6,this->m_NiftiImage->dw); case 6: - this->SetDimensions(4,this->m_NiftiImage->nv); + this->SetDimensions(5,this->m_NiftiImage->nv); //NOTE: Scaling is not defined in this dimension - this->SetSpacing(4,this->m_NiftiImage->dv); + this->SetSpacing(5,this->m_NiftiImage->dv); case 5: - // this->SetDimensions(4,this->m_NiftiImage->nu); + this->SetDimensions(4,this->m_NiftiImage->nu); //NOTE: Scaling is not defined in this dimension - // this->SetSpacing(4,this->m_NiftiImage->du); + this->SetSpacing(4,this->m_NiftiImage->du); case 4: this->SetDimensions(3,this->m_NiftiImage->nt); this->SetSpacing(3,this->m_NiftiImage->dt*timingscale); @@ -812,15 +1046,7 @@ NiftiImageIO this->SetDimensions(0,this->m_NiftiImage->nx); this->SetSpacing(0,this->m_NiftiImage->dx*spacingscale); } - // vector images? - if(this->m_NiftiImage->dim[0] > 4) - { - dims = dims - 1; - // as far as ITK is concerned, the dimension - // should now be 4 - // each pixel is a vector - this->SetNumberOfComponents(this->m_NiftiImage->nu); - } + this->ComputeStrides(); //Get Dictionary Information //Insert Orientation. @@ -836,15 +1062,20 @@ NiftiImageIO std::string(typeid(char).name())); break; case UCHAR: - if(m_PixelType != RGB) + if(this->m_PixelType == RGB) { EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName, - std::string(typeid(unsigned char).name())); + std::string("RGB")); + } + else if(this->m_PixelType == RGBA) + { + EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName, + std::string("RGBA")); } else { EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName, - std::string("RGB")); + std::string(typeid(unsigned char).name())); } break; case SHORT: @@ -917,6 +1148,21 @@ NiftiImageIO { // MetaDataDictionary &thisDic=this->GetMetaDataDictionary(); // + // + // First of all we need to not go any further if there's + // a dimension of the image that won't fit in a 16 bit short. + for(unsigned int i = 0; i < this->GetNumberOfDimensions(); i++) + { + unsigned int curdim(this->GetDimensions(i)); + if(curdim > static_cast<unsigned int>(NumericTraits<short>::max())) + { + itkExceptionMacro( << "Dimension(" << i << ") = " << curdim + << " is greater than maximum possible dimension " + << NumericTraits<short>::max() ); + + } + } + // fill out the image header. if(this->m_NiftiImage == 0) { @@ -973,11 +1219,6 @@ NiftiImageIO } this->m_NiftiImage->fname = nifti_makehdrname(BaseName.c_str(),this->m_NiftiImage->nifti_type,false,IsCompressed); this->m_NiftiImage->iname = nifti_makeimgname(BaseName.c_str(),this->m_NiftiImage->nifti_type,false,IsCompressed); - unsigned short dims = - this->m_NiftiImage->ndim = - this->m_NiftiImage->dim[0] = - this->GetNumberOfDimensions(); - unsigned short origdims = dims; // FIELD NOTES // ----------------------------------------------------- // sizeof_hdr must be 348 @@ -993,18 +1234,27 @@ NiftiImageIO // is only one dataset. Having the time specified for a purly spatial // image has no consequence, so go ahead and set it to seconds. this->m_NiftiImage->xyz_units= static_cast< int >( NIFTI_UNITS_MM | NIFTI_UNITS_SEC ); - switch(origdims) + this->m_NiftiImage->dim[7] = this->m_NiftiImage->nw=1; + this->m_NiftiImage->dim[6] = this->m_NiftiImage->nv=1; + this->m_NiftiImage->dim[5] = this->m_NiftiImage->nu=1; + this->m_NiftiImage->dim[4] = this->m_NiftiImage->nt=1; + this->m_NiftiImage->dim[3] = this->m_NiftiImage->nz=1; + this->m_NiftiImage->dim[2] = this->m_NiftiImage->ny=1; + this->m_NiftiImage->dim[1] = this->m_NiftiImage->nx=1; + switch(this->GetNumberOfDimensions()) { case 7: - this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[7] = - this->m_NiftiImage->nw = static_cast< int >( this->GetDimensions(6) ); + this->m_NiftiImage->dim[7] = this->m_NiftiImage->nw + = static_cast< int >( this->GetDimensions(6) ); this->m_NiftiImage->pixdim[7] = this->m_NiftiImage->dw = static_cast<float>( this->GetSpacing(6) ); + this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[7]; case 6: - this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[6] = - this->m_NiftiImage->nv = this->GetDimensions(5); + this->m_NiftiImage->dim[6] = this->m_NiftiImage->nv + = this->GetDimensions(5); this->m_NiftiImage->pixdim[6] = this->m_NiftiImage->dv = static_cast<float>( this->GetSpacing(5) ); + this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[6]; case 5: this->m_NiftiImage->dim[5] = this->m_NiftiImage->nu = this->GetDimensions(4); @@ -1012,69 +1262,88 @@ NiftiImageIO this->m_NiftiImage->du = static_cast<float>( this->GetSpacing(4) ); this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[5]; case 4: - this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[4] = - this->m_NiftiImage->nt = this->GetDimensions(3); + this->m_NiftiImage->dim[4] = this->m_NiftiImage->nt + = this->GetDimensions(3); this->m_NiftiImage->pixdim[4] = this->m_NiftiImage->dt = static_cast<float>( this->GetSpacing(3) ); + this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[4]; case 3: - this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[3] = - this->m_NiftiImage->nz = this->GetDimensions(2); + this->m_NiftiImage->dim[3] = this->m_NiftiImage->nz + = this->GetDimensions(2); this->m_NiftiImage->pixdim[3] = this->m_NiftiImage->dz = static_cast<float>( this->GetSpacing(2) ); + this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[3]; case 2: - this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[2] = - this->m_NiftiImage->ny = this->GetDimensions(1); + this->m_NiftiImage->dim[2] = this->m_NiftiImage->ny + = this->GetDimensions(1); this->m_NiftiImage->pixdim[2] = this->m_NiftiImage->dy = static_cast<float>( this->GetSpacing(1) ); + this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[2]; case 1: - this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[1] = - this->m_NiftiImage->nx = this->GetDimensions(0); + this->m_NiftiImage->dim[1] = this->m_NiftiImage->nx + = this->GetDimensions(0); this->m_NiftiImage->pixdim[1] = this->m_NiftiImage->dx = static_cast<float>( this->GetSpacing(0) ); + this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[1]; } const unsigned int numComponents = this->GetNumberOfComponents(); + //TODO: Also need to check for RGB images where numComponets=3 if( numComponents > 1 - && !(this->GetPixelType() == COMPLEX - && numComponents == 2)) + && !(this->GetPixelType() == COMPLEX + && numComponents == 2) + && !(this->GetPixelType() == RGB + && numComponents == 3) + && !(this->GetPixelType() == RGBA + && numComponents == 4)) { - this->m_NiftiImage->intent_code = NIFTI_INTENT_VECTOR; + this->m_NiftiImage->ndim = 5; //This must be 5 for NIFTI_INTENT_VECTOR images. + this->m_NiftiImage->dim[0] = 5; //This must be 5 for NIFTI_INTENT_VECTOR images. + if(this->GetNumberOfDimensions()> 4) + { + itkExceptionMacro(<< "Can not store a vector image of more than 4 dimensions in a Nifti file. Dimension=" << this->GetNumberOfDimensions() ); + } // - // Bumping dim to 5, so make sure dim 4 is 1 if we're coming - // from dim < 4 - if(dims < 4) + // support symmetric matrix type + if(this->GetPixelType() == ImageIOBase::DIFFUSIONTENSOR3D || + this->GetPixelType() == ImageIOBase::SYMMETRICSECONDRANKTENSOR) + { + this->m_NiftiImage->intent_code = NIFTI_INTENT_SYMMATRIX; + } + else + { + this->m_NiftiImage->intent_code = NIFTI_INTENT_VECTOR; + } + this->m_NiftiImage->nu = + this->m_NiftiImage->dim[5] = this->GetNumberOfComponents(); + if(this->GetNumberOfDimensions() < 4) { this->m_NiftiImage->nt = this->m_NiftiImage->dim[4] = 1; } - if(dims < 3) + if(this->GetNumberOfDimensions() < 3) { this->m_NiftiImage->nz = this->m_NiftiImage->dim[3] = 1; } + if(this->GetNumberOfDimensions() < 2) { - // has to be >= 5 - const unsigned int ForceDimsGreaterThanFive=(dims > 4 ? dims+1 : 5); - dims = ForceDimsGreaterThanFive; - this->m_NiftiImage->ndim = ForceDimsGreaterThanFive; - this->m_NiftiImage->dim[0] = ForceDimsGreaterThanFive; + this->m_NiftiImage->ny = + this->m_NiftiImage->dim[2] = 1; } - for(unsigned i = dims; i > 5; i--) + if(this->GetNumberOfDimensions() < 1) { - switch(i) - { - case 7: - this->m_NiftiImage->dim[7] = this->m_NiftiImage->dim[6]; - this->m_NiftiImage->nw = this->m_NiftiImage->dim[6]; - break; - case 6: - this->m_NiftiImage->dim[6] = this->m_NiftiImage->dim[5]; - this->m_NiftiImage->nv = this->m_NiftiImage->dim[5]; - } + this->m_NiftiImage->nx = + this->m_NiftiImage->dim[1] = 1; } - this->m_NiftiImage->nu = this->GetNumberOfComponents(); - this->m_NiftiImage->dim[5] = this->GetNumberOfComponents(); + // Update nvox value because in nifti, vector components are the slowest changing direction, not the fastest. + this->m_NiftiImage->nvox *= this->GetNumberOfComponents(); + } + else + { + this->m_NiftiImage->ndim = this->GetNumberOfDimensions(); + this->m_NiftiImage->dim[0] = this->GetNumberOfDimensions(); } // ----------------------------------------------------- @@ -1127,12 +1396,17 @@ NiftiImageIO } switch(this->GetPixelType()) { + case VECTOR: //NOTE: VECTOR is un-rolled by nifti to look like a multi-dimensional scalar image case SCALAR: break; case RGB: this->m_NiftiImage->nbyper *= 3; this->m_NiftiImage->datatype = NIFTI_TYPE_RGB24; break; + case RGBA: + this->m_NiftiImage->nbyper *= 4; + this->m_NiftiImage->datatype = NIFTI_TYPE_RGBA32; + break; case COMPLEX: this->m_NiftiImage->nbyper *= 2; switch(this->GetComponentType()) @@ -1150,9 +1424,19 @@ NiftiImageIO } } break; + case SYMMETRICSECONDRANKTENSOR: + case DIFFUSIONTENSOR3D: + break; + case OFFSET: + case POINT: + case COVARIANTVECTOR: + case FIXEDARRAY: + case MATRIX: + case UNKNOWNPIXELTYPE: default: - this->m_NiftiImage->nbyper *= - static_cast< int >( this->GetNumberOfComponents() ); + itkExceptionMacro(<< + "Can not process this pixel type for writing into nifti"); + break; } // ----------------------------------------------------- @@ -1162,7 +1446,7 @@ NiftiImageIO // ----------------------------------------------------- this->m_NiftiImage->scl_slope = 1.0f; this->m_NiftiImage->scl_inter = 0.0f; - this->SetNIfTIOrientationFromImageIO(origdims,dims); + this->SetNIfTIOrientationFromImageIO(this->GetNumberOfDimensions(),this->GetNumberOfDimensions()); //TODO: Note both arguments are the same, no need to distinguish between them. return; } @@ -1179,7 +1463,7 @@ void Normalize(std::vector<double> &x) { return; } - sum = sqrt(sum); + sum = vcl_sqrt(sum); for(unsigned int i = 0; i < x.size(); i++) { x[i] = x[i] / sum; @@ -1247,7 +1531,10 @@ SetImageIOOrientationFromNIfTI(unsigned short int dims) // // set origin m_Origin[0] = -theMat.m[0][3]; - m_Origin[1] = -theMat.m[1][3]; + if(dims > 1) + { + m_Origin[1] = -theMat.m[1][3]; + } if(dims > 2) { m_Origin[2] = theMat.m[2][3]; @@ -1415,7 +1702,9 @@ NiftiImageIO this->WriteImageInformation(); unsigned int numComponents = this->GetNumberOfComponents(); if(numComponents == 1 || - (numComponents == 2 && this->GetPixelType() == COMPLEX)) + (numComponents == 2 && this->GetPixelType() == COMPLEX) || + (numComponents == 3 && this->GetPixelType() == RGB) || + (numComponents == 4 && this->GetPixelType() == RGBA)) { // Need a const cast here so that we don't have to copy the memory // for writing. @@ -1424,82 +1713,84 @@ NiftiImageIO this->m_NiftiImage->data = 0; // if left pointing to data buffer // nifti_image_free will try and free this memory } - else + else ///Image intent is vector image { - // Data must be rearranged to meet nifti organzation. - // output[vec][t][z][y][x] = input[t][z][y][z][vec] - unsigned int nbyper = this->m_NiftiImage->nbyper; - const char *frombuf = (const char *)buffer; - - // correct these values filled in in WriteImageInformation - this->m_NiftiImage->nbyper = nbyper /= numComponents; - this->m_NiftiImage->nvox *= numComponents; - - int *dim = this->m_NiftiImage->dim; for(unsigned int i = 1; i < 8; i++) { - if(dim[i] == 0) + if(this->m_NiftiImage->dim[i] == 0) { - dim[i] = 1; + this->m_NiftiImage->dim[i] = 1; } } - unsigned buffer_size = dim[1] * - dim[2] * - dim[3] * - dim[4] * - dim[5] * - dim[6] * - dim[7] * - nbyper; - char *tobuffer = new char[buffer_size]; - char **scalarPtr = new char *[numComponents]; - int *_size = & dim[1]; + const unsigned numVoxels = + this->m_NiftiImage->dim[1] * + this->m_NiftiImage->dim[2] * + this->m_NiftiImage->dim[3] * + this->m_NiftiImage->dim[4]; + const unsigned buffer_size = + numVoxels* + numComponents * //Number of componenets + this->m_NiftiImage->nbyper; + + char *nifti_buf = new char[buffer_size]; + const char * const itkbuf = (const char *)buffer; + // Data must be rearranged to meet nifti organzation. + // nifti_layout[vec][t][z][y][x] = itk_layout[t][z][y][z][vec] + const unsigned int rowdist=m_NiftiImage->dim[1]; + const unsigned int slicedist=rowdist*m_NiftiImage->dim[2]; + const unsigned int volumedist=slicedist*m_NiftiImage->dim[3]; + const unsigned int seriesdist=volumedist*m_NiftiImage->dim[4]; // - // have to accommodate last two slowest looking dims if - // > 1 - unsigned lStride = - _size[4] * _size[3] * - _size[2] * _size[1] * - _size[0] * nbyper; - unsigned mStride = _size[5] * lStride; - - for(int m = 0; m < _size[6]; m++) + // as per ITK bug 0007485 + // NIfTI is lower triangular, ITK is upper triangular. + // i.e. if a symmetric matrix is + // a b c + // b d e + // c e f + // ITK stores it a b c d e f, but NIfTI is a b d c e f + // so on read, step sequentially through the source vector, but + // reverse the order of vec[2] and vec[3] + int *vecOrder; + if(this->GetPixelType() == ImageIOBase::DIFFUSIONTENSOR3D || + this->GetPixelType() == ImageIOBase::SYMMETRICSECONDRANKTENSOR) + { + vecOrder = UpperToLowerOrder(SymMatDim(numComponents)); + } + else { - for(int l = 0; l < _size[5]; l++) + vecOrder = new int[numComponents]; + for(unsigned i = 0; i < numComponents; i++) { - // distance between start of scalar images - // scalarPtr[0] = start of first scalar image - // scalarPtr[1] = start of second scalar image etc - unsigned vecStride = _size[0] * _size[1] * - _size[2] * _size[3]; - for(unsigned i = 0; i < numComponents; i++) - { - scalarPtr[i] = - tobuffer + - (l * lStride) + - (m * mStride) + - (vecStride * nbyper * i); - } - const char *from = frombuf + (l * lStride) + - (m * mStride); - for(unsigned i = 0; i < (vecStride * numComponents); i++) + vecOrder[i] = i; + } + } + for(int t = 0; t < this->m_NiftiImage->dim[4]; t++) + { + for(int z = 0; z < this->m_NiftiImage->dim[3]; z++) + { + for(int y = 0; y < this->m_NiftiImage->dim[2]; y++) { - memcpy(scalarPtr[i % numComponents], - from,nbyper); - from += nbyper; - scalarPtr[i % numComponents] += nbyper; + for(int x = 0; x < this->m_NiftiImage->dim[1]; x++) + { + for(unsigned int c=0;c< numComponents; c++) + { + const unsigned int nifti_index=(c*seriesdist+volumedist*t + slicedist*z + rowdist*y + x)*this->m_NiftiImage->nbyper; + const unsigned int itk_index=((volumedist*t + slicedist*z + rowdist*y + x)*numComponents + vecOrder[c])*this->m_NiftiImage->nbyper; + memcpy(nifti_buf+nifti_index,itkbuf+itk_index,this->m_NiftiImage->nbyper); + } + } } } } - delete [] scalarPtr; + delete [] vecOrder; dumpdata(buffer); dumpdata(tobuffer); //Need a const cast here so that we don't have to copy the memory for //writing. - this->m_NiftiImage->data=(void *)tobuffer; + this->m_NiftiImage->data=(void *)nifti_buf; nifti_image_write(this->m_NiftiImage); this->m_NiftiImage->data = 0; // if left pointing to data buffer - delete [] tobuffer; + delete [] nifti_buf; } } } // end namespace itk diff --git a/Utilities/ITK/Code/IO/itkNiftiImageIO.h b/Utilities/ITK/Code/IO/itkNiftiImageIO.h index 4c05fb0d2c..9ad8d8f09b 100644 --- a/Utilities/ITK/Code/IO/itkNiftiImageIO.h +++ b/Utilities/ITK/Code/IO/itkNiftiImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNiftiImageIO.h,v $ Language: C++ - Date: $Date: 2008-03-04 03:07:42 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-25 12:25:44 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -102,7 +102,7 @@ public: * specified by the Mayo Clinic BIR laboratory. By default this is set to false. */ itkSetMacro(LegacyAnalyze75Mode,bool); - itkGetMacro(LegacyAnalyze75Mode,bool); + itkGetConstMacro(LegacyAnalyze75Mode,bool); protected: NiftiImageIO(); diff --git a/Utilities/ITK/Code/IO/itkNumericSeriesFileNames.h b/Utilities/ITK/Code/IO/itkNumericSeriesFileNames.h index bd2f73f806..2b5a6a2db9 100644 --- a/Utilities/ITK/Code/IO/itkNumericSeriesFileNames.h +++ b/Utilities/ITK/Code/IO/itkNumericSeriesFileNames.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNumericSeriesFileNames.h,v $ Language: C++ - Date: $Date: 2007-03-22 14:28:51 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:25:44 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -62,16 +62,16 @@ public: /** Use this method to set the starting index of the numeric series. * The default value is 1. */ itkSetMacro(StartIndex,unsigned long); - itkGetMacro(StartIndex,unsigned long); + itkGetConstMacro(StartIndex,unsigned long); /** Set the end index of the numeric series. The default is 1. */ itkSetMacro(EndIndex,unsigned long); - itkGetMacro(EndIndex,unsigned long); + itkGetConstMacro(EndIndex,unsigned long); /** Set the increment of the index of the numeric series. The * default value is 1. */ itkSetMacro(IncrementIndex,unsigned long); - itkGetMacro(IncrementIndex,unsigned long); + itkGetConstMacro(IncrementIndex,unsigned long); /** The format string used to generate the series. Different subclasses * require different characteristics of this string. For example, the diff --git a/Utilities/ITK/Code/IO/itkPNGImageIO.h b/Utilities/ITK/Code/IO/itkPNGImageIO.h index f297903347..29bbce2ebe 100644 --- a/Utilities/ITK/Code/IO/itkPNGImageIO.h +++ b/Utilities/ITK/Code/IO/itkPNGImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPNGImageIO.h,v $ Language: C++ - Date: $Date: 2007-08-13 21:39:37 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-25 12:25:44 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -50,7 +50,7 @@ public: /** Set/Get the level of compression for the output images. * 0-9; 0 = none, 9 = maximum. */ itkSetMacro(CompressionLevel, int); - itkGetMacro(CompressionLevel, int); + itkGetConstMacro(CompressionLevel, int); /*-------- This part of the interface deals with reading data. ------ */ diff --git a/Utilities/ITK/Code/IO/itkRawImageIO.h b/Utilities/ITK/Code/IO/itkRawImageIO.h index 500d8240c9..f99289f86a 100644 --- a/Utilities/ITK/Code/IO/itkRawImageIO.h +++ b/Utilities/ITK/Code/IO/itkRawImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRawImageIO.h,v $ Language: C++ - Date: $Date: 2007-03-22 14:28:52 $ - Version: $Revision: 1.33 $ + Date: $Date: 2009-04-25 12:25:45 $ + Version: $Revision: 1.34 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -80,7 +80,7 @@ public: * each file contains one "slice". If three, each file will contain one * "volume". */ itkSetMacro(FileDimensionality, unsigned long); - itkGetMacro(FileDimensionality, unsigned long); + itkGetConstMacro(FileDimensionality, unsigned long); /** The different types of ImageIO's can support data of varying * dimensionality. For example, some file formats are strictly 2D diff --git a/Utilities/ITK/Code/IO/itkRegularExpressionSeriesFileNames.cxx b/Utilities/ITK/Code/IO/itkRegularExpressionSeriesFileNames.cxx index feaae27815..e48d2ebd1f 100644 --- a/Utilities/ITK/Code/IO/itkRegularExpressionSeriesFileNames.cxx +++ b/Utilities/ITK/Code/IO/itkRegularExpressionSeriesFileNames.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegularExpressionSeriesFileNames.cxx,v $ Language: C++ - Date: $Date: 2007-03-29 18:39:28 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-05 10:56:48 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,8 @@ #endif #include <vector> -#include <string> +#include <string.h> +#include <stdlib.h> #include <algorithm> #include <itksys/SystemTools.hxx> diff --git a/Utilities/ITK/Code/IO/itkRegularExpressionSeriesFileNames.h b/Utilities/ITK/Code/IO/itkRegularExpressionSeriesFileNames.h index 70c8dfcfa7..9b95e85e75 100644 --- a/Utilities/ITK/Code/IO/itkRegularExpressionSeriesFileNames.h +++ b/Utilities/ITK/Code/IO/itkRegularExpressionSeriesFileNames.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegularExpressionSeriesFileNames.h,v $ Language: C++ - Date: $Date: 2007-03-22 14:28:52 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-25 12:25:45 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,13 +95,13 @@ public: /** The index of the submatch that will be used to sort the * matches. */ itkSetMacro(SubMatch, unsigned int); - itkGetMacro(SubMatch, unsigned int); + itkGetConstMacro(SubMatch, unsigned int); /** NumericSortOn changes the sort of the submatch field to a * numeric sort. NumericSortOff is the default, and sorts the * submatch alphabetically. */ itkSetMacro(NumericSort,bool); - itkGetMacro(NumericSort,bool); + itkGetConstMacro(NumericSort,bool); itkBooleanMacro(NumericSort); /** Returns a vector containing the series' file names. The file diff --git a/Utilities/ITK/Code/IO/itkSiemensVisionImageIO.cxx b/Utilities/ITK/Code/IO/itkSiemensVisionImageIO.cxx index 2a544e4566..4f4608134c 100644 --- a/Utilities/ITK/Code/IO/itkSiemensVisionImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkSiemensVisionImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSiemensVisionImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-05-13 18:46:18 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-05 23:09:19 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -211,7 +211,7 @@ GEImageHeader *SiemensVisionImageIO::ReadHeader(const char *FileNameToRead) if (strcmp(tmpStr, "Cor") == 0) { - if (fabs(atof(tmpStr4))<= 45.0) + if (vcl_fabs(atof(tmpStr4))<= 45.0) { //hdr->imagePlane = itk::IOCommon::ITK_ANALYZE_ORIENTATION_IRP_CORONAL; hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RSP; @@ -232,7 +232,7 @@ GEImageHeader *SiemensVisionImageIO::ReadHeader(const char *FileNameToRead) } else if (strcmp(tmpStr, "Sag") == 0) { - if (fabs(atof(tmpStr4))<= 45.0) + if (vcl_fabs(atof(tmpStr4))<= 45.0) { //hdr->imagePlane = itk::SpatialOrientation::ITK_ANALYZE_ORIENTATION_IRP_SAGITTAL; hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_AIR; @@ -253,7 +253,7 @@ GEImageHeader *SiemensVisionImageIO::ReadHeader(const char *FileNameToRead) } else { - if (fabs(atof(tmpStr4))<= 45.0) + if (vcl_fabs(atof(tmpStr4))<= 45.0) { //hdr->imagePlane = itk::SpatialOrientation::ITK_ANALYZE_ORIENTATION_IRP_TRANSVERSE; hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI; diff --git a/Utilities/ITK/Code/IO/itkSpatialObjectWriter.h b/Utilities/ITK/Code/IO/itkSpatialObjectWriter.h index 0f3e365893..ae2e36bb98 100644 --- a/Utilities/ITK/Code/IO/itkSpatialObjectWriter.h +++ b/Utilities/ITK/Code/IO/itkSpatialObjectWriter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectWriter.h,v $ Language: C++ - Date: $Date: 2009-01-16 11:37:57 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-25 12:25:45 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -70,14 +70,14 @@ public: void SetInput(SceneType * input){m_Scene=input;} itkSetMacro(BinaryPoints,bool); - itkGetMacro(BinaryPoints,bool); + itkGetConstMacro(BinaryPoints,bool); void SetTransformPrecision(unsigned int precision); unsigned int GetTransformPrecision(); /** Set/Get if the images should be written in a different file */ itkSetMacro(WriteImagesInSeparateFile,bool); - itkGetMacro(WriteImagesInSeparateFile,bool); + itkGetConstMacro(WriteImagesInSeparateFile,bool); protected: diff --git a/Utilities/ITK/Code/IO/itkStimulateImageIO.cxx b/Utilities/ITK/Code/IO/itkStimulateImageIO.cxx index bb1a2b0a4c..15308d2a5e 100755 --- a/Utilities/ITK/Code/IO/itkStimulateImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkStimulateImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkStimulateImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-05-13 18:46:18 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-03-23 16:50:04 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,6 +21,7 @@ #include <stdio.h> #include <string.h> #include <itksys/SystemTools.hxx> +#include <itksys/RegularExpression.hxx> #include "itkByteSwapper.h" namespace itk @@ -199,6 +200,11 @@ void StimulateImageIO::Read(void* buffer) if( !OpenStimulateFileForReading( file_data, m_DataFileName.c_str()) ) { + itkExceptionMacro("StimulateImageIO could not open file: " + << m_DataFileName << " for reading." + << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); return; } @@ -207,7 +213,8 @@ void StimulateImageIO::Read(void* buffer) itkExceptionMacro(<<"Read failed: Wanted " << this->GetImageSizeInBytes() << " bytes, but read " - << file_data.gcount() << " bytes."); + << file_data.gcount() << " bytes." + << " from file " << m_DataFileName ); } //byte swapping depending on pixel type: @@ -243,11 +250,20 @@ void StimulateImageIO::InternalReadImageInformation(std::ifstream& file) std::string text; //read .sdt file (header) + if ( ! this->OpenStimulateFileForReading(file, m_FileName.c_str()) ) { - itkExceptionMacro(<< "Cannot read requested file"); + itkExceptionMacro("StimulateImageIO could not open sdt file: " + << m_FileName << " for reading." + << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError()); } + // re open in ascii mode + file.close(); + file.open( m_FileName.c_str(), std::ios::in ); + //extract dimensions, spacing, origin unsigned int dim; unsigned int dims[4]; @@ -272,7 +288,6 @@ void StimulateImageIO::InternalReadImageInformation(std::ifstream& file) //char fidName[256] = ""; //char orient[256] = ""; - char datafilename[256] = ""; bool fov_specified = false; bool origin_specified = false; @@ -433,10 +448,15 @@ void StimulateImageIO::InternalReadImageInformation(std::ifstream& file) //not documented itkDebugMacro(<<"mapTypeName was specified"); } - else if ( text.find("stimFileName") < text.length()) + else if ( text.find("stimFileName:") < text.length()) { //file data name is explicitely specified - sscanf(line, "%*s %s", datafilename); + std::string datafilename; + // Remove leading and trailing blanks + itksys::RegularExpression regexp("stimFileName:[ ]*(.*)[ ]*$"); + regexp.find(text); + datafilename = regexp.match(1); + //if the data filename has a directory specified, use it as is, //otherwise prepend the path of the .spr file. std::string datafilenamePath = diff --git a/Utilities/ITK/Code/IO/itkTIFFImageIO.cxx b/Utilities/ITK/Code/IO/itkTIFFImageIO.cxx index e8381fda79..042dc49643 100644 --- a/Utilities/ITK/Code/IO/itkTIFFImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkTIFFImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTIFFImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-09-13 21:11:48 $ - Version: $Revision: 1.64 $ + Date: $Date: 2009-04-05 10:56:48 $ + Version: $Revision: 1.65 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,6 +23,8 @@ #include "itkRGBAPixel.h" #include <itksys/SystemTools.hxx> #include <stdio.h> +#include <stdlib.h> +#include <string.h> #include <sys/stat.h> diff --git a/Utilities/ITK/Code/IO/itkTransformFileWriter.h b/Utilities/ITK/Code/IO/itkTransformFileWriter.h index 2bbc617cb6..a6a09ea8aa 100644 --- a/Utilities/ITK/Code/IO/itkTransformFileWriter.h +++ b/Utilities/ITK/Code/IO/itkTransformFileWriter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransformFileWriter.h,v $ Language: C++ - Date: $Date: 2009-01-16 11:37:58 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-25 12:25:45 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -76,7 +76,7 @@ public: /** Set/Get the precision of the writing */ itkSetMacro(Precision,unsigned int); - itkGetMacro(Precision,unsigned int); + itkGetConstMacro(Precision,unsigned int); /** Write out the transform */ void Update(); diff --git a/Utilities/ITK/Code/IO/itkVTKImageIO.cxx b/Utilities/ITK/Code/IO/itkVTKImageIO.cxx index 68949bdd18..8a67f230ad 100644 --- a/Utilities/ITK/Code/IO/itkVTKImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkVTKImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVTKImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-10-10 14:30:00 $ - Version: $Revision: 1.46 $ + Date: $Date: 2009-04-05 10:56:48 $ + Version: $Revision: 1.48 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,6 +23,7 @@ #include <itksys/ios/sstream> #include <stdio.h> +#include <string.h> namespace itk { @@ -64,7 +65,7 @@ bool VTKImageIO::OpenVTKFileForReading(std::ifstream& os, #if defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) const int openMode = std::ios::in|std::ios::binary; #elif ( defined(__GNUC__) && __GNUC__ >= 3 ) || defined (__MWERKS__) || defined (__INTEL_COMPILER) || defined (__MINGW32__) || defined(__CYGWIN__) - const std::ios_base::openmode openMode = std::ios::in; + const std::ios_base::openmode openMode = std::ios::in|std::ios::binary; #else const int openMode = std::ios::in; #endif @@ -106,7 +107,7 @@ bool VTKImageIO::OpenVTKFileForWriting(std::ofstream& os, #if defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) const int openMode = std::ios::out|std::ios::binary; #elif (defined(__GNUC__) && __GNUC__ >= 3) || defined (__MWERKS__) || defined (__INTEL_COMPILER) || defined (__MINGW32__) || defined(__CYGWIN__) - const std::ios_base::openmode openMode =std::ios::out; + const std::ios_base::openmode openMode =std::ios::out|std::ios::binary; #else const int openMode = std::ios::out; #endif diff --git a/Utilities/ITK/Code/Numerics/CMakeLists.txt b/Utilities/ITK/Code/Numerics/CMakeLists.txt index 329e91ab26..ba91cc2465 100644 --- a/Utilities/ITK/Code/Numerics/CMakeLists.txt +++ b/Utilities/ITK/Code/Numerics/CMakeLists.txt @@ -1,4 +1,9 @@ -SUBDIRS(Statistics FEM NeuralNetworks) +# Conditionally compile either the new or the old statistics framework. +IF (NOT ITK_USE_REVIEW_STATISTICS) + SUBDIRS (Statistics) +ENDIF (NOT ITK_USE_REVIEW_STATISTICS) + +SUBDIRS(FEM NeuralNetworks) ADD_LIBRARY(ITKNumerics itkAmoebaOptimizer.cxx diff --git a/Utilities/ITK/Code/Numerics/FEM/itkFEMElement2DC0LinearQuadrilateral.cxx b/Utilities/ITK/Code/Numerics/FEM/itkFEMElement2DC0LinearQuadrilateral.cxx index aa1dbadf04..82b0232add 100644 --- a/Utilities/ITK/Code/Numerics/FEM/itkFEMElement2DC0LinearQuadrilateral.cxx +++ b/Utilities/ITK/Code/Numerics/FEM/itkFEMElement2DC0LinearQuadrilateral.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFEMElement2DC0LinearQuadrilateral.cxx,v $ Language: C++ - Date: $Date: 2009-01-28 21:19:16 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-05 10:56:50 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -158,7 +158,7 @@ Element2DC0LinearQuadrilateral ce = (dx * yce) - (dy * xce); cn = (dx * ycn) - (dy * xcn); - localPt[0] = (2 * ce) / (-sqrt((be * be) - (2 * J1 * ce)) - be); + localPt[0] = (2 * ce) / (-vcl_sqrt((be * be) - (2 * J1 * ce)) - be); localPt[1] = (2 * cn) / ( vcl_sqrt((bn * bn) + (2 * J2 * cn)) - bn); bool isInside=true; diff --git a/Utilities/ITK/Code/Numerics/FEM/itkFEMObjectFactory.h b/Utilities/ITK/Code/Numerics/FEM/itkFEMObjectFactory.h index 18076857bc..de53e0cf44 100644 --- a/Utilities/ITK/Code/Numerics/FEM/itkFEMObjectFactory.h +++ b/Utilities/ITK/Code/Numerics/FEM/itkFEMObjectFactory.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFEMObjectFactory.h,v $ Language: C++ - Date: $Date: 2009-01-30 21:10:19 $ - Version: $Revision: 1.20 $ + Date: $Date: 2009-04-05 10:56:50 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,6 +21,7 @@ #include <string> #include <vector> #include <cstdlib> +#include <stdlib.h> namespace itk { namespace fem { diff --git a/Utilities/ITK/Code/Numerics/FEM/itkFEMSolverCrankNicolson.cxx b/Utilities/ITK/Code/Numerics/FEM/itkFEMSolverCrankNicolson.cxx index 0176e5232a..45df55d602 100644 --- a/Utilities/ITK/Code/Numerics/FEM/itkFEMSolverCrankNicolson.cxx +++ b/Utilities/ITK/Code/Numerics/FEM/itkFEMSolverCrankNicolson.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFEMSolverCrankNicolson.cxx,v $ Language: C++ - Date: $Date: 2009-01-30 21:53:03 $ - Version: $Revision: 1.39 $ + Date: $Date: 2009-04-05 23:09:19 $ + Version: $Revision: 1.40 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -292,7 +292,7 @@ void SolverCrankNicolson::FindBracketingTriplet(Float* a, Float* b, Float* c) { r=(bx-ax)*(fb-fc); q=(bx-cx)*(fb-fa); - Float denom=(2.0*GSSign(GSMax(fabs(q-r),Tiny),q-r)); + Float denom=(2.0*GSSign(GSMax(vcl_fabs(q-r),Tiny),q-r)); u=(bx)-((bx-cx)*q-(bx-ax)*r)/denom; ulim=bx + Glimit*(cx-bx); if ((bx-u)*(u-cx) > 0.0) @@ -380,14 +380,14 @@ Element::Float SolverCrankNicolson::BrentsMethod(Float tol,unsigned int MaxIters { xm=0.5*(a+b); tol2=2.0*(tol1=tol*vcl_fabs(x)+ZEPS); - if (fabs(x-xm) <= (tol2-0.5*(b-a))) + if (vcl_fabs(x-xm) <= (tol2-0.5*(b-a))) { xmin=x; SetEnergyToMin(xmin); return fx; } - if (fabs(e) > tol1) + if (vcl_fabs(e) > tol1) { r=(x-w)*(fx-fv); q=(x-v)*(fx-fw); @@ -397,7 +397,7 @@ Element::Float SolverCrankNicolson::BrentsMethod(Float tol,unsigned int MaxIters q=vcl_fabs(q); etemp=e; e=d; - if (fabs(p) >= vcl_fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) + if (vcl_fabs(p) >= vcl_fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) d=CGOLD*(e=(x>=xm ? a-x : b-x)); else { @@ -412,7 +412,7 @@ Element::Float SolverCrankNicolson::BrentsMethod(Float tol,unsigned int MaxIters d=CGOLD*(e=(x>= xm ? a-x : b-x)); } - u=(fabs(d) >= tol1 ? x+d : x + GSSign(tol1,d)); + u=(vcl_fabs(d) >= tol1 ? x+d : x + GSSign(tol1,d)); fu=vcl_fabs(EvaluateResidual(u)); if (fu <= fx) { @@ -460,7 +460,7 @@ Element::Float SolverCrankNicolson::GoldenSection(Float tol,unsigned int MaxIter x0=ax; x3=cx; - if (fabs(cx-bx) > vcl_fabs(bx-ax)) + if (vcl_fabs(cx-bx) > vcl_fabs(bx-ax)) { x1=bx; x2=bx+C*(cx-bx); @@ -473,7 +473,7 @@ Element::Float SolverCrankNicolson::GoldenSection(Float tol,unsigned int MaxIter f1=vcl_fabs(EvaluateResidual(x1)); f2=vcl_fabs(EvaluateResidual(x2)); unsigned int iters=0; - while (fabs(x3-x0) > tol*(fabs(x1)+vcl_fabs(x2)) && iters < MaxIters) + while (vcl_fabs(x3-x0) > tol*(vcl_fabs(x1)+vcl_fabs(x2)) && iters < MaxIters) { iters++; if (f2 < f1) @@ -633,7 +633,7 @@ void SolverCrankNicolson::AddToDisplacements(Float optimum) { maxs2=CurrentSolution; } - if (fabs(CurrentSolution) > absmax) absmax=vcl_fabs(CurrentSolution); + if (vcl_fabs(CurrentSolution) > absmax) absmax=vcl_fabs(CurrentSolution); // note: set rather than add - i.e. last solution of system not total solution #ifdef LOCE diff --git a/Utilities/ITK/Code/Numerics/NeuralNetworks/itkGaussianTransferFunction.txx b/Utilities/ITK/Code/Numerics/NeuralNetworks/itkGaussianTransferFunction.txx index e07077fa1c..a0e4363533 100644 --- a/Utilities/ITK/Code/Numerics/NeuralNetworks/itkGaussianTransferFunction.txx +++ b/Utilities/ITK/Code/Numerics/NeuralNetworks/itkGaussianTransferFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianTransferFunction.txx,v $ Language: C++ - Date: $Date: 2005-08-02 19:17:37 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-06 11:15:09 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -45,7 +45,7 @@ ScalarType GaussianTransferFunction<ScalarType> ::Evaluate(const ScalarType& input) const { - return static_cast<ScalarType>((exp(-1 * input * input))); + return static_cast<ScalarType>((vcl_exp(-1 * input * input))); } /** Evaluate derivatives function */ diff --git a/Utilities/ITK/Code/Numerics/NeuralNetworks/itkRBFLayer.h b/Utilities/ITK/Code/Numerics/NeuralNetworks/itkRBFLayer.h index 8fc05ba0b2..e029867284 100644 --- a/Utilities/ITK/Code/Numerics/NeuralNetworks/itkRBFLayer.h +++ b/Utilities/ITK/Code/Numerics/NeuralNetworks/itkRBFLayer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRBFLayer.h,v $ Language: C++ -Date: $Date: 2009-01-28 21:04:59 $ -Version: $Revision: 1.11 $ +Date: $Date: 2009-05-02 05:43:55 $ +Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,11 @@ PURPOSE. See the above copyright notices for more information. #include "itkObject.h" #include "itkMacro.h" #include "itkRadialBasisFunctionBase.h" +#ifdef ITK_USE_REVIEW_STATISTICS +#include "itkEuclideanDistanceMetric.h" +#else #include "itkEuclideanDistance.h" +#endif namespace itk { @@ -55,7 +59,11 @@ public: typedef typename Superclass::TransferFunctionInterfaceType TransferFunctionInterfaceType; //Distance Metric +#ifdef ITK_USE_REVIEW_STATISTICS + typedef EuclideanDistanceMetric<InternalVectorType> DistanceMetricType; +#else typedef EuclideanDistance<InternalVectorType> DistanceMetricType; +#endif typedef typename DistanceMetricType::Pointer DistanceMetricPointer; typedef RadialBasisFunctionBase<ValueType> RBFType; diff --git a/Utilities/ITK/Code/Numerics/NeuralNetworks/itkRBFNetwork.h b/Utilities/ITK/Code/Numerics/NeuralNetworks/itkRBFNetwork.h index f6d6084543..a17f4b8690 100644 --- a/Utilities/ITK/Code/Numerics/NeuralNetworks/itkRBFNetwork.h +++ b/Utilities/ITK/Code/Numerics/NeuralNetworks/itkRBFNetwork.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRBFNetwork.h,v $ Language: C++ -Date: $Date: 2009-01-28 21:04:59 $ -Version: $Revision: 1.9 $ +Date: $Date: 2009-05-02 05:43:55 $ +Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,11 @@ PURPOSE. See the above copyright notices for more information. #include "itkSymmetricSigmoidTransferFunction.h" #include "itkTanHTransferFunction.h" +#ifdef ITK_USE_REVIEW_STATISTICS +#include "itkEuclideanDistanceMetric.h" +#else #include "itkEuclideanDistance.h" +#endif #include "itkRBFLayer.h" namespace itk @@ -65,7 +69,11 @@ public: // Specializations for RBF Networks typedef Array<ValueType> ArrayType; +#ifdef ITK_USE_REVIEW_STATISTICS + typedef EuclideanDistanceMetric<ArrayType> DistanceMetricType; +#else typedef EuclideanDistance<ArrayType> DistanceMetricType; +#endif typedef RadialBasisFunctionBase<ValueType> RBFTransferFunctionType; typedef RBFLayer<TMeasurementVector, TTargetVector> HiddenLayerType; diff --git a/Utilities/ITK/Code/Numerics/Statistics/CMakeLists.txt b/Utilities/ITK/Code/Numerics/Statistics/CMakeLists.txt index 632febb0a7..8c53e54ffa 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/CMakeLists.txt +++ b/Utilities/ITK/Code/Numerics/Statistics/CMakeLists.txt @@ -8,31 +8,9 @@ ADD_LIBRARY(ITKStatistics itkGaussianDistribution.cxx itkTDistribution.cxx itkChiSquareDistribution.cxx + ) - # from SLATEC/FNLIB - d1mach.c - d9lgmc.c - d9gmit.c - d9lgic.c - d9lgit.c - dbetai.c - dcsevl.c - dgami.c - dgamit.c - dgamlm.c - dgamma.c - dgamr.c - dlbeta.c - dlgams.c - dlngam.c - dlnrel.c - initds.c - xermsg.c - d_int.c - d_mod.c - ) - -TARGET_LINK_LIBRARIES(ITKStatistics ITKCommon) +TARGET_LINK_LIBRARIES(ITKStatistics ITKCommon itkNetlibSlatec) IF(ITK_LIBRARY_PROPERTIES) SET_TARGET_PROPERTIES(ITKStatistics PROPERTIES ${ITK_LIBRARY_PROPERTIES}) diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkChiSquareDistribution.cxx b/Utilities/ITK/Code/Numerics/Statistics/itkChiSquareDistribution.cxx index 08554241c0..156e0dc7f7 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkChiSquareDistribution.cxx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkChiSquareDistribution.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkChiSquareDistribution.cxx,v $ Language: C++ - Date: $Date: 2007-02-24 13:47:32 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-06 11:15:09 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -71,14 +71,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 1; @@ -94,8 +94,8 @@ ChiSquareDistribution if (x >= 0.0) { - pdf = exp(-0.5*x) * pow(x, dofon2 - 1.0) - / (pow(2.0, dofon2) * dgamma_(&dofon2)); + pdf = vcl_exp(-0.5*x) * vcl_pow(x, dofon2 - 1.0) + / (vcl_pow(2.0, dofon2) * dgamma_(&dofon2)); } return pdf; @@ -112,14 +112,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << "ChiSquareDistribution: " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; @@ -154,14 +154,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << "ChiSquareDistribution: " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; @@ -189,7 +189,7 @@ ChiSquareDistribution nx = GaussianDistribution::InverseCDF(p); double f = 2.0 / (9.0*dof); - x = dof*pow(1.0 - f + nx*sqrt(f), 3.0); + x = dof*vcl_pow(1.0 - f + nx*vcl_sqrt(f), 3.0); // The approximation above is only accurate for large degrees of @@ -244,14 +244,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << "ChiSquareDistribution: " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; @@ -267,14 +267,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -289,14 +289,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -319,14 +319,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -341,14 +341,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -372,14 +372,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -394,14 +394,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -424,14 +424,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return NumericTraits<double>::quiet_NaN(); @@ -447,14 +447,14 @@ ChiSquareDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return NumericTraits<double>::quiet_NaN(); diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkCovarianceCalculator.h b/Utilities/ITK/Code/Numerics/Statistics/itkCovarianceCalculator.h index c134cbe235..7e422b0d9e 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkCovarianceCalculator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkCovarianceCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCovarianceCalculator.h,v $ Language: C++ - Date: $Date: 2008-06-30 15:34:57 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-04 15:23:43 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,8 +23,8 @@ #include "itkArray.h" #include "itkVariableSizeMatrix.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class CovarianceCalculator * \brief Calculates the covariance matrix of the target sample data. @@ -55,10 +55,10 @@ class CovarianceCalculator : { public: /** Standard class typedefs. */ - typedef CovarianceCalculator Self; + typedef CovarianceCalculator Self; typedef SampleAlgorithmBase< TSample > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(CovarianceCalculator, SampleAlgorithmBase); @@ -103,8 +103,8 @@ protected: void ComputeCovarianceWithoutGivenMean( void ); private: - MeanType* m_Mean; - MeanType* m_InternalMean; + MeanType* m_Mean; + MeanType* m_InternalMean; OutputType m_Output; }; // end of class @@ -116,4 +116,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkCovarianceCalculator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkCovarianceCalculator.txx index 331c3ada3f..be9f27c421 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkCovarianceCalculator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkCovarianceCalculator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCovarianceCalculator.txx,v $ Language: C++ - Date: $Date: 2008-06-27 12:57:43 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-03-04 15:23:43 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkCovarianceCalculator.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > CovarianceCalculator< TSample > @@ -36,8 +36,8 @@ CovarianceCalculator< TSample > { if ( m_InternalMean != 0 ) { - delete m_InternalMean ; - m_InternalMean = 0 ; + delete m_InternalMean; + m_InternalMean = 0; } } @@ -52,20 +52,20 @@ CovarianceCalculator< TSample > if ( m_Mean != 0) { - os << indent << "Mean: [" << *m_Mean << "]" << std::endl ; + os << indent << "Mean: [" << *m_Mean << "]" << std::endl; } else { - os << indent << "Mean: not set" << std::endl ; + os << indent << "Mean: not set" << std::endl; } if ( m_InternalMean != 0) { - os << indent << "Internal Mean: [" << *m_InternalMean << "]" << std::endl ; + os << indent << "Internal Mean: [" << *m_InternalMean << "]" << std::endl; } else { - os << indent << "Internal Mean: not used" << std::endl ; + os << indent << "Internal Mean: not used" << std::endl; } } @@ -79,8 +79,8 @@ CovarianceCalculator< TSample > if ( m_InternalMean != mean && m_InternalMean != 0 ) { - delete m_InternalMean ; - m_InternalMean = 0 ; + delete m_InternalMean; + m_InternalMean = 0; } if( mean ) @@ -92,7 +92,7 @@ CovarianceCalculator< TSample > { this->SetMeasurementVectorSize( measurementVectorLength ); } } - m_Mean = mean ; + m_Mean = mean; } @@ -103,11 +103,11 @@ CovarianceCalculator< TSample > { if ( m_InternalMean != 0 ) { - return m_InternalMean ; + return m_InternalMean; } else { - return m_Mean ; + return m_Mean; } } @@ -116,7 +116,7 @@ const typename CovarianceCalculator< TSample >::OutputType* CovarianceCalculator< TSample > ::GetOutput( void ) const { - return & m_Output ; + return & m_Output; } template< class TSample > @@ -149,24 +149,24 @@ CovarianceCalculator< TSample > frequency = iter.GetFrequency(); totalFrequency += frequency; measurements = iter.GetMeasurementVector(); - for (i = 0 ; i < measurementVectorSize ; i++) + for (i = 0; i < measurementVectorSize; i++) { diff[i] = measurements[i] - (*m_Mean)[i]; } - for ( row = 0; row < measurementVectorSize ; row++) + for ( row = 0; row < measurementVectorSize; row++) { - for ( col = 0; col < row + 1 ; col++) + for ( col = 0; col < row + 1; col++) { m_Output(row,col) += frequency * diff[row] * diff[col]; } } - ++iter ; + ++iter; } // fills the upper triangle using the lower triangle - for (row = 1 ; row < measurementVectorSize ; row++) + for (row = 1; row < measurementVectorSize; row++) { - for (col = 0 ; col < row ; col++) + for (col = 0; col < row; col++) { m_Output(col, row) = m_Output(row, col); @@ -174,14 +174,13 @@ CovarianceCalculator< TSample > } if ( totalFrequency > 1e-6 ) - { + { m_Output /= ( totalFrequency - 1.0f ); - } + } else - { + { m_Output.Fill( 0.0f ); - } - + } } template< class TSample > @@ -211,42 +210,41 @@ CovarianceCalculator< TSample > { frequency = iter.GetFrequency(); if ( frequency == 0 ) - { + { ++iter; continue; - } + } totalFrequency += frequency; measurements = iter.GetMeasurementVector(); - for ( i = 0 ; i < measurementVectorSize ; ++i ) + for ( i = 0; i < measurementVectorSize; ++i ) { diff[i] = measurements[i] - (*m_InternalMean)[i]; } // updates the mean vector double tempWeight = frequency / totalFrequency; - for ( i = 0 ; i < measurementVectorSize ; ++i ) + for ( i = 0; i < measurementVectorSize; ++i ) { (*m_InternalMean)[i] += tempWeight * diff[i]; } // updates the covariance matrix tempWeight = tempWeight * ( totalFrequency - frequency ); - for ( row = 0; row < measurementVectorSize ; row++ ) + for ( row = 0; row < measurementVectorSize; row++ ) { - for ( col = 0; col < row + 1 ; col++) + for ( col = 0; col < row + 1; col++) { - m_Output(row,col) += - tempWeight * diff[row] * diff[col]; + m_Output(row,col) += tempWeight * diff[row] * diff[col]; } } ++iter; } // fills the upper triangle using the lower triangle - for (row = 1 ; row < measurementVectorSize ; row++) + for (row = 1; row < measurementVectorSize; row++) { - for (col = 0 ; col < row ; col++) + for (col = 0; col < row; col++) { m_Output(col, row) = m_Output(row, col); @@ -254,13 +252,13 @@ CovarianceCalculator< TSample > } if ( totalFrequency > 1e-6 ) - { + { m_Output /= ( totalFrequency - 1.0f ); - } + } else - { + { m_Output.Fill( 0.0f ); - } + } } @@ -293,4 +291,3 @@ CovarianceCalculator< TSample > } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx b/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx index 4423f4a9e8..851b8b3157 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDenseFrequencyContainer.cxx,v $ Language: C++ - Date: $Date: 2006-01-13 16:52:14 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-04 15:23:44 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,15 +22,15 @@ namespace Statistics{ DenseFrequencyContainer ::DenseFrequencyContainer() { - m_FrequencyContainer = FrequencyContainerType::New() ; - m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero ; + m_FrequencyContainer = FrequencyContainerType::New(); + m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero; } void DenseFrequencyContainer ::Initialize(unsigned long length) { - m_FrequencyContainer->Reserve(length) ; + m_FrequencyContainer->Reserve(length); this->SetToZero(); } @@ -39,7 +39,7 @@ DenseFrequencyContainer ::SetToZero() { m_FrequencyContainer->Fill( NumericTraits< FrequencyType >::Zero ); - m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero ; + m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero; } bool @@ -50,9 +50,9 @@ DenseFrequencyContainer { return false; } - FrequencyType frequency = this->GetFrequency(id) ; - (*m_FrequencyContainer)[id] = value ; - m_TotalFrequency += (value - frequency) ; + FrequencyType frequency = this->GetFrequency(id); + (*m_FrequencyContainer)[id] = value; + m_TotalFrequency += (value - frequency); return true; } @@ -75,9 +75,9 @@ DenseFrequencyContainer { return false; } - FrequencyType frequency = this->GetFrequency(id) ; - (*m_FrequencyContainer)[id] = frequency + value ; - m_TotalFrequency += value ; + FrequencyType frequency = this->GetFrequency(id); + (*m_FrequencyContainer)[id] = frequency + value; + m_TotalFrequency += value; return true; } @@ -90,4 +90,3 @@ DenseFrequencyContainer } // end of namespace Statistics } // end of namespace itk - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.h b/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.h index 1d8023968a..3d4dbb4667 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDenseFrequencyContainer.h,v $ Language: C++ - Date: $Date: 2005-09-30 14:14:18 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-04 15:23:44 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,8 +23,8 @@ #include "itkValarrayImageContainer.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class DenseFrequencyContainer * \brief his class is a container for frequencies of bins in an histogram. @@ -43,8 +43,8 @@ class ITK_EXPORT DenseFrequencyContainer public: /** Standard class typedefs */ typedef DenseFrequencyContainer Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ @@ -54,30 +54,30 @@ public: itkNewMacro(Self); /** InstanceIdenfitifer type alias */ - typedef unsigned long InstanceIdentifier ; + typedef unsigned long InstanceIdentifier; /** Frequency type alias */ - typedef float FrequencyType ; + typedef float FrequencyType; - /** Total frequency type*/ - typedef NumericTraits<FrequencyType>::AccumulateType TotalFrequencyType ; + /** Total frequency type */ + typedef NumericTraits<FrequencyType>::AccumulateType TotalFrequencyType; /** Internal storage class typedefs */ typedef ValarrayImageContainer< InstanceIdentifier, FrequencyType > - FrequencyContainerType ; - typedef FrequencyContainerType::Pointer FrequencyContainerPointer ; + FrequencyContainerType; + typedef FrequencyContainerType::Pointer FrequencyContainerPointer; /** Calls the Initialize method of superclass to generate the offset table * and prepare the frequency container */ - void Initialize(unsigned long length) ; + void Initialize(unsigned long length); /** Calls the SetToZero method of superclass to initialize all the bins to Zero. * This should be done before starting to call the IncreaseFrequency method. */ - void SetToZero() ; + void SetToZero(); /** Sets the frequency of histogram using instance identifier. It returns * false when the Id is out of bounds. */ - bool SetFrequency(const InstanceIdentifier id, const FrequencyType value) ; + bool SetFrequency(const InstanceIdentifier id, const FrequencyType value); /** Increases the frequency of a bin specified by the InstanceIdentifier by * one. This function is convinient to create a histogram. It returns false @@ -87,30 +87,27 @@ public: /** Method to get the frequency of a bin from the histogram. It returns zero * when the Id is out of bounds. */ - FrequencyType GetFrequency(const InstanceIdentifier id) const ; + FrequencyType GetFrequency(const InstanceIdentifier id) const; /** Gets the sum of the frequencies */ TotalFrequencyType GetTotalFrequency() - { return m_TotalFrequency ; } + { return m_TotalFrequency; } protected: - DenseFrequencyContainer() ; + DenseFrequencyContainer(); virtual ~DenseFrequencyContainer() {} void PrintSelf(std::ostream& os, Indent indent) const; private: - DenseFrequencyContainer(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + DenseFrequencyContainer(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented /** Internal storage */ - FrequencyContainerPointer m_FrequencyContainer ; - TotalFrequencyType m_TotalFrequency ; -} ; // end of class + FrequencyContainerPointer m_FrequencyContainer; + TotalFrequencyType m_TotalFrequency; +}; // end of class } // end of namespace Statistics } // end of namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkDensityFunction.h b/Utilities/ITK/Code/Numerics/Statistics/itkDensityFunction.h index f474cd5cbb..bf9d77e1d0 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkDensityFunction.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkDensityFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDensityFunction.h,v $ Language: C++ - Date: $Date: 2006-02-24 16:57:21 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-04 15:23:46 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,8 +20,8 @@ #include "itkMembershipFunctionBase.h" #include "itkMeasurementVectorTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class DensityFunction * \brief DensityFunction class defines common interfaces for @@ -38,10 +38,10 @@ class ITK_EXPORT DensityFunction : { public: /** Standard class typedefs */ - typedef DensityFunction Self; - typedef MembershipFunctionBase< TMeasurementVector > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef DensityFunction Self; + typedef MembershipFunctionBase< TMeasurementVector > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Strandard macros */ itkTypeMacro(DensityFunction, MembershipFunctionBase); @@ -51,7 +51,7 @@ public: /** Method to get probability of an instance. The return value is the * value of the density function, not probability. */ - virtual double Evaluate(const TMeasurementVector &measurement) const = 0 ; + virtual double Evaluate(const TMeasurementVector &measurement) const = 0; protected: DensityFunction() {} @@ -63,14 +63,9 @@ protected: } private: -} ; // end of class +}; // end of class } // end of namespace Statistics } // end namespace itk #endif - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkDistanceMetric.h b/Utilities/ITK/Code/Numerics/Statistics/itkDistanceMetric.h index a6388ccefc..e350725754 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkDistanceMetric.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkDistanceMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDistanceMetric.h,v $ Language: C++ - Date: $Date: 2005-11-21 02:40:48 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-04 15:23:46 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,8 +20,8 @@ #include "itkMembershipFunctionBase.h" #include "itkArray.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class DistanceMetric * \brief this class declares common interfaces @@ -58,14 +58,15 @@ class ITK_EXPORT DistanceMetric : public MembershipFunctionBase< TVector > { public: /** Standard typedefs */ - typedef DistanceMetric Self; + typedef DistanceMetric Self; typedef MembershipFunctionBase< TVector > Superclass; - typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + typedef typename Superclass::MeasurementVectorSizeType + MeasurementVectorSizeType; /** Run-time type information (and related methods). */ itkTypeMacro(DistanceMetric, MembershipFunctionBase); - typedef Array< double > OriginType ; + typedef Array< double > OriginType; /** Set the length of each measurement vector. */ virtual void SetMeasurementVectorSize( const MeasurementVectorSizeType ); @@ -73,23 +74,23 @@ public: /** Sets the origin point that will be used for the single point * version Evaluate() function. This function is necessary part of * implementing MembershipFunctionBase's Evaluate() interface */ - void SetOrigin(const OriginType& x) ; - itkGetConstReferenceMacro(Origin, OriginType) ; + void SetOrigin(const OriginType& x); + itkGetConstReferenceMacro(Origin, OriginType); /** Gets the distance between the origin point and x. This function - * work with SetOrigin() function*/ - virtual double Evaluate(const TVector &x) const = 0 ; + * work with SetOrigin() function */ + virtual double Evaluate(const TVector &x) const = 0; /** Gets the distance between x1 and x2 points */ - virtual double Evaluate(const TVector &x1, const TVector &x2) const = 0 ; + virtual double Evaluate(const TVector &x1, const TVector &x2) const = 0; protected: DistanceMetric(); virtual ~DistanceMetric() {} void PrintSelf(std::ostream& os, Indent indent) const; - OriginType m_Origin ; -} ; // end of class + OriginType m_Origin; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -99,10 +100,3 @@ protected: #endif #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkDistanceMetric.txx b/Utilities/ITK/Code/Numerics/Statistics/itkDistanceMetric.txx index 97fc4556a9..c9e381f3ba 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkDistanceMetric.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkDistanceMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDistanceMetric.txx,v $ Language: C++ - Date: $Date: 2005-11-21 02:40:48 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-04 15:23:46 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkDistanceMetric.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TVector > DistanceMetric< TVector > @@ -42,7 +42,7 @@ DistanceMetric< TVector > << " each measurement vector."); } } - m_Origin = x ; + m_Origin = x; this->m_MeasurementVectorSize = x.Size(); this->Modified(); } @@ -81,10 +81,3 @@ DistanceMetric< TVector > } // end of namespace itk #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkDistanceToCentroidMembershipFunction.h b/Utilities/ITK/Code/Numerics/Statistics/itkDistanceToCentroidMembershipFunction.h index 105f47def3..32a5a2fd86 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkDistanceToCentroidMembershipFunction.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkDistanceToCentroidMembershipFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDistanceToCentroidMembershipFunction.h,v $ Language: C++ - Date: $Date: 2007-09-27 15:47:12 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-04 15:23:46 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,9 +26,8 @@ #include "itkMembershipFunctionBase.h" - -namespace itk{ - namespace Statistics{ +namespace itk { +namespace Statistics { /** \class DistanceToCentroidMembershipFunction * \brief class represents DistanceToCentroid Density Function. @@ -46,9 +45,9 @@ class ITK_EXPORT DistanceToCentroidMembershipFunction : public: /** Standard class typedefs */ typedef DistanceToCentroidMembershipFunction Self; - typedef MembershipFunctionBase< TVector > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef MembershipFunctionBase< TVector > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Strandard macros */ itkTypeMacro(DistanceToCentroidMembershipFunction, @@ -56,7 +55,7 @@ public: itkNewMacro(Self); /** Typedef alias for the measurement vectors */ - typedef TVector MeasurementVectorType ; + typedef TVector MeasurementVectorType; /** Typedef to represent the length of measurement vectors */ typedef typename Superclass::MeasurementVectorSizeType @@ -66,7 +65,7 @@ public: virtual void SetMeasurementVectorSize( const MeasurementVectorSizeType ); /** Method to set mean */ - void SetCentroid(const vnl_vector<double> ¢roid) ; + void SetCentroid(const vnl_vector<double> ¢roid); /** Method to get mean */ const vnl_vector<double> & GetCentroid() const; @@ -83,7 +82,7 @@ public: double Evaluate(const MeasurementVectorType &measurement) const; protected: - DistanceToCentroidMembershipFunction(void) ; + DistanceToCentroidMembershipFunction(void); virtual ~DistanceToCentroidMembershipFunction(void) {} void PrintSelf(std::ostream& os, Indent indent) const; @@ -94,7 +93,7 @@ private: int m_NumberOfSamples; }; - } // end of namespace Statistics +} // end of namespace Statistics } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkDistanceToCentroidMembershipFunction.txx b/Utilities/ITK/Code/Numerics/Statistics/itkDistanceToCentroidMembershipFunction.txx index c509ebe71d..8a3cde66e9 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkDistanceToCentroidMembershipFunction.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkDistanceToCentroidMembershipFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDistanceToCentroidMembershipFunction.txx,v $ Language: C++ - Date: $Date: 2005-11-21 02:40:48 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 15:23:46 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkDistanceToCentroidMembershipFunction.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template < class TVector > DistanceToCentroidMembershipFunction< TVector > @@ -73,7 +73,7 @@ const vnl_vector< double > & DistanceToCentroidMembershipFunction< TVector > ::GetCentroid() const { - return m_Centroid ; + return m_Centroid; } template < class TVector > @@ -95,7 +95,7 @@ DistanceToCentroidMembershipFunction< TVector > temp = vcl_sqrt( temp ); - return temp ; + return temp; } template < class TVector > @@ -109,7 +109,7 @@ DistanceToCentroidMembershipFunction< TVector > if ( this->m_MeasurementVectorSize && m_Centroid.size() == this->m_MeasurementVectorSize ) { - os << indent << "Centroid: [" ; + os << indent << "Centroid: ["; for (i=0; i+1 < m_Centroid.size(); i++) { os << m_Centroid[i] << ", "; @@ -118,7 +118,7 @@ DistanceToCentroidMembershipFunction< TVector > } else { - os << indent << "Centorid: not set or size doen't match." << std::endl ; + os << indent << "Centorid: not set or size doen't match." << std::endl; } os << indent << "Number of Samples: " << m_NumberOfSamples << std::endl; @@ -127,6 +127,4 @@ DistanceToCentroidMembershipFunction< TVector > } // end namespace Statistics } // end of namespace itk - - #endif diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkEuclideanDistance.h b/Utilities/ITK/Code/Numerics/Statistics/itkEuclideanDistance.h index cf10b9bffb..09099ce75e 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkEuclideanDistance.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkEuclideanDistance.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEuclideanDistance.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:55 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-04 15:23:46 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include "itkDistanceMetric.h" #include "itkMeasurementVectorTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class EuclideanDistance * \brief Euclidean distance function. @@ -54,39 +54,40 @@ class ITK_EXPORT EuclideanDistance : { public: /** Standard "Self" typedef. */ - typedef EuclideanDistance Self; + typedef EuclideanDistance Self; typedef DistanceMetric< TVector > Superclass; - typedef SmartPointer< Self > Pointer ; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; /** Run-time type information (and related methods). */ itkTypeMacro(EuclideanDistance, DistanceMetric); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** Type of the component of a vector */ - typedef typename TVector::ValueType ValueType ; + typedef typename TVector::ValueType ValueType; /** Gets the distance between the origin and x */ - double Evaluate(const TVector &x) const ; + double Evaluate(const TVector &x) const; /** Gets the distance between x1 and x2 */ - double Evaluate(const TVector &x1, const TVector &x2) const ; + double Evaluate(const TVector &x1, const TVector &x2) const; /** Gets the cooridnate distance between a and b. NOTE: a and b * should be type of component */ - double Evaluate(const ValueType &a, const ValueType &b) const ; + double Evaluate(const ValueType &a, const ValueType &b) const; /** Returns true if the distance between x and the origin is less * than radius */ - bool IsWithinRange(const TVector &x, const double radius) const ; + bool IsWithinRange(const TVector &x, const double radius) const; protected: EuclideanDistance() {} virtual ~EuclideanDistance() {} -} ; // end of class +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -96,10 +97,3 @@ protected: #endif #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkEuclideanDistance.txx b/Utilities/ITK/Code/Numerics/Statistics/itkEuclideanDistance.txx index 861ded2f5a..89defafb62 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkEuclideanDistance.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkEuclideanDistance.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEuclideanDistance.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:37:20 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-04 15:23:47 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,8 +18,8 @@ #define __itkEuclideanDistance_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TVector > inline double @@ -32,15 +32,15 @@ EuclideanDistance< TVector > itkExceptionMacro( << "Vector lengths must be equal." ); } - double temp, distance = NumericTraits< double >::Zero ; + double temp, distance = NumericTraits< double >::Zero; - for(unsigned int i = 0 ; i < x1.Size(); i++ ) + for(unsigned int i = 0; i < x1.Size(); i++ ) { - temp = x1[i] - x2[i] ; - distance += temp * temp ; + temp = x1[i] - x2[i]; + distance += temp * temp; } - return vcl_sqrt(distance) ; + return vcl_sqrt(distance); } @@ -58,15 +58,15 @@ EuclideanDistance< TVector > MeasurementVectorTraits::Assert( this->m_Origin, measurementVectorSize, "EuclideanDistance::Evaluate Origin and input vector have different lengths"); - double temp, distance = NumericTraits< double >::Zero ; + double temp, distance = NumericTraits< double >::Zero; - for(unsigned int i = 0 ; i < measurementVectorSize ; i++ ) + for(unsigned int i = 0; i < measurementVectorSize; i++ ) { - temp = this->GetOrigin()[i] - x[i] ; - distance += temp * temp ; + temp = this->GetOrigin()[i] - x[i]; + distance += temp * temp; } - return vcl_sqrt(distance) ; + return vcl_sqrt(distance); } template< class TVector > @@ -74,8 +74,8 @@ inline double EuclideanDistance< TVector > ::Evaluate(const ValueType &a, const ValueType &b) const { - double temp = a - b ; - return vcl_sqrt(temp * temp) ; + double temp = a - b; + return vcl_sqrt(temp * temp); } template< class TVector > @@ -92,29 +92,22 @@ EuclideanDistance< TVector > MeasurementVectorTraits::Assert( this->m_Origin, measurementVectorSize, "EuclideanDistance::IsWithinRange Origin and input vector have different lengths"); - double squaredRadius = radius * radius ; - double sum = NumericTraits< double >::Zero ; - double temp ; - for ( unsigned int i = measurementVectorSize ; i > 0 ; --i ) + double squaredRadius = radius * radius; + double sum = NumericTraits< double >::Zero; + double temp; + for ( unsigned int i = measurementVectorSize; i > 0; --i ) { - temp = this->Evaluate( this->GetOrigin()[i-1], x[i-1] ) ; - sum += temp * temp ; + temp = this->Evaluate( this->GetOrigin()[i-1], x[i-1] ); + sum += temp * temp; if (sum > squaredRadius) { - return false ; + return false; } } - return true ; + return true; } } // end of namespace Statistics } // end of namespace itk #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkExpectationMaximizationMixtureModelEstimator.h b/Utilities/ITK/Code/Numerics/Statistics/itkExpectationMaximizationMixtureModelEstimator.h index edd655a773..8ff9146244 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkExpectationMaximizationMixtureModelEstimator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkExpectationMaximizationMixtureModelEstimator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExpectationMaximizationMixtureModelEstimator.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:55 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-03-04 15:23:47 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,8 +20,8 @@ #include "itkMembershipFunctionBase.h" #include "itkMixtureModelComponentBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class ExpectationMaximizationMixtureModelEstimator * \brief This class generates the parameter estimates for a mixture @@ -53,102 +53,102 @@ template< class TSample > class ITK_EXPORT ExpectationMaximizationMixtureModelEstimator : public Object { public: - /** Standard class typedef*/ + /** Standard class typedef */ typedef ExpectationMaximizationMixtureModelEstimator Self; - typedef Object Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef Object Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard macros */ itkTypeMacro(ExpectationMaximizationMixtureModelEstimator, Object); - itkNewMacro(Self) ; + itkNewMacro(Self); /** TSample template argument related typedefs */ - typedef typename TSample::MeasurementType MeasurementType ; - typedef typename TSample::MeasurementVectorType MeasurementVectorType ; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; - /** Type of the mixture model component base class*/ - typedef MixtureModelComponentBase< TSample > ComponentType ; + /** Type of the mixture model component base class */ + typedef MixtureModelComponentBase< TSample > ComponentType; /** Type of the component pointer storage */ - typedef std::vector< ComponentType* > ComponentVectorType ; + typedef std::vector< ComponentType* > ComponentVectorType; /** Type of the membership function base class */ typedef MembershipFunctionBase< MeasurementVectorType > - ComponentMembershipFunctionType ; + ComponentMembershipFunctionType; /** Type of the array of the proportion values */ - typedef Array< double > ProportionVectorType ; + typedef Array< double > ProportionVectorType; /** Sets the target data that will be classified by this */ - void SetSample(const TSample* sample) ; + void SetSample(const TSample* sample); /** Returns the target data */ const TSample* GetSample() const; /** Set/Gets the initial proportion values. The size of proportion * vector should be same as the number of component (or classes) */ - void SetInitialProportions(ProportionVectorType &propotion) ; - ProportionVectorType* GetInitialProportions() ; + void SetInitialProportions(ProportionVectorType &propotion); + ProportionVectorType* GetInitialProportions(); /** Gets the result proportion values */ - ProportionVectorType* GetProportions() ; + ProportionVectorType* GetProportions(); /** Set/Gets the maximum number of iterations. When the optimization * process reaches the maximum number of interations, even if the * class parameters aren't converged, the optimization process * stops. */ - void SetMaximumIteration(int numberOfIterations) ; - int GetMaximumIteration() ; + void SetMaximumIteration(int numberOfIterations); + int GetMaximumIteration(); /** Gets the current iteration. */ int GetCurrentIteration() - { return m_CurrentIteration ; } + { return m_CurrentIteration; } /** Adds a new component (or class). */ - int AddComponent(ComponentType* component) ; + int AddComponent(ComponentType* component); /** Gets the total number of classes currently plugged in. */ - unsigned int GetNumberOfComponents() ; + unsigned int GetNumberOfComponents(); /** Runs the optimization process. */ - void Update() ; + void Update(); /** Termination status after running optimization */ - enum TERMINATION_CODE { CONVERGED = 0, NOT_CONVERGED = 1 } ; + enum TERMINATION_CODE { CONVERGED = 0, NOT_CONVERGED = 1 }; /** Gets the termination status */ - TERMINATION_CODE GetTerminationCode() ; + TERMINATION_CODE GetTerminationCode(); /** Gets the membership function specified by componentIndex argument. */ - ComponentMembershipFunctionType* GetComponentMembershipFunction(int componentIndex) ; + ComponentMembershipFunctionType* GetComponentMembershipFunction(int componentIndex); protected: - ExpectationMaximizationMixtureModelEstimator() ; + ExpectationMaximizationMixtureModelEstimator(); virtual ~ExpectationMaximizationMixtureModelEstimator() {} - void PrintSelf(std::ostream& os, Indent indent) const ; + void PrintSelf(std::ostream& os, Indent indent) const; - bool CalculateDensities() ; - double CalculateExpectation() ; - bool UpdateComponentParameters() ; - bool UpdateProportions() ; + bool CalculateDensities(); + double CalculateExpectation(); + bool UpdateComponentParameters(); + bool UpdateProportions(); /** Starts the estimation process */ - void GenerateData() ; + void GenerateData(); private: /** Target data sample pointer*/ - const TSample* m_Sample ; + const TSample* m_Sample; - int m_MaxIteration ; - int m_CurrentIteration ; - TERMINATION_CODE m_TerminationCode ; - ComponentVectorType m_ComponentVector ; - ProportionVectorType m_InitialProportions ; - ProportionVectorType m_Proportions ; -} ; // end of class + int m_MaxIteration; + int m_CurrentIteration; + TERMINATION_CODE m_TerminationCode; + ComponentVectorType m_ComponentVector; + ProportionVectorType m_InitialProportions; + ProportionVectorType m_Proportions; +}; // end of class } // end of namespace Statistics @@ -160,10 +160,3 @@ private: #endif #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkExpectationMaximizationMixtureModelEstimator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkExpectationMaximizationMixtureModelEstimator.txx index 0391579933..309917795d 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkExpectationMaximizationMixtureModelEstimator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkExpectationMaximizationMixtureModelEstimator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExpectationMaximizationMixtureModelEstimator.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:37:20 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-03-04 15:23:47 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,14 +20,14 @@ #include "itkExpectationMaximizationMixtureModelEstimator.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > ExpectationMaximizationMixtureModelEstimator< TSample > ::ExpectationMaximizationMixtureModelEstimator() { - m_TerminationCode = NOT_CONVERGED ; + m_TerminationCode = NOT_CONVERGED; } template< class TSample > @@ -35,7 +35,7 @@ void ExpectationMaximizationMixtureModelEstimator< TSample > ::PrintSelf(std::ostream& os, Indent indent) const { - Superclass::PrintSelf(os, indent) ; + Superclass::PrintSelf(os, indent); } @@ -44,7 +44,7 @@ void ExpectationMaximizationMixtureModelEstimator< TSample > ::SetMaximumIteration(int numberOfIterations) { - m_MaxIteration = numberOfIterations ; + m_MaxIteration = numberOfIterations; } template< class TSample > @@ -52,7 +52,7 @@ int ExpectationMaximizationMixtureModelEstimator< TSample > ::GetMaximumIteration() { - return m_MaxIteration ; + return m_MaxIteration; } template< class TSample > @@ -60,7 +60,7 @@ void ExpectationMaximizationMixtureModelEstimator< TSample > ::SetInitialProportions(ProportionVectorType &proportions) { - m_InitialProportions = proportions ; + m_InitialProportions = proportions; } template< class TSample > @@ -68,7 +68,7 @@ typename ExpectationMaximizationMixtureModelEstimator< TSample >::ProportionVect ExpectationMaximizationMixtureModelEstimator< TSample > ::GetInitialProportions() { - return m_InitialProportions ; + return m_InitialProportions; } template< class TSample > @@ -76,7 +76,7 @@ typename ExpectationMaximizationMixtureModelEstimator< TSample >::ProportionVect ExpectationMaximizationMixtureModelEstimator< TSample > ::GetProportions() { - return &m_Proportions ; + return &m_Proportions; } template< class TSample > @@ -84,7 +84,7 @@ void ExpectationMaximizationMixtureModelEstimator< TSample > ::SetSample(const TSample* sample) { - m_Sample = sample ; + m_Sample = sample; } template< class TSample > @@ -92,7 +92,7 @@ const TSample * ExpectationMaximizationMixtureModelEstimator< TSample > ::GetSample() const { - return m_Sample ; + return m_Sample; } @@ -101,7 +101,7 @@ int ExpectationMaximizationMixtureModelEstimator< TSample > ::AddComponent(ComponentType* component) { - m_ComponentVector.push_back(component) ; + m_ComponentVector.push_back(component); return static_cast<int>( m_ComponentVector.size() ); } @@ -118,7 +118,7 @@ typename ExpectationMaximizationMixtureModelEstimator< TSample >::TERMINATION_CO ExpectationMaximizationMixtureModelEstimator< TSample > ::GetTerminationCode() { - return m_TerminationCode ; + return m_TerminationCode; } template< class TSample > @@ -126,7 +126,7 @@ typename ExpectationMaximizationMixtureModelEstimator< TSample >::ComponentMembe ExpectationMaximizationMixtureModelEstimator< TSample > ::GetComponentMembershipFunction(int componentIndex) { - return (m_ComponentVector[componentIndex])->GetMembershipFunction() ; + return (m_ComponentVector[componentIndex])->GetMembershipFunction(); } @@ -135,79 +135,79 @@ bool ExpectationMaximizationMixtureModelEstimator< TSample > ::CalculateDensities() { - bool componentModified = false ; + bool componentModified = false; - for (unsigned int i = 0 ; i < m_ComponentVector.size() ; i++) + for (unsigned int i = 0; i < m_ComponentVector.size(); i++) { if ( (m_ComponentVector[i])->AreParametersModified() ) { - componentModified = true ; + componentModified = true; } } if (!componentModified) { - return false ; + return false; } - double temp ; + double temp; int numberOfComponents = static_cast<int>( m_ComponentVector.size() ); - std::vector< double > tempWeights(numberOfComponents) ; + std::vector< double > tempWeights(numberOfComponents); - typename TSample::ConstIterator iter = m_Sample->Begin() ; - typename TSample::ConstIterator last = m_Sample->End() ; + typename TSample::ConstIterator iter = m_Sample->Begin(); + typename TSample::ConstIterator last = m_Sample->End(); - int componentIndex ; + int componentIndex; - typedef typename TSample::FrequencyType FrequencyType ; - FrequencyType frequency ; - FrequencyType zeroFrequency = NumericTraits< FrequencyType >::Zero ; - typename TSample::MeasurementVectorType mvector ; - double density ; - double densitySum ; - double minDouble = NumericTraits< double >::NonpositiveMin() ; + typedef typename TSample::FrequencyType FrequencyType; + FrequencyType frequency; + FrequencyType zeroFrequency = NumericTraits< FrequencyType >::Zero; + typename TSample::MeasurementVectorType mvector; + double density; + double densitySum; + double minDouble = NumericTraits< double >::NonpositiveMin(); - long measurementVectorIndex = 0 ; + long measurementVectorIndex = 0; while (iter != last) { - mvector = iter.GetMeasurementVector() ; - frequency = iter.GetFrequency() ; - densitySum = 0.0 ; + mvector = iter.GetMeasurementVector(); + frequency = iter.GetFrequency(); + densitySum = 0.0; if ( frequency > zeroFrequency ) { - for (componentIndex = 0 ; componentIndex < numberOfComponents ; + for (componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) { density = m_Proportions[componentIndex] * - m_ComponentVector[componentIndex]->Evaluate(mvector) ; - tempWeights[componentIndex] = density ; - densitySum += density ; + m_ComponentVector[componentIndex]->Evaluate(mvector); + tempWeights[componentIndex] = density; + densitySum += density; } - for (componentIndex = 0 ; componentIndex < numberOfComponents ; + for (componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) { - temp = tempWeights[componentIndex] ; - temp /= densitySum ; + temp = tempWeights[componentIndex]; + temp /= densitySum; m_ComponentVector[componentIndex]->SetWeight(measurementVectorIndex, - temp) ; + temp); } } else { - for (componentIndex = 0 ; componentIndex < numberOfComponents ; + for (componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) { m_ComponentVector[componentIndex]->SetWeight(measurementVectorIndex, - minDouble) ; + minDouble); } } - ++iter ; - ++measurementVectorIndex ; + ++iter; + ++measurementVectorIndex; } - return true ; + return true; } template< class TSample > @@ -215,27 +215,26 @@ double ExpectationMaximizationMixtureModelEstimator< TSample > ::CalculateExpectation() { - int componentIndex, measurementVectorIndex ; - long size = m_Sample->Size() ; - double logProportion ; - double sum = 0.0 ; - double temp = 0.0 ; - for (componentIndex = 0 ; componentIndex < m_ComponentVector.size() ; + int componentIndex, measurementVectorIndex; + long size = m_Sample->Size(); + double logProportion; + double sum = 0.0; + double temp = 0.0; + for (componentIndex = 0; componentIndex < m_ComponentVector.size(); componentIndex++) { - logProportion = vcl_log(m_Proportions[componentIndex]) ; - for (measurementVectorIndex = 0 ; measurementVectorIndex < size ; + logProportion = vcl_log(m_Proportions[componentIndex]); + for (measurementVectorIndex = 0; measurementVectorIndex < size; measurementVectorIndex++) { temp = m_ComponentVector[componentIndex]-> - GetWeight(measurementVectorIndex) ; - sum += - temp * ( logProportion + - vcl_log(m_ComponentVector[componentIndex]-> - GetWeight(measurementVectorIndex) ) ) ; + GetWeight(measurementVectorIndex); + sum += temp * ( logProportion + + vcl_log(m_ComponentVector[componentIndex]-> + GetWeight(measurementVectorIndex) ) ); } } - return sum ; + return sum; } template< class TSample > @@ -243,22 +242,22 @@ bool ExpectationMaximizationMixtureModelEstimator< TSample > ::UpdateComponentParameters() { - unsigned int componentIndex ; - bool updated = false ; - ComponentType* component ; + unsigned int componentIndex; + bool updated = false; + ComponentType* component; - for (componentIndex = 0 ; componentIndex < m_ComponentVector.size() ; + for (componentIndex = 0; componentIndex < m_ComponentVector.size(); componentIndex++) { - component = m_ComponentVector[componentIndex] ; - component->Update() ; + component = m_ComponentVector[componentIndex]; + component->Update(); if (component->AreParametersModified()) { - updated = true ; + updated = true; } } - return updated ; + return updated; } template< class TSample > @@ -266,33 +265,32 @@ bool ExpectationMaximizationMixtureModelEstimator< TSample > ::UpdateProportions() { - int numberOfComponents = m_ComponentVector.size() ; - long sampleSize = m_Sample->Size() ; - double totalFrequency = (double) (m_Sample->GetTotalFrequency()) ; - long i, j ; - double tempSum ; - bool updated = false ; - - for (i = 0 ; i < numberOfComponents ; i++) + int numberOfComponents = m_ComponentVector.size(); + long sampleSize = m_Sample->Size(); + double totalFrequency = (double) (m_Sample->GetTotalFrequency()); + long i, j; + double tempSum; + bool updated = false; + + for (i = 0; i < numberOfComponents; i++) { - tempSum = 0.0 ; - for (j = 0 ; j < sampleSize ; j++) + tempSum = 0.0; + for (j = 0; j < sampleSize; j++) { - tempSum += - (m_ComponentVector[i]->GetWeight(j) * - m_Sample->GetFrequency(j)) ; + tempSum += (m_ComponentVector[i]->GetWeight(j) * + m_Sample->GetFrequency(j)); } - - tempSum /= totalFrequency ; + + tempSum /= totalFrequency; if (tempSum != m_Proportions[i]) { - m_Proportions[i] = tempSum ; - updated = true ; + m_Proportions[i] = tempSum; + updated = true; } } - return updated ; + return updated; } template< class TSample > @@ -300,27 +298,27 @@ void ExpectationMaximizationMixtureModelEstimator< TSample > ::GenerateData() { - m_Proportions = m_InitialProportions ; + m_Proportions = m_InitialProportions; - int iteration = 0 ; - m_CurrentIteration = 0 ; + int iteration = 0; + m_CurrentIteration = 0; while (iteration < m_MaxIteration) { - m_CurrentIteration = iteration ; + m_CurrentIteration = iteration; if (this->CalculateDensities()) { - this->UpdateComponentParameters() ; - this->UpdateProportions() ; + this->UpdateComponentParameters(); + this->UpdateProportions(); } else { - m_TerminationCode = CONVERGED ; - break ; + m_TerminationCode = CONVERGED; + break; } - ++iteration ; + ++iteration; } - m_TerminationCode = NOT_CONVERGED ; + m_TerminationCode = NOT_CONVERGED; } template< class TSample > @@ -328,17 +326,10 @@ void ExpectationMaximizationMixtureModelEstimator< TSample > ::Update() { - this->GenerateData() ; + this->GenerateData(); } } // end of namespace Statistics } // end of namespace itk #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDensityFunction.h b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDensityFunction.h index 11fc5d5e49..f329e95e3d 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDensityFunction.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDensityFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianDensityFunction.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:55 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-04 15:23:47 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,8 +26,8 @@ #include "itkMatrix.h" #include "itkDensityFunction.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class GaussianDensityFunction * \brief GaussianDensityFunction class represents Gaussian Density Function. @@ -57,17 +57,17 @@ class ITK_EXPORT GaussianDensityFunction : { public: /** Standard class typedefs */ - typedef GaussianDensityFunction Self; - typedef DensityFunction< TMeasurementVector > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef GaussianDensityFunction Self; + typedef DensityFunction< TMeasurementVector > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Strandard macros */ itkTypeMacro(GaussianDensityFunction, DensityFunction); itkNewMacro(Self); /** Typedef alias for the measurement vectors */ - typedef TMeasurementVector MeasurementVectorType ; + typedef TMeasurementVector MeasurementVectorType; /** Length of each measurement vector */ typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; @@ -80,27 +80,27 @@ public: /** Sets the mean */ void SetMean( const MeanType * mean ) - { - if( this->GetMeasurementVectorSize() ) { - MeasurementVectorTraits::Assert(mean, this->GetMeasurementVectorSize(), - "GaussianDensityFunction::SetMean Size of measurement vectors in the sample must the same as the size of the mean." ); + if( this->GetMeasurementVectorSize() ) + { + MeasurementVectorTraits::Assert(mean, this->GetMeasurementVectorSize(), + "GaussianDensityFunction::SetMean Size of measurement vectors in the sample must the same as the size of the mean." ); + } + else + { + this->SetMeasurementVectorSize( mean->Size() ); + } + + if ( m_Mean != mean) + { + m_Mean = mean; + this->Modified(); + } } - else - { - this->SetMeasurementVectorSize( mean->Size() ); - } - - if ( m_Mean != mean) - { - m_Mean = mean ; - this->Modified() ; - } - } /** Gets the mean */ const MeanType * GetMean() const - { return m_Mean ; } + { return m_Mean; } /** Sets the covariance matrix. * Also, this function calculates inverse covariance and pre factor of @@ -108,13 +108,13 @@ public: void SetCovariance(const CovarianceType* cov); /** Gets the covariance matrix */ - const CovarianceType* GetCovariance() const ; + const CovarianceType* GetCovariance() const; /** Gets the probability density of a measurement vector. */ - double Evaluate(const MeasurementVectorType &measurement) const ; + double Evaluate(const MeasurementVectorType &measurement) const; protected: - GaussianDensityFunction(void) ; + GaussianDensityFunction(void); virtual ~GaussianDensityFunction(void) {} void PrintSelf(std::ostream& os, Indent indent) const; @@ -132,7 +132,7 @@ private: /** if the all element of the given covarinace is zero, then this * value set to true */ - bool m_IsCovarianceZero ; + bool m_IsCovarianceZero; }; } // end of namespace Statistics diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDensityFunction.txx b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDensityFunction.txx index fdee392caf..8317807285 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDensityFunction.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDensityFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianDensityFunction.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:37:20 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,16 +19,16 @@ #include "itkGaussianDensityFunction.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template < class TMeasurementVector > GaussianDensityFunction< TMeasurementVector > ::GaussianDensityFunction() { - m_Mean = 0 ; - m_Covariance = 0 ; - m_PreFactor = 0.0 ; + m_Mean = 0; + m_Covariance = 0; + m_PreFactor = 0.0; } template < class TMeasurementVector > @@ -38,25 +38,25 @@ GaussianDensityFunction< TMeasurementVector > { Superclass::PrintSelf(os,indent); - os << indent << "Mean: " ; + os << indent << "Mean: "; if ( m_Mean != 0 ) { - os << (*m_Mean) << std::endl ; + os << (*m_Mean) << std::endl; } else { - os << " not set." << std::endl ; + os << " not set." << std::endl; } - os << indent << "Covariance: " << std::endl ; + os << indent << "Covariance: " << std::endl; if ( m_Covariance != 0 ) { - os << m_Covariance->GetVnlMatrix() ; - os << indent << "InverseCovariance: " << std::endl ; - os << indent << m_InverseCovariance.GetVnlMatrix() ; + os << m_Covariance->GetVnlMatrix(); + os << indent << "InverseCovariance: " << std::endl; + os << indent << m_InverseCovariance.GetVnlMatrix(); os << indent << "Prefactor: " << m_PreFactor << std::endl; } - os << indent << " not set." << std::endl ; + os << indent << " not set." << std::endl; } template < class TMeasurementVector > @@ -84,7 +84,7 @@ GaussianDensityFunction< TMeasurementVector > m_Covariance = cov; - m_IsCovarianceZero = m_Covariance->GetVnlMatrix().is_zero() ; + m_IsCovarianceZero = m_Covariance->GetVnlMatrix().is_zero(); if ( !m_IsCovarianceZero ) { @@ -96,8 +96,8 @@ GaussianDensityFunction< TMeasurementVector > double det = vnl_determinant(m_Covariance->GetVnlMatrix()); // calculate coefficient C of multivariate gaussian - m_PreFactor = 1.0 / (sqrt(det) * - vcl_pow(sqrt(2.0 * vnl_math::pi), double(this->GetMeasurementVectorSize()))) ; + m_PreFactor = 1.0 / (vcl_sqrt(det) * + vcl_pow(vcl_sqrt(2.0 * vnl_math::pi), double(this->GetMeasurementVectorSize()))); } } @@ -106,7 +106,7 @@ const typename GaussianDensityFunction< TMeasurementVector >::CovarianceType* GaussianDensityFunction< TMeasurementVector > ::GetCovariance() const { - return m_Covariance ; + return m_Covariance; } template < class TMeasurementVector > @@ -115,7 +115,7 @@ GaussianDensityFunction< TMeasurementVector > ::Evaluate(const MeasurementVectorType &measurement) const { - double temp ; + double temp; const MeasurementVectorSizeType measurementVectorSize = this->GetMeasurementVectorSize(); @@ -127,43 +127,43 @@ GaussianDensityFunction< TMeasurementVector > if ( !m_IsCovarianceZero ) { // Compute |y - mean | - for ( unsigned int i = 0 ; i < measurementVectorSize ; i++) + for ( unsigned int i = 0; i < measurementVectorSize; i++) { - tempVector[i] = measurement[i] - (*m_Mean)[i] ; + tempVector[i] = measurement[i] - (*m_Mean)[i]; } // Compute |y - mean | * inverse(cov) - for (unsigned int i = 0 ; i < measurementVectorSize ; i++) + for (unsigned int i = 0; i < measurementVectorSize; i++) { - temp = 0 ; - for (unsigned int j = 0 ; j < measurementVectorSize ; j++) + temp = 0; + for (unsigned int j = 0; j < measurementVectorSize; j++) { - temp += tempVector[j] * m_InverseCovariance.GetVnlMatrix().get(j, i) ; + temp += tempVector[j] * m_InverseCovariance.GetVnlMatrix().get(j, i); } - tempVector2[i] = temp ; + tempVector2[i] = temp; } // Compute |y - mean | * inverse(cov) * |y - mean|^T - temp = 0 ; - for (unsigned int i = 0 ; i < measurementVectorSize ; i++) + temp = 0; + for (unsigned int i = 0; i < measurementVectorSize; i++) { - temp += tempVector2[i] * tempVector[i] ; + temp += tempVector2[i] * tempVector[i]; } - return m_PreFactor * vcl_exp(-0.5 * temp ) ; + return m_PreFactor * vcl_exp(-0.5 * temp ); } else { - for ( unsigned int i = 0 ; i < measurementVectorSize ; i++) + for ( unsigned int i = 0; i < measurementVectorSize; i++) { if ( (*m_Mean)[i] != (double) measurement[i] ) { - return 0 ; + return 0; } } - return NumericTraits< double >::max() ; + return NumericTraits< double >::max(); } } @@ -171,6 +171,4 @@ GaussianDensityFunction< TMeasurementVector > } // end namespace Statistics } // end of namespace itk - - #endif diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.cxx b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.cxx index 193f4914d9..edf0f5f659 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.cxx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianDistribution.cxx,v $ Language: C++ - Date: $Date: 2007-02-24 13:47:32 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-05 10:56:50 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,14 +42,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -114,14 +114,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -181,21 +181,21 @@ double GaussianDistribution ::PDF(double x) { - static const double oneonsqrttwopi = 1.0 / sqrt( 2.0 * vnl_math::pi ); + static const double oneonsqrttwopi = 1.0 / vcl_sqrt( 2.0 * vnl_math::pi ); - return oneonsqrttwopi * exp(-0.5*x*x); + return oneonsqrttwopi * vcl_exp(-0.5*x*x); } double GaussianDistribution ::PDF(double x, double mean, double variance) { - static const double oneonsqrttwopi = 1.0 / sqrt( 2.0 * vnl_math::pi ); + static const double oneonsqrttwopi = 1.0 / vcl_sqrt( 2.0 * vnl_math::pi ); double xminusmean = x - mean; - return (oneonsqrttwopi / sqrt(variance)) - * exp(-0.5*xminusmean*xminusmean / variance); + return (oneonsqrttwopi / vcl_sqrt(variance)) + * vcl_exp(-0.5*xminusmean*xminusmean / variance); } double @@ -209,14 +209,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << "GaussianDistribution: " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -234,7 +234,7 @@ GaussianDistribution ::CDF(double x, double mean, double variance) { // convert to zero mean unit variance - double u = (x - mean) / sqrt(variance); + double u = (x - mean) / vcl_sqrt(variance); return 0.5 * (vnl_erf(vnl_math::sqrt1_2 * u) + 1.0); } @@ -251,14 +251,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << "GaussianDistribution: " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -290,19 +290,19 @@ GaussianDistribution } - /** Step 1: use 26.2.23 from Abramowitz and Stegun **/ + /** Step 1: use 26.2.23 from Abramowitz and Stegun */ - dt = sqrt( -2.0 * log(dp) ); + dt = vcl_sqrt( -2.0 * vcl_log(dp) ); dx = dt - ((.010328e+0*dt + .802853e+0)*dt + 2.515517e+0) /(((.001308e+0*dt + .189269e+0)*dt + 1.432788e+0)*dt + 1.e+0); - /** Step 2: do 3 Newton steps to improve this **/ + /** Step 2: do 3 Newton steps to improve this */ for( newt=0; newt < 3; newt++ ) { dq = 0.5e+0 * vnl_erfc( dx / 1.414213562373095e+0 ) - dp; - ddq = exp( -0.5e+0 * dx * dx ) / 2.506628274631000e+0; + ddq = vcl_exp( -0.5e+0 * dx * dx ) / 2.506628274631000e+0; dx = dx + dq / ddq; } @@ -326,7 +326,7 @@ GaussianDistribution // apply the mean and variance to provide the value for the // prescribed Gaussian - x = x*sqrt(variance) + mean; + x = x*vcl_sqrt(variance) + mean; return x; } @@ -342,14 +342,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << "GaussianDistribution: " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -369,14 +369,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -396,14 +396,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -436,14 +436,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -463,14 +463,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -503,14 +503,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } @@ -530,14 +530,14 @@ GaussianDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excep(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excep.SetDescription(message.str()); + excep.SetLocation(ITK_LOCATION); + throw excep; return 0.0; } } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.h b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.h index 439a4906a0..b6c97f772b 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianDistribution.h,v $ Language: C++ - Date: $Date: 2007-02-24 13:47:32 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-03-04 15:23:48 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -119,7 +119,7 @@ public: virtual void SetMean(double); /** Get the mean of the Gaussian distribution. Defaults to 0.0. The - * mean is stored in position 0 of the parameters vector.*/ + * mean is stored in position 0 of the parameters vector. */ virtual double GetMean() const; /** Does this distribution have a mean? */ @@ -159,7 +159,7 @@ public: /** Static method to evaluate the cumulative distribution function * (cdf) of a standardized (mean zero, unit variance) Gaussian. The * static method provides optimized access without requiring an - * instance of the class. Accuracy is approximately 10^-8.*/ + * instance of the class. Accuracy is approximately 10^-8. */ static double CDF(double x); /** Static method to evaluate the cumulative distribution function @@ -204,7 +204,7 @@ public: * * This function has been modified to compute the inverse of P(x) instead * of Q(x). - **/ + */ static double InverseCDF(double p); /** Static method to evaluate the inverse cumulative distribution diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianGoodnessOfFitComponent.h b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianGoodnessOfFitComponent.h index 3285dfbc21..741805d828 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianGoodnessOfFitComponent.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianGoodnessOfFitComponent.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianGoodnessOfFitComponent.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:55 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-04 15:23:48 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,8 +23,8 @@ #include "itkWeightedCovarianceCalculator.h" #include "itkSymmetricEigenAnalysis.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class GaussianGoodnessOfFitComponent * \brief is a GoodnessOfFitComponent for Gaussian distribution. @@ -53,112 +53,112 @@ class GaussianGoodnessOfFitComponent { public: /** Standard class typedefs */ - typedef GaussianGoodnessOfFitComponent Self; + typedef GaussianGoodnessOfFitComponent Self; typedef GoodnessOfFitComponentBase< TInputSample > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer< const Self > ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(GaussianGoodnessOfFitComponent, - GoodnessOfFitComponentBase) ; + GoodnessOfFitComponentBase); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** Typedefs from input sample */ - typedef typename TInputSample::MeasurementType MeasurementType ; - typedef typename TInputSample::MeasurementVectorType MeasurementVectorType ; + typedef typename TInputSample::MeasurementType MeasurementType; + typedef typename TInputSample::MeasurementVectorType MeasurementVectorType; /** Typedefs from Superclass */ - typedef typename Superclass::CenterType CenterType ; - typedef typename Superclass::RadiusType RadiusType ; - typedef typename Superclass::MeanType MeanType ; - typedef typename Superclass::StandardDeviationType StandardDeviationType ; - typedef typename Superclass::ResampledSampleType ResampledSampleType ; - typedef typename Superclass::ProjectionAxisArrayType ProjectionAxisArrayType; + typedef typename Superclass::CenterType CenterType; + typedef typename Superclass::RadiusType RadiusType; + typedef typename Superclass::MeanType MeanType; + typedef typename Superclass::StandardDeviationType StandardDeviationType; + typedef typename Superclass::ResampledSampleType ResampledSampleType; + typedef typename Superclass::ProjectionAxisArrayType ProjectionAxisArrayType; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; - typedef Array< double > ParametersType ; + typedef Array< double > ParametersType; /** Weight function type. The density values are used as weights of * each instance (measurement vector) for the Covariance calulator */ typedef GaussianDensityFunction< MeasurementVectorType > - ProbabilityDensityFunctionType ; + ProbabilityDensityFunctionType; - typedef typename ProbabilityDensityFunctionType::CovarianceType CovarianceType ; + typedef typename ProbabilityDensityFunctionType::CovarianceType CovarianceType; /** Type of the covariance calculator. the output of this calculator is * a covariance matrix that is used as the input of the Projection * calculator */ typedef WeightedCovarianceCalculator< ResampledSampleType > - CovarianceCalculatorType ; + CovarianceCalculatorType; - /** Default projection axis calculator type.*/ + /** Default projection axis calculator type. */ typedef Array< double > EigenValuesArrayType; typedef SymmetricEigenAnalysis< ProjectionAxisArrayType, EigenValuesArrayType > - ProjectionAxisCalculatorType; + ProjectionAxisCalculatorType; /** Gets the size of parameters which consists of mean * and standard deviation */ unsigned int GetNumberOfParameters() const - { return (unsigned int)(this->GetMeasurementVectorSize() + 1) ; } + { return (unsigned int)(this->GetMeasurementVectorSize() + 1); } /** Sets the component distribution parameters */ - void SetParameters(const ParametersType ¶meter) ; + void SetParameters(const ParametersType ¶meter); /** Gets the center point for the neighborhood sampling */ - CenterType* GetCenter() ; + CenterType* GetCenter(); /** Gets the radius for the neighborhood sampling */ - RadiusType* GetRadius() ; + RadiusType* GetRadius(); /** Gets the mean of the distributon */ - MeanType* GetMean() ; + MeanType* GetMean(); /** Gets the standard deviation of the distribution */ - StandardDeviationType* GetStandardDeviation() ; + StandardDeviationType* GetStandardDeviation(); /** Univariate (standard) cumulative probability function */ - double GetCumulativeProbability(double x) const ; + double GetCumulativeProbability(double x) const; /** Multivariate probability density function */ - double GetProbabilityDensity(MeasurementVectorType &measurements) const ; + double GetProbabilityDensity(MeasurementVectorType &measurements) const; /** Prints all the parameters. Usually for debugging. */ - void PrintParameters(std::ostream &os) const ; + void PrintParameters(std::ostream &os) const; /** Gets the full distribution parameters which consists of * mean vector and covariance matrix in a single array */ - ParametersType GetFullParameters() const ; + ParametersType GetFullParameters() const; /** Set the input sample */ virtual void SetInputSample( const TInputSample* sample ); protected: - GaussianGoodnessOfFitComponent() ; - virtual ~GaussianGoodnessOfFitComponent() ; - virtual void PrintSelf(std::ostream& os, Indent indent) const ; + GaussianGoodnessOfFitComponent(); + virtual ~GaussianGoodnessOfFitComponent(); + virtual void PrintSelf(std::ostream& os, Indent indent) const; /** Calculates the base axes for projection */ - virtual void CalculateProjectionAxes() ; + virtual void CalculateProjectionAxes(); private: typename ProbabilityDensityFunctionType::Pointer - m_ProbabilityDensityFunction ; - typename CovarianceCalculatorType::Pointer m_CovarianceCalculator ; - ProjectionAxisCalculatorType * m_ProjectionAxisCalculator ; + m_ProbabilityDensityFunction; + typename CovarianceCalculatorType::Pointer m_CovarianceCalculator; + ProjectionAxisCalculatorType * m_ProjectionAxisCalculator; - MeanType m_Mean ; - CenterType m_Center ; - RadiusType m_Radius ; - StandardDeviationType m_StandardDeviation ; - CovarianceType m_Covariance ; + MeanType m_Mean; + CenterType m_Center; + RadiusType m_Radius; + StandardDeviationType m_StandardDeviation; + CovarianceType m_Covariance; - unsigned int m_NumberOfParameters ; + unsigned int m_NumberOfParameters; - int m_LongestAxisIndex ; - double m_LargestEigenValue ; -} ; // end of class + int m_LongestAxisIndex; + double m_LargestEigenValue; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -168,4 +168,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianGoodnessOfFitComponent.txx b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianGoodnessOfFitComponent.txx index 8f1a2bef95..9480c1fed7 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianGoodnessOfFitComponent.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianGoodnessOfFitComponent.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianGoodnessOfFitComponent.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:37:20 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 15:23:48 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,28 +21,28 @@ #include "vnl/vnl_math.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TInputSample > GaussianGoodnessOfFitComponent< TInputSample > ::GaussianGoodnessOfFitComponent() { - m_StandardDeviation = 0.0 ; - m_Radius = 0.0 ; + m_StandardDeviation = 0.0; + m_Radius = 0.0; - m_NumberOfParameters = (unsigned int)(this->GetMeasurementVectorSize() + 1) ; + m_NumberOfParameters = (unsigned int)(this->GetMeasurementVectorSize() + 1); - m_ProbabilityDensityFunction = ProbabilityDensityFunctionType::New() ; + m_ProbabilityDensityFunction = ProbabilityDensityFunctionType::New(); - m_CovarianceCalculator = CovarianceCalculatorType::New() ; + m_CovarianceCalculator = CovarianceCalculatorType::New(); m_CovarianceCalculator-> - SetWeightFunction(m_ProbabilityDensityFunction.GetPointer()) ; + SetWeightFunction(m_ProbabilityDensityFunction.GetPointer()); - m_ProjectionAxisCalculator = new ProjectionAxisCalculatorType() ; + m_ProjectionAxisCalculator = new ProjectionAxisCalculatorType(); //m_ProjectionAxisCalculator->SetMatrix(&m_Covariance); - m_LargestEigenValue = 0.0 ; + m_LargestEigenValue = 0.0; m_LongestAxisIndex = 0; } @@ -65,8 +65,8 @@ GaussianGoodnessOfFitComponent< TInputSample > MeasurementVectorTraits::SetLength( m_Center, measurementVectorLength ); m_Covariance.SetSize( measurementVectorLength, measurementVectorLength ); - m_Mean.Fill(0.0) ; - m_Covariance.Fill(0.0) ; + m_Mean.Fill(0.0); + m_Covariance.Fill(0.0); m_CovarianceCalculator->SetMean(&m_Mean); m_ProbabilityDensityFunction->SetMean(&m_Mean); @@ -80,19 +80,19 @@ void GaussianGoodnessOfFitComponent< TInputSample > ::PrintSelf(std::ostream& os, Indent indent) const { - Superclass::PrintSelf(os,indent) ; - - os << indent << "Mean: " << m_Mean << std::endl ; - os << indent << "Covariance: " << m_Covariance << std::endl ; - os << indent << "StandardDeviation: " << m_StandardDeviation << std::endl ; - os << indent << "Center: " << m_Center << std::endl ; - os << indent << "Radius: " << m_Radius << std::endl ; - os << indent << "NumberOfParameters: " << m_NumberOfParameters << std::endl ; - os << indent << "ProbabilityDensityFunction: " << m_ProbabilityDensityFunction << std::endl ; - os << indent << "CovarianceCalculator: " << m_CovarianceCalculator << std::endl ; - os << indent << "ProjectionAxisCalculator: " << m_ProjectionAxisCalculator << std::endl ; - os << indent << "LongestAxisIndex: " << m_LongestAxisIndex << std::endl ; - os << indent << "LargestEigenValue: " << m_LargestEigenValue << std::endl ; + Superclass::PrintSelf(os,indent); + + os << indent << "Mean: " << m_Mean << std::endl; + os << indent << "Covariance: " << m_Covariance << std::endl; + os << indent << "StandardDeviation: " << m_StandardDeviation << std::endl; + os << indent << "Center: " << m_Center << std::endl; + os << indent << "Radius: " << m_Radius << std::endl; + os << indent << "NumberOfParameters: " << m_NumberOfParameters << std::endl; + os << indent << "ProbabilityDensityFunction: " << m_ProbabilityDensityFunction << std::endl; + os << indent << "CovarianceCalculator: " << m_CovarianceCalculator << std::endl; + os << indent << "ProjectionAxisCalculator: " << m_ProjectionAxisCalculator << std::endl; + os << indent << "LongestAxisIndex: " << m_LongestAxisIndex << std::endl; + os << indent << "LargestEigenValue: " << m_LargestEigenValue << std::endl; } @@ -101,31 +101,31 @@ void GaussianGoodnessOfFitComponent< TInputSample > ::SetParameters(const ParametersType ¶meters) { - Superclass::SetParameters(parameters) ; + Superclass::SetParameters(parameters); - bool changed = false ; + bool changed = false; - unsigned int i = 0 ; + unsigned int i = 0; while ( i < this->GetMeasurementVectorSize() ) { if ( m_Mean[i] != parameters[i] ) { - m_Mean[i] = parameters[i] ; - m_Center[i] = m_Mean[i] ; - changed = true ; + m_Mean[i] = parameters[i]; + m_Center[i] = m_Mean[i]; + changed = true; } - i++ ; + i++; } if ( m_StandardDeviation != parameters[i] ) { - m_StandardDeviation = parameters[i] ; - changed = true ; + m_StandardDeviation = parameters[i]; + changed = true; } if ( changed ) { - this->Modified() ; + this->Modified(); } } @@ -134,7 +134,7 @@ typename GaussianGoodnessOfFitComponent< TInputSample >::CenterType* GaussianGoodnessOfFitComponent< TInputSample > ::GetCenter() { - return &m_Center ; + return &m_Center; } template< class TInputSample > @@ -142,8 +142,8 @@ typename GaussianGoodnessOfFitComponent< TInputSample >::RadiusType* GaussianGoodnessOfFitComponent< TInputSample > ::GetRadius() { - m_Radius = m_StandardDeviation * this->GetHistogramExtent() ; - return &m_Radius ; + m_Radius = m_StandardDeviation * this->GetHistogramExtent(); + return &m_Radius; } template< class TInputSample > @@ -151,7 +151,7 @@ typename GaussianGoodnessOfFitComponent< TInputSample >::MeanType* GaussianGoodnessOfFitComponent< TInputSample > ::GetMean() { - return &m_Mean ; + return &m_Mean; } template< class TInputSample > @@ -159,7 +159,7 @@ typename GaussianGoodnessOfFitComponent< TInputSample >::StandardDeviationType* GaussianGoodnessOfFitComponent< TInputSample > ::GetStandardDeviation() { - return &m_StandardDeviation ; + return &m_StandardDeviation; } template< class TInputSample > @@ -167,19 +167,19 @@ void GaussianGoodnessOfFitComponent< TInputSample > ::CalculateProjectionAxes() { - unsigned int i, j ; + unsigned int i, j; - m_CovarianceCalculator->SetInputSample(this->GetResampledSample()) ; - m_Covariance.Fill(0.0) ; + m_CovarianceCalculator->SetInputSample(this->GetResampledSample()); + m_Covariance.Fill(0.0); m_Covariance.GetVnlMatrix(). - fill_diagonal( m_StandardDeviation * m_StandardDeviation ) ; + fill_diagonal( m_StandardDeviation * m_StandardDeviation ); if ( this->GetResampledSample()->GetTotalFrequency() > 0 ) { - m_ProbabilityDensityFunction->SetCovariance(&m_Covariance) ; - m_CovarianceCalculator->Update() ; + m_ProbabilityDensityFunction->SetCovariance(&m_Covariance); + m_CovarianceCalculator->Update(); - m_Covariance = (*m_CovarianceCalculator->GetOutput()) ; + m_Covariance = (*m_CovarianceCalculator->GetOutput()); } m_ProjectionAxisCalculator->SetDimension( this->GetResampledSample( @@ -188,32 +188,32 @@ GaussianGoodnessOfFitComponent< TInputSample > ProjectionAxisArrayType from; from.SetSize( this->GetMeasurementVectorSize(), this->GetMeasurementVectorSize()); - ProjectionAxisArrayType* to = this->GetProjectionAxes() ; + ProjectionAxisArrayType* to = this->GetProjectionAxes(); m_ProjectionAxisCalculator->ComputeEigenValuesAndVectors( m_Covariance, eigenValues, from); - for ( i = 0 ; i < this->GetMeasurementVectorSize(); i++ ) + for ( i = 0; i < this->GetMeasurementVectorSize(); i++ ) { - for (j = 0 ; j < this->GetMeasurementVectorSize(); j++) + for (j = 0; j < this->GetMeasurementVectorSize(); j++) { - (*to)[i][j] = (from)[i][j] ; + (*to)[i][j] = (from)[i][j]; } } - m_LongestAxisIndex = 0 ; - m_LargestEigenValue = NumericTraits< double >::NonpositiveMin() ; - for ( i = 0 ; i < this->GetMeasurementVectorSize(); i++ ) + m_LongestAxisIndex = 0; + m_LargestEigenValue = NumericTraits< double >::NonpositiveMin(); + for ( i = 0; i < this->GetMeasurementVectorSize(); i++ ) { if ( eigenValues[i] > m_LargestEigenValue ) { - m_LongestAxisIndex = i ; - m_LargestEigenValue = (eigenValues)[i] ; + m_LongestAxisIndex = i; + m_LargestEigenValue = (eigenValues)[i]; } } m_Covariance *= - (m_StandardDeviation * m_StandardDeviation / m_LargestEigenValue) ; + (m_StandardDeviation * m_StandardDeviation / m_LargestEigenValue); } template< class TInputSample > @@ -223,10 +223,10 @@ GaussianGoodnessOfFitComponent< TInputSample > { /* |e(x)| < 7.5e-8 : From Handbook, p491 */ - double mean = 0.0 ; - double standardDeviation = 1.0 ; + double mean = 0.0; + double standardDeviation = 1.0; - double nx = vcl_fabs(x - mean ) / standardDeviation ; + double nx = vcl_fabs(x - mean ) / standardDeviation; double t = 1 / (1 + 0.2316419 * nx); double tt = t*t; @@ -253,7 +253,7 @@ double GaussianGoodnessOfFitComponent< TInputSample > ::GetProbabilityDensity(MeasurementVectorType &measurements) const { - return m_ProbabilityDensityFunction->Evaluate(measurements) ; + return m_ProbabilityDensityFunction->Evaluate(measurements); } template< class TInputSample > @@ -261,16 +261,16 @@ void GaussianGoodnessOfFitComponent< TInputSample > ::PrintParameters(std::ostream &os) const { - unsigned int i, j ; - os << m_Mean ; - for( i = 0 ; i < this->GetMeasurementVectorSize() ; i++) + unsigned int i, j; + os << m_Mean; + for( i = 0; i < this->GetMeasurementVectorSize(); i++) { - for( j = 0 ; j < this->GetMeasurementVectorSize() ; j++) + for( j = 0; j < this->GetMeasurementVectorSize(); j++) { - os << " " << m_Covariance.GetVnlMatrix().get(i,j) ; + os << " " << m_Covariance.GetVnlMatrix().get(i,j); } } - os << std::endl ; + os << std::endl; } template< class TInputSample > @@ -279,30 +279,29 @@ GaussianGoodnessOfFitComponent< TInputSample > ::GetFullParameters() const { ParametersType params(this->GetMeasurementVectorSize() + - this->GetMeasurementVectorSize() * this->GetMeasurementVectorSize()) ; + this->GetMeasurementVectorSize() * this->GetMeasurementVectorSize()); - unsigned int index = 0 ; + unsigned int index = 0; while ( index < this->GetMeasurementVectorSize() ) { - params[index] = m_Mean[index] ; - ++index ; + params[index] = m_Mean[index]; + ++index; } - unsigned int i, j ; - for( i = 0 ; i < this->GetMeasurementVectorSize() ; i++) + unsigned int i, j; + for( i = 0; i < this->GetMeasurementVectorSize(); i++) { - for( j = 0 ; j < this->GetMeasurementVectorSize() ; j++) + for( j = 0; j < this->GetMeasurementVectorSize(); j++) { - params[index] = m_Covariance.GetVnlMatrix().get(i,j) ; - ++index ; + params[index] = m_Covariance.GetVnlMatrix().get(i,j); + ++index; } } - return params ; + return params; } } // end of namespace Statistics } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianMixtureModelComponent.h b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianMixtureModelComponent.h index 158895cc8e..b608c23939 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianMixtureModelComponent.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianMixtureModelComponent.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianMixtureModelComponent.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:55 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-04 15:23:48 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,8 +23,8 @@ #include "itkWeightedMeanCalculator.h" #include "itkWeightedCovarianceCalculator.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class GaussianMixtureModelComponent * \brief is a component (derived from MixtureModelComponentBase) for @@ -50,63 +50,63 @@ class GaussianMixtureModelComponent : { public: /**Standard class typedefs. */ - typedef GaussianMixtureModelComponent Self; - typedef MixtureModelComponentBase< TSample > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef GaussianMixtureModelComponent Self; + typedef MixtureModelComponentBase< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /**Standard Macros */ itkTypeMacro(GaussianMixtureModelComponent, MixtureModelComponentBase); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Typedefs from the superclass */ - typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; - typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType ; - typedef typename Superclass::MembershipFunctionType MembershipFunctionType ; - typedef typename Superclass::WeightArrayType WeightArrayType ; - typedef typename Superclass::ParametersType ParametersType ; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + typedef typename Superclass::MembershipFunctionType MembershipFunctionType; + typedef typename Superclass::WeightArrayType WeightArrayType; + typedef typename Superclass::ParametersType ParametersType; /** Type of the membership function. Gaussian density function */ typedef GaussianDensityFunction< MeasurementVectorType > - NativeMembershipFunctionType ; + NativeMembershipFunctionType; /** Types of the mean and the covariance calculator that will update * this component's distribution parameters */ - typedef WeightedMeanCalculator< TSample > MeanEstimatorType ; - typedef WeightedCovarianceCalculator< TSample > CovarianceEstimatorType ; + typedef WeightedMeanCalculator< TSample > MeanEstimatorType; + typedef WeightedCovarianceCalculator< TSample > CovarianceEstimatorType; /** Type of the mean vector */ - typedef typename MeanEstimatorType::OutputType MeanType ; + typedef typename MeanEstimatorType::OutputType MeanType; /** Type of the covariance matrix */ - typedef typename CovarianceEstimatorType::OutputType CovarianceType ; + typedef typename CovarianceEstimatorType::OutputType CovarianceType; /** Sets the input sample */ - void SetSample(const TSample* sample) ; + void SetSample(const TSample* sample); /** Sets the component's distribution parameters. */ - void SetParameters(const ParametersType ¶meters) ; + void SetParameters(const ParametersType ¶meters); protected: - GaussianMixtureModelComponent() ; + GaussianMixtureModelComponent(); virtual ~GaussianMixtureModelComponent() {} void PrintSelf(std::ostream& os, Indent indent) const; /** Returns the sum of squared changes in parameters between * iterations */ - double CalculateParametersChange() ; + double CalculateParametersChange(); /** Computes the new distribution parameters */ - void GenerateData() ; + void GenerateData(); private: - typename NativeMembershipFunctionType::Pointer m_GaussianDensityFunction ; - MeanType m_Mean ; - CovarianceType m_Covariance ; - typename MeanEstimatorType::Pointer m_MeanEstimator ; - typename CovarianceEstimatorType::Pointer m_CovarianceEstimator ; -} ; // end of class + typename NativeMembershipFunctionType::Pointer m_GaussianDensityFunction; + MeanType m_Mean; + CovarianceType m_Covariance; + typename MeanEstimatorType::Pointer m_MeanEstimator; + typename CovarianceEstimatorType::Pointer m_CovarianceEstimator; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -116,4 +116,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianMixtureModelComponent.txx b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianMixtureModelComponent.txx index 74ab57566a..83fda3910b 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianMixtureModelComponent.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianMixtureModelComponent.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianMixtureModelComponent.txx,v $ Language: C++ -Date: $Date: 2006-03-19 04:37:20 $ -Version: $Revision: 1.16 $ +Date: $Date: 2009-04-16 15:27:01 $ +Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,18 +22,20 @@ PURPOSE. See the above copyright notices for more information. #include "itkGaussianMixtureModelComponent.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > GaussianMixtureModelComponent< TSample > ::GaussianMixtureModelComponent() { - m_MeanEstimator = MeanEstimatorType::New() ; - m_CovarianceEstimator = CovarianceEstimatorType::New() ; - m_GaussianDensityFunction = NativeMembershipFunctionType::New() ; + m_MeanEstimator = MeanEstimatorType::New(); + m_CovarianceEstimator = CovarianceEstimatorType::New(); + m_GaussianDensityFunction = NativeMembershipFunctionType::New(); this->SetMembershipFunction((MembershipFunctionType*) - m_GaussianDensityFunction.GetPointer()) ; + m_GaussianDensityFunction.GetPointer()); + m_Mean.Fill(0.0); + m_Covariance.SetIdentity(); } template< class TSample > @@ -41,13 +43,13 @@ void GaussianMixtureModelComponent< TSample > ::PrintSelf(std::ostream& os, Indent indent) const { - Superclass::PrintSelf(os, indent) ; + Superclass::PrintSelf(os, indent); - os << indent << "Mean: " << m_Mean << std::endl ; - os << indent << "Covariance: " << m_Covariance << std::endl ; - os << indent << "Mean Estimator: " << m_MeanEstimator << std::endl ; - os << indent << "Covariance Estimator: " << m_CovarianceEstimator << std::endl ; - os << indent << "GaussianDensityFunction: " << m_GaussianDensityFunction << std::endl ; + os << indent << "Mean: " << m_Mean << std::endl; + os << indent << "Covariance: " << m_Covariance << std::endl; + os << indent << "Mean Estimator: " << m_MeanEstimator << std::endl; + os << indent << "Covariance Estimator: " << m_CovarianceEstimator << std::endl; + os << indent << "GaussianDensityFunction: " << m_GaussianDensityFunction << std::endl; } template< class TSample > @@ -55,24 +57,24 @@ void GaussianMixtureModelComponent< TSample > ::SetSample(const TSample* sample) { - Superclass::SetSample(sample) ; + Superclass::SetSample(sample); - m_MeanEstimator->SetInputSample(sample) ; - m_CovarianceEstimator->SetInputSample(sample) ; + m_MeanEstimator->SetInputSample(sample); + m_CovarianceEstimator->SetInputSample(sample); - WeightArrayType* weights = this->GetWeights() ; - m_MeanEstimator->SetWeights(weights) ; - m_CovarianceEstimator->SetWeights(weights) ; + WeightArrayType* weights = this->GetWeights(); + m_MeanEstimator->SetWeights(weights); + m_CovarianceEstimator->SetWeights(weights); const MeasurementVectorSizeType measurementVectorLength = sample->GetMeasurementVectorSize(); m_GaussianDensityFunction->SetMeasurementVectorSize( measurementVectorLength ); MeasurementVectorTraits::SetLength( m_Mean, measurementVectorLength ); m_Covariance.SetSize( measurementVectorLength, measurementVectorLength ); - m_Mean.Fill(NumericTraits< double >::NonpositiveMin()) ; - m_Covariance.Fill(NumericTraits< double >::NonpositiveMin()) ; - m_CovarianceEstimator->SetMean(&m_Mean) ; - m_GaussianDensityFunction->SetMean(&m_Mean) ; + m_Mean.Fill(NumericTraits< double >::NonpositiveMin()); + m_Covariance.Fill(NumericTraits< double >::NonpositiveMin()); + m_CovarianceEstimator->SetMean(&m_Mean); + m_GaussianDensityFunction->SetMean(&m_Mean); } template< class TSample > @@ -80,41 +82,41 @@ void GaussianMixtureModelComponent< TSample > ::SetParameters(const ParametersType ¶meters) { - Superclass::SetParameters(parameters) ; + Superclass::SetParameters(parameters); - unsigned int paramIndex = 0 ; - unsigned int i, j ; + unsigned int paramIndex = 0; + unsigned int i, j; - bool changed = false ; + bool changed = false; MeasurementVectorSizeType measurementVectorSize = this->GetSample()->GetMeasurementVectorSize(); - for ( i = 0 ; i < measurementVectorSize ; i++) + for ( i = 0; i < measurementVectorSize; i++) { if ( m_Mean[i] != parameters[paramIndex] ) { - m_Mean[i] = parameters[paramIndex] ; - changed = true ; + m_Mean[i] = parameters[paramIndex]; + changed = true; } - ++paramIndex ; + ++paramIndex; } - for ( i = 0 ; i < measurementVectorSize ; i++ ) + for ( i = 0; i < measurementVectorSize; i++ ) { - for ( j = 0 ; j < measurementVectorSize; j++ ) + for ( j = 0; j < measurementVectorSize; j++ ) { if ( m_Covariance.GetVnlMatrix().get(i, j) != parameters[paramIndex] ) { - m_Covariance.GetVnlMatrix().put(i, j, parameters[paramIndex]) ; - changed = true ; + m_Covariance.GetVnlMatrix().put(i, j, parameters[paramIndex]); + changed = true; } - ++paramIndex ; + ++paramIndex; } } - m_GaussianDensityFunction->SetCovariance(&m_Covariance) ; - this->AreParametersModified(changed) ; + m_GaussianDensityFunction->SetCovariance(&m_Covariance); + this->AreParametersModified(changed); } @@ -123,34 +125,34 @@ double GaussianMixtureModelComponent< TSample > ::CalculateParametersChange() { - unsigned int i, j ; + unsigned int i, j; - MeanType meanEstimate = *(m_MeanEstimator->GetOutput()) ; - CovarianceType covEstimate = *(m_CovarianceEstimator->GetOutput()) ; + MeanType meanEstimate = *(m_MeanEstimator->GetOutput()); + CovarianceType covEstimate = *(m_CovarianceEstimator->GetOutput()); - double temp ; - double changes = 0.0 ; + double temp; + double changes = 0.0; MeasurementVectorSizeType measurementVectorSize = this->GetSample()->GetMeasurementVectorSize(); - for ( i = 0 ; i < measurementVectorSize ; i++) + for ( i = 0; i < measurementVectorSize; i++) { - temp = m_Mean[i] - meanEstimate[i] ; - changes += temp * temp ; + temp = m_Mean[i] - meanEstimate[i]; + changes += temp * temp; } - for ( i = 0 ; i < measurementVectorSize ; i++ ) + for ( i = 0; i < measurementVectorSize; i++ ) { - for ( j = 0 ; j < measurementVectorSize ; j++ ) + for ( j = 0; j < measurementVectorSize; j++ ) { temp = m_Covariance.GetVnlMatrix().get(i, j) - - covEstimate.GetVnlMatrix().get(i, j) ; - changes += temp * temp ; + covEstimate.GetVnlMatrix().get(i, j); + changes += temp * temp; } } - changes = vcl_sqrt(changes) ; - return changes ; + changes = vcl_sqrt(changes); + return changes; } template< class TSample > @@ -161,84 +163,83 @@ GaussianMixtureModelComponent< TSample > MeasurementVectorSizeType measurementVectorSize = this->GetSample()->GetMeasurementVectorSize(); - this->AreParametersModified(false) ; + this->AreParametersModified(false); - m_MeanEstimator->Update() ; + m_MeanEstimator->Update(); - unsigned int i, j ; - double temp ; - double changes ; - bool changed = false ; - ParametersType parameters = this->GetFullParameters() ; - int paramIndex = 0 ; + unsigned int i, j; + double temp; + double changes; + bool changed = false; + ParametersType parameters = this->GetFullParameters(); + int paramIndex = 0; - MeanType meanEstimate = *(m_MeanEstimator->GetOutput()) ; - for ( i = 0 ; i < measurementVectorSize ; i++) + MeanType meanEstimate = *(m_MeanEstimator->GetOutput()); + for ( i = 0; i < measurementVectorSize; i++) { - temp = m_Mean[i] - meanEstimate[i] ; - changes = temp * temp ; - changes = vcl_sqrt(changes) ; + temp = m_Mean[i] - meanEstimate[i]; + changes = temp * temp; + changes = vcl_sqrt(changes); if ( changes > this->GetMinimalParametersChange() ) { - changed = true ; + changed = true; } } if ( changed ) { - m_Mean = *(m_MeanEstimator->GetOutput()) ; - for ( i = 0 ; i < measurementVectorSize ; i++) + m_Mean = *(m_MeanEstimator->GetOutput()); + for ( i = 0; i < measurementVectorSize; i++) { parameters[paramIndex] = meanEstimate[i]; - ++paramIndex ; + ++paramIndex; } - this->AreParametersModified(true) ; + this->AreParametersModified(true); } else { - paramIndex = measurementVectorSize ; + paramIndex = measurementVectorSize; } - m_CovarianceEstimator->Update() ; - CovarianceType covEstimate = *(m_CovarianceEstimator->GetOutput()) ; - changed = false ; - for ( i = 0 ; i < measurementVectorSize ; i++ ) + m_CovarianceEstimator->Update(); + CovarianceType covEstimate = *(m_CovarianceEstimator->GetOutput()); + changed = false; + for ( i = 0; i < measurementVectorSize; i++ ) { - for ( j = 0 ; j < measurementVectorSize ; j++ ) + for ( j = 0; j < measurementVectorSize; j++ ) { temp = m_Covariance.GetVnlMatrix().get(i, j) - - covEstimate.GetVnlMatrix().get(i, j) ; - changes = temp * temp ; - changes = vcl_sqrt(changes) ; + covEstimate.GetVnlMatrix().get(i, j); + changes = temp * temp; + changes = vcl_sqrt(changes); if ( changes > this->GetMinimalParametersChange() ) { - changed = true ; + changed = true; } } } if ( changed ) { - m_Covariance = *(m_CovarianceEstimator->GetOutput()) ; - for ( i = 0 ; i < measurementVectorSize ; i++ ) + m_Covariance = *(m_CovarianceEstimator->GetOutput()); + for ( i = 0; i < measurementVectorSize; i++ ) { - for ( j = 0 ; j < measurementVectorSize ; j++ ) + for ( j = 0; j < measurementVectorSize; j++ ) { - parameters[paramIndex] = covEstimate.GetVnlMatrix().get(i, j) ; - ++paramIndex ; + parameters[paramIndex] = covEstimate.GetVnlMatrix().get(i, j); + ++paramIndex; } } - this->AreParametersModified(true) ; + this->AreParametersModified(true); } - Superclass::SetParameters(parameters) ; + Superclass::SetParameters(parameters); + //update covariance and its inverse of Gaussian mixture + m_GaussianDensityFunction->SetCovariance( &m_Covariance ); } } // end of namespace Statistics } // end of namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitComponentBase.h b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitComponentBase.h index 8dccb0a1b9..673574b057 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitComponentBase.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitComponentBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGoodnessOfFitComponentBase.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:56 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-04 15:23:48 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,8 +26,8 @@ #include "vnl/vnl_matrix.h" #include "itkVariableSizeMatrix.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class GoodnessOfFitComponentBase * \brief provides component (module) type specific functionalities @@ -92,138 +92,138 @@ class GoodnessOfFitComponentBase public: /** Standard class typedefs */ typedef GoodnessOfFitComponentBase Self; - typedef Object Superclass; - typedef SmartPointer< Self > Pointer; + typedef Object Superclass; + typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(GoodnessOfFitComponentBase, Object) ; + itkTypeMacro(GoodnessOfFitComponentBase, Object); /** TInputSample type alias */ - typedef TInputSample InputSampleType ; + typedef TInputSample InputSampleType; /** Typedefs from the TInputSample */ - typedef typename TInputSample::MeasurementType MeasurementType ; - typedef typename TInputSample::MeasurementVectorType MeasurementVectorType ; + typedef typename TInputSample::MeasurementType MeasurementType; + typedef typename TInputSample::MeasurementVectorType MeasurementVectorType; typedef typename TInputSample::MeasurementVectorSizeType MeasurementVectorSizeType; /** Resample() output type */ - typedef Subsample< TInputSample > ResampledSampleType ; + typedef Subsample< TInputSample > ResampledSampleType; - /** Histogram type that will be used for observed and expected histogram*/ - typedef Histogram< float, 1 > HistogramType ; - typedef typename HistogramType::Pointer HistogramPointer ; - typedef typename HistogramType::ConstPointer HistogramConstPointer ; + /** Histogram type that will be used for observed and expected +* histogram */ + typedef Histogram< float, 1 > HistogramType; + typedef typename HistogramType::Pointer HistogramPointer; + typedef typename HistogramType::ConstPointer HistogramConstPointer; /** Type of the array of component parameters */ - typedef Array< double > ParametersType ; + typedef Array< double > ParametersType; /** Type of the center position for the hyperspherical neighborhood * sampling */ typedef Array< double > CenterType; /** Type of the radius of the hyperspherical neighborhood sampling */ - typedef double RadiusType ; + typedef double RadiusType; /** Type of the mean of the distribution */ - typedef Array< double > MeanType ; + typedef Array< double > MeanType; /** Type of standard deviation of the distribution */ - typedef double StandardDeviationType ; + typedef double StandardDeviationType; /** Set/Gets the input sample */ - virtual void SetInputSample(const TInputSample* sample) ; + virtual void SetInputSample(const TInputSample* sample); const TInputSample* GetInputSample() const; /** Gets the total number of parameters for this component */ - virtual unsigned int GetNumberOfParameters() const = 0 ; + virtual unsigned int GetNumberOfParameters() const = 0; /** Set/Gets the component parameters */ - virtual void SetParameters(const ParametersType ¶meters) ; + virtual void SetParameters(const ParametersType ¶meters); ParametersType* GetParameters() - { return m_Parameters ; } + { return m_Parameters; } /** Sets the flag that indicates this component uses the histogram - * generated with expected distribution from the parameters.*/ - void SetUseExpectedHistogram(bool flag) ; + * generated with expected distribution from the parameters. */ + void SetUseExpectedHistogram(bool flag); /** Set/Gets the nubmer of bins of histograms (expected and observed) */ - void SetHistogramNumberOfBins(int numberOfBins) ; + void SetHistogramNumberOfBins(int numberOfBins); int GetHistogramNumberOfBins() - { return m_HistogramNumberOfBins ; } + { return m_HistogramNumberOfBins; } /** Set/Gets the flag that indicates the probability of each bins in the * histograms should be equal. This can be achieved by varying the * interval of bins. */ - void SetHistogramUseEquiProbableBins(bool flag) ; + void SetHistogramUseEquiProbableBins(bool flag); bool GetHistogramUseEquiProbableBins() - { return m_HistogramUseEquiProbableBins ; } + { return m_HistogramUseEquiProbableBins; } /** Set/Get the overlapping effects extent. */ - void SetHistogramBinOverlap(double overlap) ; + void SetHistogramBinOverlap(double overlap); double GetHistogramBinOverlap() - { return m_HistogramBinOverlap ; } + { return m_HistogramBinOverlap; } /** Set/Gets the extent of histogram from the mean in terms of * standard deivation */ - void SetHistogramExtent(double extent) ; + void SetHistogramExtent(double extent); double GetHistogramExtent() - { return m_HistogramExtent ; } + { return m_HistogramExtent; } /** Gets the center position for the neighborhood sampling */ - virtual CenterType* GetCenter() = 0 ; + virtual CenterType* GetCenter() = 0; /** Gets the radius for the neighborhood sampling */ - virtual RadiusType* GetRadius() = 0 ; + virtual RadiusType* GetRadius() = 0; /** Gets the mean of the distribution */ - virtual MeanType* GetMean() = 0 ; + virtual MeanType* GetMean() = 0; /** Gets the standard deviation of the distribution */ - virtual RadiusType* GetStandardDeviation() = 0 ; + virtual RadiusType* GetStandardDeviation() = 0; /** Generates the histogram (expected and observed) */ - virtual void CreateHistograms() ; + virtual void CreateHistograms(); /** Samples measurement vectors using the center and radius */ - virtual void Resample() ; + virtual void Resample(); /** Gets the sampled data set */ ResampledSampleType* GetResampledSample() - { return m_Resampler->GetOutput() ; } + { return m_Resampler->GetOutput(); } /** Gest the size of the sampled data set */ - virtual unsigned int GetResampledSampleSize() ; + virtual unsigned int GetResampledSampleSize(); /** Calculates the longest axis based on eigen analysis */ - virtual void CalculateProjectionAxes() = 0 ; + virtual void CalculateProjectionAxes() = 0; /** Projects measurement vectors onto the projection axis calculated * by the CalculateProjectionAxes method. */ - virtual void Project(int projectionAxisIndex) ; + virtual void Project(int projectionAxisIndex); /** Fills up the expected histogram based on the distribution * parameters */ - virtual void UpdateExpectedHistogram() ; + virtual void UpdateExpectedHistogram(); /** Gets the total scale of the observed histogram */ double* GetTotalObservedScale() - { return &m_TotalObservedScale ; } + { return &m_TotalObservedScale; } /** Gets the probability of x. univariate function */ - virtual double GetCumulativeProbability(double x) - const = 0 ; + virtual double GetCumulativeProbability(double x) const = 0; /** Gets the probability density of measurements. multivariate * function */ virtual double GetProbabilityDensity(MeasurementVectorType &measurements) - const = 0 ; + const = 0; /** Gets the proportion of this component among multiple components. */ virtual double GetProportion() const - { return m_Proportion ; } + { return m_Proportion; } /** Gets the observed historm */ HistogramType * GetObservedHistogram(); @@ -232,10 +232,10 @@ public: HistogramType * GetExpectedHistogram(); /** Prints component parameters. For debugging */ - virtual void PrintParameters(std::ostream &os) const = 0 ; + virtual void PrintParameters(std::ostream &os) const = 0; /** Gest the parameters of this component */ - virtual ParametersType GetFullParameters() const = 0 ; + virtual ParametersType GetFullParameters() const = 0; /** Get Macro to get the length of a measurement vector. This is equal to * the length of each measurement vector contained in the samples that are @@ -244,16 +244,16 @@ public: itkGetConstMacro( MeasurementVectorSize, MeasurementVectorSizeType ); protected: - GoodnessOfFitComponentBase() ; - virtual ~GoodnessOfFitComponentBase() ; - virtual void PrintSelf(std::ostream& os, Indent indent) const ; + GoodnessOfFitComponentBase(); + virtual ~GoodnessOfFitComponentBase(); + virtual void PrintSelf(std::ostream& os, Indent indent) const; /** default resampler type and realted types */ - typedef NeighborhoodSampler< TInputSample > ResamplerType ; + typedef NeighborhoodSampler< TInputSample > ResamplerType; - /** default projection filter type*/ + /** default projection filter type */ typedef SampleToHistogramProjectionFilter< ResampledSampleType, float > - ProjectorType ; + ProjectorType; /** projection axis array type. The type of output from @@ -263,48 +263,48 @@ protected: ProjectionAxisArrayType* GetProjectionAxes() - { return &m_ProjectionAxes ; } + { return &m_ProjectionAxes; } /** Creates an empty histogram with bins having same interval */ - virtual void CreateEquiRangeBins() ; + virtual void CreateEquiRangeBins(); /** Creates an empty histogram with bins having same probability * based on the distribution parameters */ - virtual void CreateEquiProbableBins() ; + virtual void CreateEquiProbableBins(); private: /** Length of each measurement vector */ MeasurementVectorSizeType m_MeasurementVectorSize; - const TInputSample* m_InputSample ; - ParametersType m_Parameters ; + const TInputSample* m_InputSample; + ParametersType m_Parameters; /** helper classes */ - typename ResamplerType::Pointer m_Resampler ; - typename ProjectorType::Pointer m_Projector ; + typename ResamplerType::Pointer m_Resampler; + typename ProjectorType::Pointer m_Projector; - ProjectionAxisArrayType m_ProjectionAxes ; + ProjectionAxisArrayType m_ProjectionAxes; /** Histogram parameters */ - unsigned int m_HistogramNumberOfBins ; - bool m_HistogramUseEquiProbableBins ; - double m_HistogramExtent ; - double m_HistogramBinOverlap ; - bool m_HistogramSizeChanged ; + unsigned int m_HistogramNumberOfBins; + bool m_HistogramUseEquiProbableBins; + double m_HistogramExtent; + double m_HistogramBinOverlap; + bool m_HistogramSizeChanged; /** Histogram statistics */ - double m_TotalObservedScale ; - double m_HistogramMean ; - double m_HistogramStandardDeviation ; + double m_TotalObservedScale; + double m_HistogramMean; + double m_HistogramStandardDeviation; - double m_Proportion ; + double m_Proportion; /** resampled sample projected to a histogram */ - HistogramPointer m_ObservedHistogram ; - HistogramPointer m_ExpectedHistogram ; - bool m_UseExpectedHistogram ; + HistogramPointer m_ObservedHistogram; + HistogramPointer m_ExpectedHistogram; + bool m_UseExpectedHistogram; -} ; // end of class +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -314,4 +314,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitComponentBase.txx b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitComponentBase.txx index 844a773b63..0d5abcf904 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitComponentBase.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitComponentBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGoodnessOfFitComponentBase.txx,v $ Language: C++ - Date: $Date: 2005-08-07 12:10:37 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-03-04 15:23:49 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,38 +20,38 @@ #include "itkGoodnessOfFitComponentBase.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TInputSample > GoodnessOfFitComponentBase< TInputSample > ::GoodnessOfFitComponentBase() : m_MeasurementVectorSize( 0 ) { - m_InputSample = 0 ; - m_Resampler = ResamplerType::New() ; - - m_HistogramNumberOfBins = 0 ; - m_HistogramBinOverlap = 0.75 ; - m_HistogramExtent = 1.5 ; - m_HistogramMean = 0.0 ; - m_HistogramStandardDeviation = 0.0 ; - m_HistogramUseEquiProbableBins = true ; - m_UseExpectedHistogram = true ; + m_InputSample = 0; + m_Resampler = ResamplerType::New(); + + m_HistogramNumberOfBins = 0; + m_HistogramBinOverlap = 0.75; + m_HistogramExtent = 1.5; + m_HistogramMean = 0.0; + m_HistogramStandardDeviation = 0.0; + m_HistogramUseEquiProbableBins = true; + m_UseExpectedHistogram = true; m_HistogramSizeChanged = true; - m_Projector = ProjectorType::New() ; - m_Projector->SetInputSample(m_Resampler->GetOutput()) ; - m_Projector->SetHistogramBinOverlap(m_HistogramBinOverlap) ; + m_Projector = ProjectorType::New(); + m_Projector->SetInputSample(m_Resampler->GetOutput()); + m_Projector->SetHistogramBinOverlap(m_HistogramBinOverlap); - m_ObservedHistogram = 0 ; - m_ExpectedHistogram = 0 ; + m_ObservedHistogram = 0; + m_ExpectedHistogram = 0; - m_Proportion = 0.5 ; - //ProjectionAxisType tempAxis ; - //tempAxis.Fill(0.0) ; - //m_ProjectionAxes.Fill(tempAxis) ; - m_TotalObservedScale = 0.0 ; + m_Proportion = 0.5; + //ProjectionAxisType tempAxis; + //tempAxis.Fill(0.0); + //m_ProjectionAxes.Fill(tempAxis); + m_TotalObservedScale = 0.0; } template< class TInputSample > @@ -67,7 +67,7 @@ GoodnessOfFitComponentBase< TInputSample > { Superclass::PrintSelf(os,indent); - os << indent << "Input Sample: " ; + os << indent << "Input Sample: "; if ( m_InputSample != 0 ) { os << m_InputSample << std::endl; @@ -75,7 +75,7 @@ GoodnessOfFitComponentBase< TInputSample > } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } if(!m_Parameters.empty()) @@ -88,24 +88,24 @@ GoodnessOfFitComponentBase< TInputSample > os << indent << "Projection Axes: " << m_ProjectionAxes << std::endl; os << indent << "Total Observed Scale: " << m_TotalObservedScale << std::endl; - os << indent << "Observed Histogram: " ; + os << indent << "Observed Histogram: "; if ( m_ObservedHistogram.IsNotNull() ) { os << m_ObservedHistogram << std::endl; } else { - os << "not allocated." << std::endl ; + os << "not allocated." << std::endl; } - os << indent << "Expected Histogram: " ; + os << indent << "Expected Histogram: "; if ( m_ExpectedHistogram.IsNotNull() ) { - os << m_ExpectedHistogram << std::endl ; + os << m_ExpectedHistogram << std::endl; } else { - os << "not allocated yet." << std::endl ; + os << "not allocated yet." << std::endl; } os << indent << "Histogram Number of Bins: " @@ -131,17 +131,17 @@ GoodnessOfFitComponentBase< TInputSample > { if ( m_InputSample != sample ) { - m_InputSample = sample ; + m_InputSample = sample; // Get length of measurement vector from the sample and set the // length of the arrays. this->m_MeasurementVectorSize = m_InputSample->GetMeasurementVectorSize(); this->m_ProjectionAxes.SetSize( this->m_MeasurementVectorSize, this->m_MeasurementVectorSize ); - m_ProjectionAxes.Fill(0.0) ; + m_ProjectionAxes.Fill(0.0); - m_Resampler->SetInputSample(m_InputSample) ; - this->Modified() ; + m_Resampler->SetInputSample(m_InputSample); + this->Modified(); } } @@ -150,7 +150,7 @@ const TInputSample* GoodnessOfFitComponentBase< TInputSample > ::GetInputSample() const { - return m_InputSample ; + return m_InputSample; } template< class TInputSample > @@ -160,8 +160,8 @@ GoodnessOfFitComponentBase< TInputSample > { if ( m_Parameters != parameters ) { - m_Parameters = parameters ; - this->Modified() ; + m_Parameters = parameters; + this->Modified(); } } @@ -172,8 +172,8 @@ GoodnessOfFitComponentBase< TInputSample > { if ( m_UseExpectedHistogram != flag ) { - m_UseExpectedHistogram = flag ; - this->Modified() ; + m_UseExpectedHistogram = flag; + this->Modified(); } } @@ -184,9 +184,9 @@ GoodnessOfFitComponentBase< TInputSample > { if ( m_HistogramNumberOfBins != (unsigned int)numberOfBins ) { - m_HistogramNumberOfBins = numberOfBins ; - m_HistogramSizeChanged = true ; - this->Modified() ; + m_HistogramNumberOfBins = numberOfBins; + m_HistogramSizeChanged = true; + this->Modified(); } } @@ -197,9 +197,9 @@ GoodnessOfFitComponentBase< TInputSample > { if ( m_HistogramBinOverlap != histogramBinOverlap ) { - m_HistogramBinOverlap = histogramBinOverlap ; - m_Projector->SetHistogramBinOverlap(histogramBinOverlap) ; - this->Modified() ; + m_HistogramBinOverlap = histogramBinOverlap; + m_Projector->SetHistogramBinOverlap(histogramBinOverlap); + this->Modified(); } } @@ -210,8 +210,8 @@ GoodnessOfFitComponentBase< TInputSample > { if ( m_HistogramExtent != histogramExtent ) { - m_HistogramExtent = histogramExtent ; - this->Modified() ; + m_HistogramExtent = histogramExtent; + this->Modified(); } } @@ -222,8 +222,8 @@ GoodnessOfFitComponentBase< TInputSample > { if ( m_HistogramUseEquiProbableBins != flag ) { - m_HistogramUseEquiProbableBins = flag ; - this->Modified() ; + m_HistogramUseEquiProbableBins = flag; + this->Modified(); } } @@ -234,57 +234,57 @@ GoodnessOfFitComponentBase< TInputSample > { if (m_HistogramNumberOfBins < 1) { - return ; + return; } - HistogramType::SizeType size ; + HistogramType::SizeType size; - size[0] = m_HistogramNumberOfBins ; + size[0] = m_HistogramNumberOfBins; - m_ObservedHistogram->Initialize(size) ; + m_ObservedHistogram->Initialize(size); - m_ObservedHistogram->SetBinMin(0, 0, -m_HistogramExtent) ; + m_ObservedHistogram->SetBinMin(0, 0, -m_HistogramExtent); double binMinProbability = - this->GetCumulativeProbability(-m_HistogramExtent) ; + this->GetCumulativeProbability(-m_HistogramExtent); double step = - (1.0 - 2.0 * binMinProbability) / (double)m_HistogramNumberOfBins ; + (1.0 - 2.0 * binMinProbability) / (double)m_HistogramNumberOfBins; - HistogramType::InstanceIdentifier binId ; - double rangeExtent ; - MeasurementType tempMin ; - MeasurementType tempMax = NumericTraits< MeasurementType >::Zero ; - double binMaxProbability = 0.0 ; + HistogramType::InstanceIdentifier binId; + double rangeExtent; + MeasurementType tempMin; + MeasurementType tempMax = NumericTraits< MeasurementType >::Zero; + double binMaxProbability = 0.0; - for(binId = 0 ; binId < m_HistogramNumberOfBins ; binId++) + for(binId = 0; binId < m_HistogramNumberOfBins; binId++) { - tempMin = m_ObservedHistogram->GetBinMin(0, binId) ; + tempMin = m_ObservedHistogram->GetBinMin(0, binId); - for (rangeExtent = 0.00001; rangeExtent < 2.0 ; rangeExtent += 0.00001) + for (rangeExtent = 0.00001; rangeExtent < 2.0; rangeExtent += 0.00001) { - tempMax = tempMin + rangeExtent ; + tempMax = tempMin + rangeExtent; binMaxProbability = - this->GetCumulativeProbability(tempMax) ; + this->GetCumulativeProbability(tempMax); if ( (binMaxProbability - binMinProbability) > step ) { - break ; + break; } } - m_ObservedHistogram->SetBinMax(0, binId, tempMax) ; + m_ObservedHistogram->SetBinMax(0, binId, tempMax); - binMinProbability = binMaxProbability ; + binMinProbability = binMaxProbability; if ( binId < (m_HistogramNumberOfBins - 1) ) { - m_ObservedHistogram->SetBinMin(0, binId + 1, tempMax) ; + m_ObservedHistogram->SetBinMin(0, binId + 1, tempMax); } } m_ObservedHistogram-> - SetBinMax(0, m_HistogramNumberOfBins - 1, m_HistogramExtent) ; + SetBinMax(0, m_HistogramNumberOfBins - 1, m_HistogramExtent); } template< class TInputSample > @@ -294,18 +294,18 @@ GoodnessOfFitComponentBase< TInputSample > { if (m_HistogramNumberOfBins < 1) { - return ; + return; } - HistogramType::SizeType size ; - HistogramType::MeasurementVectorType lowerBound ; - HistogramType::MeasurementVectorType upperBound ; + HistogramType::SizeType size; + HistogramType::MeasurementVectorType lowerBound; + HistogramType::MeasurementVectorType upperBound; - size[0] = m_HistogramNumberOfBins ; - lowerBound[0] = -m_HistogramExtent ; - upperBound[0] = m_HistogramExtent ; + size[0] = m_HistogramNumberOfBins; + lowerBound[0] = -m_HistogramExtent; + upperBound[0] = m_HistogramExtent; - m_ObservedHistogram->Initialize(size, lowerBound, upperBound) ; + m_ObservedHistogram->Initialize(size, lowerBound, upperBound); } template< class TInputHistogram > @@ -313,34 +313,34 @@ void GoodnessOfFitComponentBase< TInputHistogram > ::CreateHistograms() { - m_TotalObservedScale = this->GetCumulativeProbability(m_HistogramExtent) ; - m_TotalObservedScale = m_TotalObservedScale - (1.0f - m_TotalObservedScale) ; - m_HistogramMean = (double(m_HistogramNumberOfBins) - 1.0) / 2.0 ; - m_HistogramStandardDeviation = m_HistogramMean / m_HistogramExtent ; + m_TotalObservedScale = this->GetCumulativeProbability(m_HistogramExtent); + m_TotalObservedScale = m_TotalObservedScale - (1.0f - m_TotalObservedScale); + m_HistogramMean = (double(m_HistogramNumberOfBins) - 1.0) / 2.0; + m_HistogramStandardDeviation = m_HistogramMean / m_HistogramExtent; - m_ObservedHistogram = HistogramType::New() ; + m_ObservedHistogram = HistogramType::New(); if ( m_HistogramUseEquiProbableBins ) { - this->CreateEquiProbableBins() ; + this->CreateEquiProbableBins(); } else { - this->CreateEquiRangeBins() ; + this->CreateEquiRangeBins(); } - m_Projector->SetHistogram(m_ObservedHistogram.GetPointer()) ; + m_Projector->SetHistogram(m_ObservedHistogram.GetPointer()); if ( m_UseExpectedHistogram ) { - m_ExpectedHistogram = HistogramType::New() ; - HistogramType::SizeType size ; - size[0] = m_HistogramNumberOfBins ; - m_ExpectedHistogram->Initialize(size) ; + m_ExpectedHistogram = HistogramType::New(); + HistogramType::SizeType size; + size[0] = m_HistogramNumberOfBins; + m_ExpectedHistogram->Initialize(size); } - m_HistogramSizeChanged = false ; + m_HistogramSizeChanged = false; } template< class TInputSample > @@ -348,9 +348,9 @@ void GoodnessOfFitComponentBase< TInputSample > ::Resample() { - m_Resampler->SetCenter(this->GetCenter()) ; - m_Resampler->SetRadius(this->GetRadius()) ; - m_Resampler->Update() ; + m_Resampler->SetCenter(this->GetCenter()); + m_Resampler->SetRadius(this->GetRadius()); + m_Resampler->Update(); } @@ -359,7 +359,7 @@ unsigned int GoodnessOfFitComponentBase< TInputSample > ::GetResampledSampleSize() { - return m_Resampler->GetOutput()->Size() ; + return m_Resampler->GetOutput()->Size(); } @@ -368,8 +368,8 @@ void GoodnessOfFitComponentBase< TInputSample > ::Project(int projectionAxisIndex) { - m_Projector->SetMean(this->GetMean()) ; - m_Projector->SetStandardDeviation(this->GetStandardDeviation()) ; + m_Projector->SetMean(this->GetMean()); + m_Projector->SetStandardDeviation(this->GetStandardDeviation()); Array< double > projectionAxis( m_MeasurementVectorSize ); for( unsigned int i=0; i< m_MeasurementVectorSize; i++ ) @@ -377,7 +377,7 @@ GoodnessOfFitComponentBase< TInputSample > projectionAxis[i] = m_ProjectionAxes(projectionAxisIndex, i ); } m_Projector->SetProjectionAxis( &projectionAxis ); - m_Projector->Update() ; + m_Projector->Update(); } template< class TInputHistogram > @@ -385,22 +385,22 @@ void GoodnessOfFitComponentBase< TInputHistogram > ::UpdateExpectedHistogram() { - float totalObservedFrequency = m_ObservedHistogram->GetTotalFrequency() ; - HistogramType::Iterator e_iter = m_ExpectedHistogram->Begin() ; - HistogramType::Iterator e_last = m_ExpectedHistogram->End() ; - int i = 0 ; + float totalObservedFrequency = m_ObservedHistogram->GetTotalFrequency(); + HistogramType::Iterator e_iter = m_ExpectedHistogram->Begin(); + HistogramType::Iterator e_last = m_ExpectedHistogram->End(); + int i = 0; float frequency; while (e_iter != e_last) { frequency = this->GetCumulativeProbability(m_ObservedHistogram->GetBinMax(0, i)) - - this->GetCumulativeProbability(m_ObservedHistogram->GetBinMin(0, i)) ; + this->GetCumulativeProbability(m_ObservedHistogram->GetBinMin(0, i)); frequency = (frequency / m_TotalObservedScale) * - totalObservedFrequency ; + totalObservedFrequency; - e_iter.SetFrequency(frequency) ; - ++e_iter ; - ++i ; + e_iter.SetFrequency(frequency); + ++e_iter; + ++i; } } @@ -409,7 +409,7 @@ typename GoodnessOfFitComponentBase< TInputSample >::HistogramType * GoodnessOfFitComponentBase< TInputSample > ::GetObservedHistogram() { - return m_ObservedHistogram ; + return m_ObservedHistogram; } template< class TInputSample > @@ -417,7 +417,7 @@ typename GoodnessOfFitComponentBase< TInputSample >::HistogramType * GoodnessOfFitComponentBase< TInputSample > ::GetExpectedHistogram() { - return m_ExpectedHistogram ; + return m_ExpectedHistogram; } } // end of namespace Statistics diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitFunctionBase.h b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitFunctionBase.h index e06a184983..26537fb7f5 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitFunctionBase.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitFunctionBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGoodnessOfFitFunctionBase.h,v $ Language: C++ - Date: $Date: 2004-11-04 20:40:41 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 15:23:49 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include "itkFunctionBase.h" #include "itkGoodnessOfFitComponentBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class GoodnessOfFitFunctionBase * \brief base class for classes calculates different types of goodness-of-fit @@ -41,64 +41,65 @@ class GoodnessOfFitFunctionBase { public: /** Standard class typedefs */ - typedef GoodnessOfFitFunctionBase Self; + typedef GoodnessOfFitFunctionBase Self; typedef SampleAlgorithmBase< TInputHistogram > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer< const Self > ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(GoodnessOfFitFunctionBase, - SampleAlgorithimBase) ; + SampleAlgorithimBase); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** typedefs from Superclass */ itkStaticConstMacro(MeasurementVectorSize, unsigned int, - TInputHistogram::MeasurementVectorSize) ; - typedef typename TInputHistogram::MeasurementType MeasurementType ; - typedef typename TInputHistogram::MeasurementVectorType MeasurementVectorType ; - typedef TInputHistogram InputHistogramType ; + TInputHistogram::MeasurementVectorSize); + + typedef typename TInputHistogram::MeasurementType MeasurementType; + typedef typename TInputHistogram::MeasurementVectorType MeasurementVectorType; + typedef TInputHistogram InputHistogramType; /** Sets the observed histogram input */ - void SetObservedHistogram(InputHistogramType* histogram) ; + void SetObservedHistogram(InputHistogramType* histogram); /** Gets the observed histogram */ InputHistogramType* GetObservedHistogram() - { return m_ObservedHistogram ; } + { return m_ObservedHistogram; } /** Sets the expected histogram input */ - void SetExpectedHistogram(InputHistogramType* histogram) ; + void SetExpectedHistogram(InputHistogramType* histogram); /** Gets the expected histogram input */ InputHistogramType* GetExpectedHistogram() - { return m_ExpectedHistogram ; } + { return m_ExpectedHistogram; } /** Sets the flag that tells if a subclass needs * the expected histogram for goodness-of-fit statistics * calculation. This flag should be set only by a subclass */ - itkGetMacro(UseExpectedHistogram, bool) ; + itkGetMacro(UseExpectedHistogram, bool); void SetTotalObservedScale(double* scale) - { + { if ( m_TotalObservedScale != scale ) { - m_TotalObservedScale = scale ; - this->Modified() ; + m_TotalObservedScale = scale; + this->Modified(); } - } + } - typedef double OutputType ; + typedef double OutputType; OutputType& GetOutput() - { return m_Output ; } + { return m_Output; } protected: - GoodnessOfFitFunctionBase() ; - virtual ~GoodnessOfFitFunctionBase(){} ; + GoodnessOfFitFunctionBase(); + virtual ~GoodnessOfFitFunctionBase(){}; void PrintSelf(std::ostream& os, Indent indent) const; - itkSetMacro(UseExpectedHistogram, bool) ; + itkSetMacro(UseExpectedHistogram, bool); virtual void GenerateData() {} @@ -106,18 +107,18 @@ protected: itkGetConstReferenceMacro(LogEpsilon,float); private: - float m_Epsilon ; - float m_LogEpsilon ; + float m_Epsilon; + float m_LogEpsilon; - bool m_UseExpectedHistogram ; + bool m_UseExpectedHistogram; - InputHistogramType* m_ObservedHistogram ; - InputHistogramType* m_ExpectedHistogram ; + InputHistogramType* m_ObservedHistogram; + InputHistogramType* m_ExpectedHistogram; - double* m_TotalObservedScale ; - OutputType m_Output ; + double* m_TotalObservedScale; + OutputType m_Output; -} ; // end of class +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -127,4 +128,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitFunctionBase.txx b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitFunctionBase.txx index cfbe5ae704..60d8372646 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitFunctionBase.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitFunctionBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGoodnessOfFitFunctionBase.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:37:20 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-04 15:23:49 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,24 +19,24 @@ #include "itkGoodnessOfFitFunctionBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TInputHistogram > GoodnessOfFitFunctionBase< TInputHistogram > ::GoodnessOfFitFunctionBase() { - m_Epsilon = 1e-20 ; - m_LogEpsilon = vcl_log(m_Epsilon) ; + m_Epsilon = 1e-20; + m_LogEpsilon = vcl_log(m_Epsilon); - m_UseExpectedHistogram = true ; - m_ObservedHistogram = 0 ; - m_ExpectedHistogram = 0 ; + m_UseExpectedHistogram = true; + m_ObservedHistogram = 0; + m_ExpectedHistogram = 0; - m_UseExpectedHistogram = false ; - m_TotalObservedScale = 0 ; + m_UseExpectedHistogram = false; + m_TotalObservedScale = 0; - m_Output = 0.0 ; + m_Output = 0.0; } template< class TInputHistogram > @@ -44,35 +44,35 @@ void GoodnessOfFitFunctionBase< TInputHistogram > ::PrintSelf(std::ostream& os, Indent indent) const { - Superclass::PrintSelf(os, indent) ; + Superclass::PrintSelf(os, indent); - os << indent << "ObservedHistogram: " ; + os << indent << "ObservedHistogram: "; if ( m_ObservedHistogram != 0 ) { - os << m_ObservedHistogram << std::endl ; + os << m_ObservedHistogram << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "ExpectedHistogram: " ; + os << indent << "ExpectedHistogram: "; if ( m_ExpectedHistogram != 0 ) { - os << m_ExpectedHistogram << std::endl ; + os << m_ExpectedHistogram << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "Output: " << m_Output << std::endl ; + os << indent << "Output: " << m_Output << std::endl; os << indent << "Total Observed Scale: " << m_TotalObservedScale - << std::endl ; + << std::endl; os << indent << "Use Expected Histogram: " << m_UseExpectedHistogram - << std::endl ; - os << indent << "Epsilon: " << m_Epsilon << std::endl ; - os << indent << "Log(Epsilon): " << m_LogEpsilon << std::endl ; + << std::endl; + os << indent << "Epsilon: " << m_Epsilon << std::endl; + os << indent << "Log(Epsilon): " << m_LogEpsilon << std::endl; } template< class TInputHistogram > @@ -80,8 +80,8 @@ void GoodnessOfFitFunctionBase< TInputHistogram > ::SetObservedHistogram(InputHistogramType* histogram) { - m_ObservedHistogram = histogram ; - this->Modified() ; + m_ObservedHistogram = histogram; + this->Modified(); } template< class TInputHistogram > @@ -89,12 +89,11 @@ void GoodnessOfFitFunctionBase< TInputHistogram > ::SetExpectedHistogram(InputHistogramType* histogram) { - m_ExpectedHistogram = histogram ; - this->Modified() ; + m_ExpectedHistogram = histogram; + this->Modified(); } } // end of namespace Statistics } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitMixtureModelCostFunction.h b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitMixtureModelCostFunction.h index 9e3e5dbcbc..9a2a647871 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitMixtureModelCostFunction.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitMixtureModelCostFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGoodnessOfFitMixtureModelCostFunction.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:57 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 15:23:49 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,8 +23,8 @@ #include "itkGoodnessOfFitFunctionBase.h" #include "itkFunctionBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class GoodnessOfFitMixtureModelCostFunction * \brief calculates the goodness-of-fit statstics for multivarate @@ -49,7 +49,7 @@ namespace Statistics{ * 5) calculates the discrepancy between the observed histogram and * the expected histogram using a goodness-of-fit statistics * 6) repeat step 3) - 5) and sum the goodness-of-fit values - * + * * For a mixture model, the above procedure is applied independently for each * model (module). The sum of the goodness-of-fit values of models is the * goodness-of-fit statistics for the mixture model. @@ -83,66 +83,65 @@ class ITK_EXPORT GoodnessOfFitMixtureModelCostFunction public: /** Standard class typedefs */ typedef GoodnessOfFitMixtureModelCostFunction Self; - typedef SingleValuedCostFunction Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer< const Self > ConstPointer; + typedef SingleValuedCostFunction Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(GoodnessOfFitMixtureModelCostFunction, SingleValuedCostFunction) ; + itkTypeMacro(GoodnessOfFitMixtureModelCostFunction, SingleValuedCostFunction); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); - typedef TInputSample InputSampleType ; - typedef typename TInputSample::MeasurementType MeasurementType ; - typedef typename TInputSample::MeasurementVectorType MeasurementVectorType ; + typedef TInputSample InputSampleType; + typedef typename TInputSample::MeasurementType MeasurementType; + typedef typename TInputSample::MeasurementVectorType MeasurementVectorType; typedef typename TInputSample::MeasurementVectorSizeType MeasurementVectorSizeType; /** ParametersType typedef. * It defines a position in the optimization search space. */ - typedef SingleValuedCostFunction::ParametersType ParamtersType ; + typedef SingleValuedCostFunction::ParametersType ParamtersType; /** MeasureType typedef. * It defines a type used to return the cost function value. */ - typedef SingleValuedCostFunction::MeasureType MeasureType ; + typedef SingleValuedCostFunction::MeasureType MeasureType; - typedef GoodnessOfFitComponentBase< TInputSample > ComponentType ; - typedef std::vector< ComponentType* > ComponentVectorType ; + typedef GoodnessOfFitComponentBase< TInputSample > ComponentType; + typedef std::vector< ComponentType* > ComponentVectorType; typedef GoodnessOfFitFunctionBase< typename ComponentType::HistogramType > - FunctionType ; + FunctionType; /** aceesing methods for the sample manipulator */ - void AddComponent(ComponentType* component) ; + void AddComponent(ComponentType* component); /** aceesing methods for the expected probability histogram */ - void SetFunction(FunctionType* core) ; + void SetFunction(FunctionType* core); FunctionType* GetFunction() - { return m_Function ; } + { return m_Function; } - virtual unsigned int GetNumberOfParameters() const ; + virtual unsigned int GetNumberOfParameters() const; /** This method returns the value of the cost function corresponding * to the specified parameters. */ - virtual MeasureType GetValue( const ParametersType & parameters ) const ; + virtual MeasureType GetValue( const ParametersType & parameters ) const; /** This method returns the derivative of the cost function corresponding * to the specified parameters. */ virtual void GetDerivative( const ParametersType &, - DerivativeType & ) const - { /* not implemented */ } + DerivativeType & ) const {} protected: - GoodnessOfFitMixtureModelCostFunction() ; - virtual ~GoodnessOfFitMixtureModelCostFunction() ; - virtual void PrintSelf(std::ostream& os, Indent indent) const ; + GoodnessOfFitMixtureModelCostFunction(); + virtual ~GoodnessOfFitMixtureModelCostFunction(); + virtual void PrintSelf(std::ostream& os, Indent indent) const; private: /** helper classes */ - ComponentVectorType m_Components ; - FunctionType* m_Function ; -} ; // end of class + ComponentVectorType m_Components; + FunctionType* m_Function; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -152,4 +151,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitMixtureModelCostFunction.txx b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitMixtureModelCostFunction.txx index c13abf0030..98934e5641 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitMixtureModelCostFunction.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGoodnessOfFitMixtureModelCostFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGoodnessOfFitMixtureModelCostFunction.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:57 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,14 +19,14 @@ #include "itkGoodnessOfFitMixtureModelCostFunction.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TInputSample > GoodnessOfFitMixtureModelCostFunction< TInputSample > ::GoodnessOfFitMixtureModelCostFunction() { - m_Function = 0 ; + m_Function = 0; } template< class TInputSample > @@ -42,7 +42,7 @@ GoodnessOfFitMixtureModelCostFunction< TInputSample > { Superclass::PrintSelf(os,indent); os << indent << "Function " << m_Function << std::endl; - for ( unsigned int i = 0 ; i < m_Components.size() ; i++) + for ( unsigned int i = 0; i < m_Components.size(); i++) { os << indent << "Components["<< i <<"] " << m_Components[i] << std::endl; } @@ -53,7 +53,7 @@ void GoodnessOfFitMixtureModelCostFunction< TInputSample > ::AddComponent(ComponentType* component) { - m_Components.push_back(component) ; + m_Components.push_back(component); } template< class TInputSample > @@ -63,8 +63,8 @@ GoodnessOfFitMixtureModelCostFunction< TInputSample > { if ( m_Function != core ) { - m_Function = core ; - this->Modified() ; + m_Function = core; + this->Modified(); } } @@ -73,16 +73,16 @@ unsigned int GoodnessOfFitMixtureModelCostFunction< TInputSample > ::GetNumberOfParameters() const { - unsigned int size = 0 ; - ComponentType* component ; - for ( unsigned int componentIndex = 0 ; componentIndex < m_Components.size() ; + unsigned int size = 0; + ComponentType* component; + for ( unsigned int componentIndex = 0; componentIndex < m_Components.size(); componentIndex++ ) { - component = m_Components[componentIndex] ; - size += component->GetNumberOfParameters() ; + component = m_Components[componentIndex]; + size += component->GetNumberOfParameters(); } - return size ; + return size; } template< class TInputSample > @@ -92,49 +92,47 @@ GoodnessOfFitMixtureModelCostFunction< TInputSample > { unsigned int i; - double value = 0.0 ; + double value = 0.0; - unsigned int index = 0 ; + unsigned int index = 0; unsigned int paramSize; - ComponentType* component ; - for ( unsigned int componentIndex = 0 ; componentIndex < m_Components.size() ; + ComponentType* component; + for ( unsigned int componentIndex = 0; componentIndex < m_Components.size(); componentIndex++ ) { - component = m_Components[componentIndex] ; - paramSize = component->GetNumberOfParameters() ; - ParametersType params(paramSize) ; - for ( i = 0 ; i < paramSize ; i++) + component = m_Components[componentIndex]; + paramSize = component->GetNumberOfParameters(); + ParametersType params(paramSize); + for ( i = 0; i < paramSize; i++) { - params[i] = parameters[index] ; - index++ ; + params[i] = parameters[index]; + index++; } - component->SetParameters(params) ; - component-> - SetUseExpectedHistogram(m_Function->GetUseExpectedHistogram()) ; + component->SetParameters(params); + component->SetUseExpectedHistogram(m_Function->GetUseExpectedHistogram()); if ( component->GetObservedHistogram() == 0 ) { - component->CreateHistograms() ; + component->CreateHistograms(); } - component->Resample() ; + component->Resample(); if ( component->GetResampledSample()->GetTotalFrequency() == 0 ) { - return NumericTraits< double >::max() ; + return NumericTraits< double >::max(); } - component->CalculateProjectionAxes() ; + component->CalculateProjectionAxes(); m_Function-> - SetTotalObservedScale(component->GetTotalObservedScale()) ; + SetTotalObservedScale(component->GetTotalObservedScale()); - m_Function->SetObservedHistogram(component->GetObservedHistogram()) ; + m_Function->SetObservedHistogram(component->GetObservedHistogram()); if ( m_Function->GetUseExpectedHistogram() ) { - m_Function-> - SetExpectedHistogram(component->GetExpectedHistogram()) ; + m_Function->SetExpectedHistogram(component->GetExpectedHistogram()); } MeasurementVectorSizeType measurementVectorSize = @@ -143,20 +141,20 @@ GoodnessOfFitMixtureModelCostFunction< TInputSample > { itkExceptionMacro( << "Must set MeasurementVectorSize for the sample" ); } - for (i = 0 ; i < measurementVectorSize ; i++) + for (i = 0; i < measurementVectorSize; i++) { - component->Project(i) ; + component->Project(i); if ( m_Function->GetUseExpectedHistogram() ) { - component->UpdateExpectedHistogram() ; + component->UpdateExpectedHistogram(); } - m_Function->Update() ; - value += m_Function->GetOutput() ; + m_Function->Update(); + value += m_Function->GetOutput(); } } // end of while ( iter ... - return value ; + return value; } } // end of namespace Statistics diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.h b/Utilities/ITK/Code/Numerics/Statistics/itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.h index 41216961b0..a45c6e4914 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.h,v $ Language: C++ - Date: $Date: 2005-04-20 20:31:22 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-20 16:21:47 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,78 +21,78 @@ #include "itkMacro.h" namespace itk { - namespace Statistics { +namespace Statistics { /** \class GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator -* \brief This class computes texture feature coefficients from a grey level -* co-occurrence matrix. -* -* This class computes features that summarize image texture, given a grey level -* co-occurrence matrix (generated by a ScalarImageToGreyLevelCooccurrenceMatrixGenerator -* or related class). -* -* The features calculated are as follows (where \f$ g(i, j) \f$ is the element in -* cell i, j of a a normalized GLCM): -* -* "Energy" \f$ = f_1 = \sum_{i,j}g(i, j)^2 \f$ -* -* "Entropy" \f$ = f_2 = -\sum_{i,j}g(i, j) \log_2 g(i, j)\f$, or 0 if \f$g(i, j) = 0\f$ -* -* "Correlation" \f$ = f_3 = \sum_{i,j}\frac{(i - \mu)(j - \mu)g(i, j)}{\sigma^2} \f$ -* -* "Difference Moment" \f$= f_4 = \sum_{i,j}\frac{1}{1 + (i - j)^2}g(i, j) \f$ -* -* "Inertia" \f$ = f_5 = \sum_{i,j}(i - j)^2g(i, j) \f$ (sometimes called "contrast.") -* -* "Cluster Shade" \f$ = f_6 = \sum_{i,j}((i - \mu) + (j - \mu))^3 g(i, j) \f$ -* -* "Cluster Prominence" \f$ = f_7 = \sum_{i,j}((i - \mu) + (j - \mu))^4 g(i, j) \f$ -* -* "Haralick's Correlation" \f$ = f_8 = \frac{\sum_{i,j}(i, j) g(i, j) -\mu_t^2}{\sigma_t^2} \f$ -* where \f$\mu_t\f$ and \f$\sigma_t\f$ are the mean and standard deviation of the row -* (or column, due to symmetry) sums. -* -* Above, \f$ \mu = \f$ (weighted pixel average) \f$ = \sum_{i,j}i \cdot g(i, j) = -* \sum_{i,j}j \cdot g(i, j) \f$ (due to matrix summetry), and -* -* \f$ \sigma = \f$ (weighted pixel variance) \f$ = \sum_{i,j}(i - \mu)^2 \cdot g(i, j) = -* \sum_{i,j}(j - \mu)^2 \cdot g(i, j) \f$ (due to matrix summetry) -* -* A good texture feature set to use is the Conners, Trivedi and Harlow set: -* features 1, 2, 4, 5, 6, and 7. There is some correlation between the various -* features, so using all of them at the same time is not necessarialy a good idea. -* -* NOTA BENE: The input histogram will be forcably normalized! -* This algorithm takes three passes through the input -* histogram if the histogram was already normalized, and four if not. -* -* Web references: -* -* http://www.cssip.uq.edu.au/meastex/www/algs/algs/algs.html -* http://www.ucalgary.ca/~mhallbey/texture/texture_tutorial.html -* -* Print references: -* -* Haralick, R.M., K. Shanmugam and I. Dinstein. 1973. Textural Features for -* Image Classification. IEEE Transactions on Systems, Man and Cybernetics. -* SMC-3(6):610-620. -* -* Haralick, R.M. 1979. Statistical and Structural Approaches to Texture. -* Proceedings of the IEEE, 67:786-804. -* -* R.W. Conners and C.A. Harlow. A Theoretical Comaprison of Texture Algorithms. -* IEEE Transactions on Pattern Analysis and Machine Intelligence, 2:204-222, 1980. -* -* R.W. Conners, M.M. Trivedi, and C.A. Harlow. Segmentation of a High-Resolution -* Urban Scene using Texture Operators. Computer Vision, Graphics and Image -* Processing, 25:273-310, 1984. -* -* \sa ScalarImageToGreyLevelCooccurrenceMatrixGenerator -* \sa MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator -* \sa ScalarImageTextureCalculator -* -* Author: Zachary Pincus -*/ + * \brief This class computes texture feature coefficients from a grey level + * co-occurrence matrix. + * + * This class computes features that summarize image texture, given a grey level + * co-occurrence matrix (generated by a ScalarImageToGreyLevelCooccurrenceMatrixGenerator + * or related class). + * + * The features calculated are as follows (where \f$ g(i, j) \f$ is the element in + * cell i, j of a a normalized GLCM): + * + * "Energy" \f$ = f_1 = \sum_{i,j}g(i, j)^2 \f$ + * + * "Entropy" \f$ = f_2 = -\sum_{i,j}g(i, j) \log_2 g(i, j)\f$, or 0 if \f$g(i, j) = 0\f$ + * + * "Correlation" \f$ = f_3 = \sum_{i,j}\frac{(i - \mu)(j - \mu)g(i, j)}{\sigma^2} \f$ + * + * "Difference Moment" \f$= f_4 = \sum_{i,j}\frac{1}{1 + (i - j)^2}g(i, j) \f$ + * + * "Inertia" \f$ = f_5 = \sum_{i,j}(i - j)^2g(i, j) \f$ (sometimes called "contrast.") + * + * "Cluster Shade" \f$ = f_6 = \sum_{i,j}((i - \mu) + (j - \mu))^3 g(i, j) \f$ + * + * "Cluster Prominence" \f$ = f_7 = \sum_{i,j}((i - \mu) + (j - \mu))^4 g(i, j) \f$ + * + * "Haralick's Correlation" \f$ = f_8 = \frac{\sum_{i,j}(i, j) g(i, j) -\mu_t^2}{\sigma_t^2} \f$ + * where \f$\mu_t\f$ and \f$\sigma_t\f$ are the mean and standard deviation of the row + * (or column, due to symmetry) sums. + * + * Above, \f$ \mu = \f$ (weighted pixel average) \f$ = \sum_{i,j}i \cdot g(i, j) = + * \sum_{i,j}j \cdot g(i, j) \f$ (due to matrix summetry), and + * + * \f$ \sigma = \f$ (weighted pixel variance) \f$ = \sum_{i,j}(i - \mu)^2 \cdot g(i, j) = + * \sum_{i,j}(j - \mu)^2 \cdot g(i, j) \f$ (due to matrix summetry) + * + * A good texture feature set to use is the Conners, Trivedi and Harlow set: + * features 1, 2, 4, 5, 6, and 7. There is some correlation between the various + * features, so using all of them at the same time is not necessarialy a good idea. + * + * NOTA BENE: The input histogram will be forcably normalized! + * This algorithm takes three passes through the input + * histogram if the histogram was already normalized, and four if not. + * + * Web references: + * + * http://www.cssip.uq.edu.au/meastex/www/algs/algs/algs.html + * http://www.ucalgary.ca/~mhallbey/texture/texture_tutorial.html + * + * Print references: + * + * Haralick, R.M., K. Shanmugam and I. Dinstein. 1973. Textural Features for + * Image Classification. IEEE Transactions on Systems, Man and Cybernetics. + * SMC-3(6):610-620. + * + * Haralick, R.M. 1979. Statistical and Structural Approaches to Texture. + * Proceedings of the IEEE, 67:786-804. + * + * R.W. Conners and C.A. Harlow. A Theoretical Comaprison of Texture Algorithms. + * IEEE Transactions on Pattern Analysis and Machine Intelligence, 2:204-222, 1980. + * + * R.W. Conners, M.M. Trivedi, and C.A. Harlow. Segmentation of a High-Resolution + * Urban Scene using Texture Operators. Computer Vision, Graphics and Image + * Processing, 25:273-310, 1984. + * + * \sa ScalarImageToGreyLevelCooccurrenceMatrixGenerator + * \sa MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator + * \sa ScalarImageTextureCalculator + * + * Author: Zachary Pincus + */ /** Texture feature types */ enum TextureFeatureName { Energy, Entropy, Correlation, @@ -101,65 +101,68 @@ enum TextureFeatureName { Energy, Entropy, Correlation, template< class THistogram > class GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator : public Object - { - public: - /** Standard typedefs */ - typedef GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; +{ +public: + /** Standard typedefs */ + typedef GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator, Object); + + /** standard New() method support */ + itkNewMacro(Self); - /** Run-time type information (and related methods). */ - itkTypeMacro(GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator, Object); + typedef THistogram HistogramType; + typedef typename HistogramType::Pointer HistogramPointer; + typedef typename HistogramType::ConstPointer HistogramConstPointer; + typedef typename HistogramType::MeasurementType MeasurementType; + typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; + typedef typename HistogramType::IndexType IndexType; + typedef typename HistogramType::FrequencyType FrequencyType; - /** standard New() method support */ - itkNewMacro(Self) ; - - typedef THistogram HistogramType; - typedef typename HistogramType::Pointer HistogramPointer; - typedef typename HistogramType::ConstPointer HistogramConstPointer; - typedef typename HistogramType::MeasurementType MeasurementType; - typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; - typedef typename HistogramType::IndexType IndexType; - typedef typename HistogramType::FrequencyType FrequencyType; - - /** Triggers the Computation of the histogram */ - void Compute( void ); - - /** Connects the GLCM histogram over which the features are going to be computed */ - itkSetObjectMacro( Histogram, HistogramType ); - itkGetObjectMacro( Histogram, HistogramType ); - - /** Methods to return the feature values. + /** Triggers the Computation of the histogram */ + void Compute( void ); + + /** Connects the GLCM histogram over which the features are going to be computed */ + itkSetObjectMacro( Histogram, HistogramType ); + itkGetObjectMacro( Histogram, HistogramType ); + + /** Methods to return the feature values. \warning These outputs are only valid after the Compute() method has been invoked \sa Compute */ - double GetFeature(TextureFeatureName feature); - - itkGetMacro(Energy, double); - itkGetMacro(Entropy, double); - itkGetMacro(Correlation, double); - itkGetMacro(InverseDifferenceMoment, double); - itkGetMacro(Inertia, double); - itkGetMacro(ClusterShade, double); - itkGetMacro(ClusterProminence, double); - itkGetMacro(HaralickCorrelation, double); + double GetFeature(TextureFeatureName feature); + + itkGetMacro(Energy, double); + itkGetMacro(Entropy, double); + itkGetMacro(Correlation, double); + itkGetMacro(InverseDifferenceMoment, double); + itkGetMacro(Inertia, double); + itkGetMacro(ClusterShade, double); + itkGetMacro(ClusterProminence, double); + itkGetMacro(HaralickCorrelation, double); - protected: - GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator() {}; - virtual ~GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator() {}; - void PrintSelf(std::ostream& os, Indent indent) const; +protected: + GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator() {}; + virtual ~GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator() {}; + void PrintSelf(std::ostream& os, Indent indent) const; - private: - HistogramPointer m_Histogram; - double m_Energy, m_Entropy, m_Correlation, m_InverseDifferenceMoment, - m_Inertia, m_ClusterShade, m_ClusterProminence, m_HaralickCorrelation; - void NormalizeHistogram(void); - void ComputeMeansAndVariances( double &pixelMean, double &marginalMean, - double &marginalDevSquared, double &pixelVariance ); - }; - - - } // end of namespace Statistics +private: + GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + HistogramPointer m_Histogram; + double m_Energy, m_Entropy, m_Correlation, m_InverseDifferenceMoment, + m_Inertia, m_ClusterShade, m_ClusterProminence, m_HaralickCorrelation; + void NormalizeHistogram(void); + void ComputeMeansAndVariances( double &pixelMean, double &marginalMean, + double &marginalDevSquared, double &pixelVariance ); +}; + + +} // end of namespace Statistics } // end of namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.txx index 75cc9df08a..62a4224202 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:37:20 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator_txx -#define _itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator_txx +#ifndef __itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator_txx +#define __itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator_txx #include "itkGreyLevelCooccurrenceMatrixTextureCoefficientsCalculator.h" @@ -23,115 +23,115 @@ #include "vnl/vnl_math.h" namespace itk { - namespace Statistics { +namespace Statistics { - template< class THistogram > - void - GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: - Compute( void ) - { - typedef typename HistogramType::Iterator HistogramIterator; +template< class THistogram > +void +GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: +Compute( void ) +{ + typedef typename HistogramType::Iterator HistogramIterator; - // First, normalize the histogram if it doesn't look normalized. - // This is one pass through the histogram. - FrequencyType totalFrequency = m_Histogram->GetTotalFrequency(); - if ( (totalFrequency - NumericTraits<MeasurementType>::One) > 0.0001 ) - { - // Doesn't look normalized: - this->NormalizeHistogram(); - } + // First, normalize the histogram if it doesn't look normalized. + // This is one pass through the histogram. + FrequencyType totalFrequency = m_Histogram->GetTotalFrequency(); + if ( (totalFrequency - NumericTraits<MeasurementType>::One) > 0.0001 ) + { + // Doesn't look normalized: + this->NormalizeHistogram(); + } - // Now get the various means and variances. This is takes two passes - // through the histogram. - double pixelMean, marginalMean, marginalDevSquared, pixelVariance; - this->ComputeMeansAndVariances(pixelMean, marginalMean, marginalDevSquared, - pixelVariance); + // Now get the various means and variances. This is takes two passes + // through the histogram. + double pixelMean, marginalMean, marginalDevSquared, pixelVariance; + this->ComputeMeansAndVariances(pixelMean, marginalMean, marginalDevSquared, + pixelVariance); - // Finally compute the texture features. Another one pass. - m_Energy = m_Entropy = m_Correlation = m_InverseDifferenceMoment = - m_Inertia = m_ClusterShade = m_ClusterProminence = m_HaralickCorrelation = 0; + // Finally compute the texture features. Another one pass. + m_Energy = m_Entropy = m_Correlation = m_InverseDifferenceMoment = + m_Inertia = m_ClusterShade = m_ClusterProminence = m_HaralickCorrelation = 0; - double pixelVarianceSquared = pixelVariance * pixelVariance; - double log2 = vcl_log(2.); - for (HistogramIterator hit = m_Histogram->Begin(); - hit != m_Histogram->End(); ++hit) - { - MeasurementType frequency = hit.GetFrequency(); - if (frequency == 0) - { - continue; // no use doing these calculations if we're just multiplying by zero. - } + double pixelVarianceSquared = pixelVariance * pixelVariance; + double log2 = vcl_log(2.); + for (HistogramIterator hit = m_Histogram->Begin(); + hit != m_Histogram->End(); ++hit) + { + MeasurementType frequency = hit.GetFrequency(); + if (frequency == 0) + { + continue; // no use doing these calculations if we're just multiplying by zero. + } - IndexType index = m_Histogram->GetIndex(hit.GetInstanceIdentifier()); - m_Energy += frequency * frequency; - m_Entropy -= (frequency > 0.0001) ? frequency * vcl_log(frequency) / log2 : 0; - m_Correlation += ( (index[0] - pixelMean) * (index[1] - pixelMean) * frequency) - / pixelVarianceSquared; - m_InverseDifferenceMoment += frequency / - (1.0 + (index[0] - index[1]) * (index[0] - index[1]) ); - m_Inertia += (index[0] - index[1]) * (index[0] - index[1]) * frequency; - m_ClusterShade += vcl_pow((index[0] - pixelMean) + (index[1] - pixelMean), 3) * - frequency; - m_ClusterProminence += vcl_pow((index[0] - pixelMean) + (index[1] - pixelMean), 4) * - frequency; - m_HaralickCorrelation += index[0] * index[1] * frequency; - } + IndexType index = m_Histogram->GetIndex(hit.GetInstanceIdentifier()); + m_Energy += frequency * frequency; + m_Entropy -= (frequency > 0.0001) ? frequency * vcl_log(frequency) / log2 : 0; + m_Correlation += ( (index[0] - pixelMean) * (index[1] - pixelMean) * frequency) + / pixelVarianceSquared; + m_InverseDifferenceMoment += frequency / + (1.0 + (index[0] - index[1]) * (index[0] - index[1]) ); + m_Inertia += (index[0] - index[1]) * (index[0] - index[1]) * frequency; + m_ClusterShade += vcl_pow((index[0] - pixelMean) + (index[1] - pixelMean), 3) * + frequency; + m_ClusterProminence += vcl_pow((index[0] - pixelMean) + (index[1] - pixelMean), 4) * + frequency; + m_HaralickCorrelation += index[0] * index[1] * frequency; + } - m_HaralickCorrelation = (m_HaralickCorrelation - marginalMean * marginalMean) / - marginalDevSquared; - } + m_HaralickCorrelation = (m_HaralickCorrelation - marginalMean * marginalMean) / + marginalDevSquared; +} - template< class THistogram > - void - GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: - NormalizeHistogram( void ) - { - typename HistogramType::Iterator hit; - typename HistogramType::FrequencyType totalFrequency = - m_Histogram->GetTotalFrequency(); +template< class THistogram > +void +GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: +NormalizeHistogram( void ) +{ + typename HistogramType::Iterator hit; + typename HistogramType::FrequencyType totalFrequency = + m_Histogram->GetTotalFrequency(); - for (hit = m_Histogram->Begin(); hit != m_Histogram->End(); ++hit) - { - hit.SetFrequency(hit.GetFrequency() / totalFrequency); - } - } + for (hit = m_Histogram->Begin(); hit != m_Histogram->End(); ++hit) + { + hit.SetFrequency(hit.GetFrequency() / totalFrequency); + } +} - template< class THistogram > - void - GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: - ComputeMeansAndVariances( double &pixelMean, double &marginalMean, - double &marginalDevSquared, double &pixelVariance ) - { - // This function takes two passes through the histogram and two passes through - // an array of the same length as a histogram axis. This could probably be - // cleverly compressed to one pass, but it's not clear that that's necessary. +template< class THistogram > +void +GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: +ComputeMeansAndVariances( double &pixelMean, double &marginalMean, + double &marginalDevSquared, double &pixelVariance ) +{ + // This function takes two passes through the histogram and two passes through + // an array of the same length as a histogram axis. This could probably be + // cleverly compressed to one pass, but it's not clear that that's necessary. - typedef typename HistogramType::Iterator HistogramIterator; + typedef typename HistogramType::Iterator HistogramIterator; - // Initialize everything - typename HistogramType::SizeValueType binsPerAxis = m_Histogram->GetSize(0); - double *marginalSums = new double[binsPerAxis]; - for (double *ms_It = marginalSums; - ms_It < marginalSums + binsPerAxis; ms_It++) - { - *ms_It = 0; - } - pixelMean = 0; + // Initialize everything + typename HistogramType::SizeValueType binsPerAxis = m_Histogram->GetSize(0); + double *marginalSums = new double[binsPerAxis]; + for (double *ms_It = marginalSums; + ms_It < marginalSums + binsPerAxis; ms_It++) + { + *ms_It = 0; + } + pixelMean = 0; - // Ok, now do the first pass through the histogram to get the marginal sums - // and compute the pixel mean - HistogramIterator hit; - for (hit = m_Histogram->Begin(); hit != m_Histogram->End(); ++hit) - { - MeasurementType frequency = hit.GetFrequency(); - IndexType index = m_Histogram->GetIndex(hit.GetInstanceIdentifier()); - pixelMean += index[0] * frequency; - marginalSums[index[0]] += frequency; - } + // Ok, now do the first pass through the histogram to get the marginal sums + // and compute the pixel mean + HistogramIterator hit; + for (hit = m_Histogram->Begin(); hit != m_Histogram->End(); ++hit) + { + MeasurementType frequency = hit.GetFrequency(); + IndexType index = m_Histogram->GetIndex(hit.GetInstanceIdentifier()); + pixelMean += index[0] * frequency; + marginalSums[index[0]] += frequency; + } - /* Now get the mean and deviaton of the marginal sums. + /* Now get the mean and deviaton of the marginal sums. Compute incremental mean and SD, a la Knuth, "The Art of Computer Programming, Volume 2: Seminumerical Algorithms", section 4.2.2. Compute mean and standard deviation using the recurrence relation: @@ -141,71 +141,71 @@ namespace itk { sigma = vcl_sqrt(S(n) / n) (or divide by n-1 for sample SD instead of population SD). */ - marginalMean = marginalSums[0]; - marginalDevSquared = 0; - for (unsigned int arrayIndex = 1 ; arrayIndex < binsPerAxis; arrayIndex++) - { - int k = arrayIndex + 1; - double M_k_minus_1 = marginalMean; - double S_k_minus_1 = marginalDevSquared; - double x_k = marginalSums[arrayIndex]; + marginalMean = marginalSums[0]; + marginalDevSquared = 0; + for (unsigned int arrayIndex = 1; arrayIndex < binsPerAxis; arrayIndex++) + { + int k = arrayIndex + 1; + double M_k_minus_1 = marginalMean; + double S_k_minus_1 = marginalDevSquared; + double x_k = marginalSums[arrayIndex]; - double M_k = M_k_minus_1 + (x_k - M_k_minus_1) / k; - double S_k = S_k_minus_1 + (x_k - M_k_minus_1) * (x_k - M_k); + double M_k = M_k_minus_1 + (x_k - M_k_minus_1) / k; + double S_k = S_k_minus_1 + (x_k - M_k_minus_1) * (x_k - M_k); - marginalMean = M_k; - marginalDevSquared = S_k; - } - marginalDevSquared = marginalDevSquared / binsPerAxis; + marginalMean = M_k; + marginalDevSquared = S_k; + } + marginalDevSquared = marginalDevSquared / binsPerAxis; - // OK, now compute the pixel variances. - pixelVariance = 0; - for (hit = m_Histogram->Begin(); hit != m_Histogram->End(); ++hit) - { - MeasurementType frequency = hit.GetFrequency(); - IndexType index = m_Histogram->GetIndex(hit.GetInstanceIdentifier()); - pixelVariance += (index[0] - pixelMean) * (index[0] - pixelMean) * frequency; - } - delete [] marginalSums; - } + // OK, now compute the pixel variances. + pixelVariance = 0; + for (hit = m_Histogram->Begin(); hit != m_Histogram->End(); ++hit) + { + MeasurementType frequency = hit.GetFrequency(); + IndexType index = m_Histogram->GetIndex(hit.GetInstanceIdentifier()); + pixelVariance += (index[0] - pixelMean) * (index[0] - pixelMean) * frequency; + } + delete [] marginalSums; +} - template< class THistogram > - double - GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: - GetFeature(TextureFeatureName feature) - { - switch(feature) - { - case Energy: - return this->GetEnergy(); - case Entropy: - return this->GetEntropy(); - case Correlation: - return this->GetCorrelation(); - case InverseDifferenceMoment: - return this->GetInverseDifferenceMoment(); - case Inertia: - return this->GetInertia(); - case ClusterShade: - return this->GetClusterShade(); - case ClusterProminence: - return this->GetClusterProminence(); - case HaralickCorrelation: - return this->GetHaralickCorrelation(); - default: - return 0; - } - } +template< class THistogram > +double +GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: +GetFeature(TextureFeatureName feature) +{ + switch(feature) + { + case Energy: + return this->GetEnergy(); + case Entropy: + return this->GetEntropy(); + case Correlation: + return this->GetCorrelation(); + case InverseDifferenceMoment: + return this->GetInverseDifferenceMoment(); + case Inertia: + return this->GetInertia(); + case ClusterShade: + return this->GetClusterShade(); + case ClusterProminence: + return this->GetClusterProminence(); + case HaralickCorrelation: + return this->GetHaralickCorrelation(); + default: + return 0; + } +} - template< class THistogram > - void - GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: - PrintSelf(std::ostream& os, Indent indent) const - { - Superclass::PrintSelf(os,indent); - } +template< class THistogram > +void +GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator< THistogram >:: +PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} - } // end of namespace Statistics +} // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkHistogram.h b/Utilities/ITK/Code/Numerics/Statistics/itkHistogram.h index 92a8872f7d..0b582223b8 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkHistogram.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkHistogram.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogram.h,v $ Language: C++ - Date: $Date: 2005-09-30 17:24:45 $ - Version: $Revision: 1.49 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.50 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,8 +26,8 @@ #include "itkDenseFrequencyContainer.h" #include "itkSparseFrequencyContainer.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** * Due to a bug in MSVC, an enum value cannot be accessed out of a template @@ -86,16 +86,17 @@ public: /** Standard typedefs */ - typedef Histogram Self ; - typedef Sample< FixedArray< TMeasurement, VMeasurementVectorSize > > Superclass ; - typedef SmartPointer<Self> Pointer ; - typedef SmartPointer<const Self> ConstPointer ; + typedef Histogram Self; + typedef Sample< FixedArray< TMeasurement, VMeasurementVectorSize > > + Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(Histogram, Sample) ; + itkTypeMacro(Histogram, Sample); /** standard New() method support */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** Dimension of a measurement vector */ itkStaticConstMacro(MeasurementVectorSize, unsigned int, @@ -103,54 +104,54 @@ public: /** type of an element of a measurement vector */ - typedef TMeasurement MeasurementType ; + typedef TMeasurement MeasurementType; /** Common sample class typedefs */ - typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; - typedef typename Superclass::InstanceIdentifier InstanceIdentifier ; - typedef MeasurementVectorType ValueType ; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + typedef MeasurementVectorType ValueType; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; /** frequency container typedef */ - typedef TFrequencyContainer FrequencyContainerType ; - typedef typename FrequencyContainerType::Pointer FrequencyContainerPointer ; + typedef TFrequencyContainer FrequencyContainerType; + typedef typename FrequencyContainerType::Pointer FrequencyContainerPointer; /** Frequency and TotalFrequency value type from superclass */ - typedef typename FrequencyContainerType::FrequencyType FrequencyType ; - typedef typename FrequencyContainerType::TotalFrequencyType TotalFrequencyType ; + typedef typename FrequencyContainerType::FrequencyType FrequencyType; + typedef typename FrequencyContainerType::TotalFrequencyType TotalFrequencyType; /** Index typedef support. An index is used to access pixel values. */ typedef itk::Index< VMeasurementVectorSize > IndexType; - typedef typename IndexType::IndexValueType IndexValueType; + typedef typename IndexType::IndexValueType IndexValueType; /** size array type */ - typedef itk::Size< VMeasurementVectorSize > SizeType ; - typedef typename SizeType::SizeValueType SizeValueType ; + typedef itk::Size< VMeasurementVectorSize > SizeType; + typedef typename SizeType::SizeValueType SizeValueType; /** bin min max value storage types */ - typedef std::vector< MeasurementType > BinMinVectorType ; - typedef std::vector< MeasurementType > BinMaxVectorType ; - typedef std::vector< BinMinVectorType > BinMinContainerType ; - typedef std::vector< BinMaxVectorType > BinMaxContainerType ; + typedef std::vector< MeasurementType > BinMinVectorType; + typedef std::vector< MeasurementType > BinMaxVectorType; + typedef std::vector< BinMinVectorType > BinMinContainerType; + typedef std::vector< BinMaxVectorType > BinMaxContainerType; /** Initialize the histogram, generating the offset table and * preparing the frequency container. Subclasses should call this * method in their Initialize() method. */ - void Initialize(const SizeType &size) ; + void Initialize(const SizeType &size); /** Initialize the histogram using equal size bins. To assign bin's * min and max values along each dimension use SetBinMin() and * SetBinMax() functions. */ void Initialize(const SizeType &size, MeasurementVectorType& lowerBound, - MeasurementVectorType& upperBound) ; + MeasurementVectorType& upperBound); /** Initialize the values of the histogram bins to zero */ - void SetToZero() ; + void SetToZero(); /** Get the index of a measurement value from the histogram. * \deprecated Use GetIndex(const MeasurementVectorType & - * measurement, IndexType & index ) const instead.*/ + * measurement, IndexType & index ) const instead. */ const IndexType & GetIndex(const MeasurementVectorType& measurement) const; /** Get the index of histogram corresponding to the specified @@ -179,105 +180,97 @@ public: /** Get the instance identifier of the bin that is indexed by the * index. The corresponding instance identifier is the offset of the index * This method uses ImageBase::ComputeIndex() method */ - InstanceIdentifier GetInstanceIdentifier(const IndexType &index) const ; + InstanceIdentifier GetInstanceIdentifier(const IndexType &index) const; /** Returns the number of instances (bins or cells) in this container */ - unsigned int Size() const ; + unsigned int Size() const; /** Get the size (N-dimensional) of the histogram */ SizeType GetSize() const - { return m_Size ; } + { return m_Size; } /** Get the size of histogram along a specified dimension */ SizeValueType GetSize(const unsigned int dimension) const - { - return m_Size[dimension] ; - } + { + return m_Size[dimension]; + } /** Get the minimum value of nth bin of dimension d */ const MeasurementType& GetBinMin(const unsigned int dimension, const unsigned long nbin) const - { return m_Min[dimension][nbin] ; } + { return m_Min[dimension][nbin]; } /** Get the maximum value of nth bin of dimension d */ const MeasurementType& GetBinMax(const unsigned int dimension, const unsigned long nbin) const - { return m_Max[dimension][nbin] ; } + { return m_Max[dimension][nbin]; } /** Set the minimum value of nth bin of dimension d */ void SetBinMin(const unsigned int dimension, const unsigned long nbin, const MeasurementType min) - { m_Min[dimension][nbin] = min ; } + { m_Min[dimension][nbin] = min; } /** Set the maximum value of nth bin of dimension d */ void SetBinMax(const unsigned int dimension, unsigned long nbin, const MeasurementType max) - { m_Max[dimension][nbin] = max ; } + { m_Max[dimension][nbin] = max; } /** Get the minimum of the bin along dimension d corresponding to a * particular measurement. */ const MeasurementType& GetBinMinFromValue(const unsigned int dimension, - const float value ) const ; + const float value ) const; /** Get the maximum of the bin along dimension d corresponding to a * particular measurement. */ const MeasurementType& GetBinMaxFromValue(const unsigned int dimension, - const float value ) const ; + const float value ) const; /** Get the vector of bin minimums along a dimension */ const BinMinVectorType& GetDimensionMins(const unsigned int dimension) const - { return m_Min[dimension] ; } + { return m_Min[dimension]; } /** Get the vector of maximums along a dimension */ const BinMaxVectorType& GetDimensionMaxs(const unsigned int dimension) const - { return m_Max[dimension] ; } + { return m_Max[dimension]; } /** Get the minimums of the bins */ const BinMinContainerType& GetMins() const - { return m_Min ; } + { return m_Min; } /** Method the maximums of the bins */ const BinMaxContainerType& GetMaxs() const - { return m_Max ; } - -// /** Get the minimums of the bin corresponding to a particular measurement */ -// MeasurementVectorType& GetHistogramMinFromValue(const MeasurementVectorType -// &measurement) ; -// -// /** Get the maximums of the bin corresponding to a particular measurement */ -// MeasurementVectorType& GetHistogramMaxFromValue(const MeasurementVectorType -// &measurement) ; + { return m_Max; } /** Get the minimums of the bin corresponding to a particular index */ - MeasurementVectorType& GetHistogramMinFromIndex(const IndexType &index) ; + MeasurementVectorType& GetHistogramMinFromIndex(const IndexType &index); /** Get the maximums of the bin corresponding to a particular index */ - MeasurementVectorType& GetHistogramMaxFromIndex(const IndexType &index) ; + MeasurementVectorType& GetHistogramMaxFromIndex(const IndexType &index); /** Get the frequency of an instance indentifier */ FrequencyType GetFrequency(const InstanceIdentifier &id) const - { return m_FrequencyContainer->GetFrequency(id) ; } + { return m_FrequencyContainer->GetFrequency(id); } /** Get the frequency of an index */ - FrequencyType GetFrequency(const IndexType &index) const ; + FrequencyType GetFrequency(const IndexType &index) const; /** Set all the bins in the histogram to a specified frequency */ - void SetFrequency(const FrequencyType value) ; + void SetFrequency(const FrequencyType value); /** Set the frequency of an instance identifier. Returns false if the bin is * out of bounds. */ bool SetFrequency(const InstanceIdentifier &id, const FrequencyType value) - { return m_FrequencyContainer->SetFrequency(id, value) ; } + { return m_FrequencyContainer->SetFrequency(id, value); } /** Set the frequency of an index. Returns false if the bin is * out of bounds. */ bool SetFrequency(const IndexType &index, - const FrequencyType value) ; + const FrequencyType value); /** Set the frequency of a measurement. Returns false if the bin is * out of bounds. */ bool SetFrequency(const MeasurementVectorType &measurement, - const FrequencyType value) ; + const FrequencyType value); /** Increase the frequency of an instance identifier. @@ -285,19 +278,19 @@ public: * the bin is out of bounds. */ bool IncreaseFrequency(const InstanceIdentifier &id, const FrequencyType value) - { return m_FrequencyContainer->IncreaseFrequency(id, value) ; } + { return m_FrequencyContainer->IncreaseFrequency(id, value); } /** Increase the frequency of an index. Frequency is * increased by the specified value. Returns false if the bin is out * of bounds. */ bool IncreaseFrequency(const IndexType &index, - const FrequencyType value) ; + const FrequencyType value); /** Increase the frequency of a measurement. Frequency is * increased by the specified value. Returns false if the * measurement is outside the bounds of the histogram. */ bool IncreaseFrequency(const MeasurementVectorType &measurement, - const FrequencyType value) ; + const FrequencyType value); /** Get the measurement of an instance identifier. This is the * centroid of the bin. @@ -310,14 +303,14 @@ public: /** Get the measurement a bin along a specified dimension. This is * the midpoint of the bin along that dimension. */ MeasurementType GetMeasurement(const unsigned long n, - const unsigned int dimension) const ; + const unsigned int dimension) const; - /** Get the total frequency in the histogram*/ - TotalFrequencyType GetTotalFrequency() const ; + /** Get the total frequency in the histogram */ + TotalFrequencyType GetTotalFrequency() const; /** Get the frequency of a dimension's nth element. */ FrequencyType GetFrequency(const unsigned long n, - const unsigned int dimension) const ; + const unsigned int dimension) const; /** Get the pth percentile value for a dimension. * @@ -325,7 +318,7 @@ public: * min = min value of the dimension of the bin, * max = max value of the dimension of the bin, * interval = max - min , - * pp = cumlated proportion until n-1 bin ; + * pp = cumlated proportion until n-1 bin; * and pb = frequency of the bin / total frequency of the dimension. * * If p is less than 0.5, @@ -336,204 +329,201 @@ public: * max - ((pp - p) / pb) * interval */ double Quantile(const unsigned int dimension, const double &p) const; - protected: +protected: void PrintSelf(std::ostream& os, Indent indent) const; public: - /** iterator support */ + /** iterator support */ class Iterator - { - public: + { + public: Iterator(){}; Iterator(Self * histogram) - { - m_Id = 0 ; + { + m_Id = 0; m_Histogram = histogram; - } + } Iterator(InstanceIdentifier id, Self * histogram) - : m_Id(id), m_Histogram(histogram) - {} + : m_Id(id), m_Histogram(histogram) {} FrequencyType GetFrequency() const - { - return m_Histogram->GetFrequency(m_Id) ; - } + { + return m_Histogram->GetFrequency(m_Id); + } bool SetFrequency(const FrequencyType value) - { + { return m_Histogram->SetFrequency(m_Id, value); - } + } InstanceIdentifier GetInstanceIdentifier() const - { return m_Id ; } + { return m_Id; } const MeasurementVectorType & GetMeasurementVector() const - { - return m_Histogram->GetMeasurementVector(m_Id) ; - } + { + return m_Histogram->GetMeasurementVector(m_Id); + } Iterator& operator++() - { + { ++m_Id; return *this; - } + } bool operator!=(const Iterator& it) - { return (m_Id != it.m_Id); } + { return (m_Id != it.m_Id); } bool operator==(const Iterator& it) - { return (m_Id == it.m_Id); } + { return (m_Id == it.m_Id); } Iterator& operator=(const Iterator& it) - { + { m_Id = it.m_Id; - m_Histogram = it.m_Histogram ; - return *this ; - } + m_Histogram = it.m_Histogram; + return *this; + } Iterator(const Iterator& it) - { + { m_Id = it.m_Id; - m_Histogram = it.m_Histogram ; - } + m_Histogram = it.m_Histogram; + } private: // Iterator pointing DenseFrequencyContainer InstanceIdentifier m_Id; // Pointer of DenseFrequencyContainer - Self* m_Histogram ; - } ; // end of iterator class + Self* m_Histogram; + }; // end of iterator class // Const Iterator class ConstIterator - { - public: + { + public: ConstIterator(){}; - + ConstIterator(const Self * histogram) - { - m_Id = 0 ; + { + m_Id = 0; m_Histogram = histogram; - } + } ConstIterator(InstanceIdentifier id, const Self * histogram) - : m_Id(id), m_Histogram(histogram) - {} + : m_Id(id), m_Histogram(histogram) {} FrequencyType GetFrequency() const - { - return m_Histogram->GetFrequency(m_Id) ; - } + { + return m_Histogram->GetFrequency(m_Id); + } InstanceIdentifier GetInstanceIdentifier() const - { return m_Id ; } + { return m_Id; } const MeasurementVectorType & GetMeasurementVector() const - { - return m_Histogram->GetMeasurementVector(m_Id) ; - } + { + return m_Histogram->GetMeasurementVector(m_Id); + } ConstIterator& operator++() - { + { ++m_Id; return *this; - } + } bool operator!=(const ConstIterator& it) - { return (m_Id != it.m_Id); } + { return (m_Id != it.m_Id); } bool operator==(const ConstIterator& it) - { return (m_Id == it.m_Id); } + { return (m_Id == it.m_Id); } ConstIterator& operator=(const ConstIterator& it) - { + { m_Id = it.m_Id; - m_Histogram = it.m_Histogram ; - return *this ; - } + m_Histogram = it.m_Histogram; + return *this; + } ConstIterator(const ConstIterator & it) - { + { m_Id = it.m_Id; - m_Histogram = it.m_Histogram ; - } + m_Histogram = it.m_Histogram; + } - private: - // ConstIterator pointing DenseFrequencyContainer - InstanceIdentifier m_Id; + private: + // ConstIterator pointing DenseFrequencyContainer + InstanceIdentifier m_Id; - // Pointer of DenseFrequencyContainer - const Self* m_Histogram ; - } ; // end of iterator class - + // Pointer of DenseFrequencyContainer + const Self* m_Histogram; + }; // end of iterator class + Iterator Begin() - { - Iterator iter(0, this) ; - return iter ; - } + { + Iterator iter(0, this); + return iter; + } - Iterator End() - { - return Iterator(m_OffsetTable[VMeasurementVectorSize], this) ; - } + Iterator End() + { + return Iterator(m_OffsetTable[VMeasurementVectorSize], this); + } ConstIterator Begin() const - { - ConstIterator iter(0, this) ; - return iter ; - } + { + ConstIterator iter(0, this); + return iter; + } ConstIterator End() const - { - return ConstIterator(m_OffsetTable[VMeasurementVectorSize], this) ; - } - - virtual void SetMeasurementVectorSize( const MeasurementVectorSizeType s ) - { - if( s!= VMeasurementVectorSize ) - { - itkExceptionMacro( << "This Histogram class is meant to be used only for " - << "fixed length vectors of length " << VMeasurementVectorSize << - ". Cannot set this to " << s); - } - } - MeasurementVectorSizeType GetMeasurementVectorSize() const - { - return VMeasurementVectorSize; - } - + { + return ConstIterator(m_OffsetTable[VMeasurementVectorSize], this); + } + + virtual void SetMeasurementVectorSize( const MeasurementVectorSizeType s ) + { + if( s!= VMeasurementVectorSize ) + { + itkExceptionMacro( << "This Histogram class is meant to be used only for " + << "fixed length vectors of length " << VMeasurementVectorSize << + ". Cannot set this to " << s); + } + } + MeasurementVectorSizeType GetMeasurementVectorSize() const + { + return VMeasurementVectorSize; + } protected: - Histogram() ; + Histogram(); virtual ~Histogram() {} // The number of bins for each dimension - SizeType m_Size ; + SizeType m_Size; private: Histogram(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented - InstanceIdentifier m_OffsetTable[VMeasurementVectorSize + 1] ; - FrequencyContainerPointer m_FrequencyContainer ; - unsigned int m_NumberOfInstances ; + InstanceIdentifier m_OffsetTable[VMeasurementVectorSize + 1]; + FrequencyContainerPointer m_FrequencyContainer; + unsigned int m_NumberOfInstances; // lower bound of each bin - std::vector< std::vector<MeasurementType> > m_Min ; + std::vector< std::vector<MeasurementType> > m_Min; // upper bound of each bin - std::vector< std::vector<MeasurementType> > m_Max ; + std::vector< std::vector<MeasurementType> > m_Max; - mutable MeasurementVectorType m_TempMeasurementVector ; - mutable IndexType m_TempIndex ; + mutable MeasurementVectorType m_TempMeasurementVector; + mutable IndexType m_TempIndex; bool m_ClipBinsAtEnds; -} ; +}; } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkHistogram.txx b/Utilities/ITK/Code/Numerics/Statistics/itkHistogram.txx index 7173c1cfe8..2ccb6c5f97 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkHistogram.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkHistogram.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogram.txx,v $ Language: C++ - Date: $Date: 2009-01-11 19:20:01 $ - Version: $Revision: 1.51 $ + Date: $Date: 2009-04-26 00:37:48 $ + Version: $Revision: 1.53 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,14 +14,14 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkHistogram_txx -#define _itkHistogram_txx +#ifndef __itkHistogram_txx +#define __itkHistogram_txx #include "itkHistogram.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TMeasurement, unsigned int VMeasurementVectorSize, class TFrequencyContainer> @@ -29,10 +29,10 @@ Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> ::Histogram() { m_ClipBinsAtEnds = true; - m_FrequencyContainer = FrequencyContainerType::New() ; - for (unsigned int i = 0 ; i < (MeasurementVectorSize + 1) ; ++i ) + m_FrequencyContainer = FrequencyContainerType::New(); + for (unsigned int i = 0; i < (MeasurementVectorSize + 1); ++i ) { - m_OffsetTable[i] = 0 ; + m_OffsetTable[i] = 0; } } @@ -42,12 +42,12 @@ unsigned int Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> ::Size() const { - unsigned int size = 1 ; - for (unsigned int i = 0 ; i < MeasurementVectorSize ; i++) + unsigned int size = 1; + for (unsigned int i = 0; i < MeasurementVectorSize; i++) { - size *= m_Size[i] ; + size *= m_Size[i]; } - return size ; + return size; } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -56,20 +56,20 @@ void Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> ::Initialize(const SizeType &size) { - m_Size = size ; + m_Size = size; // creates offset table which will be used for generation of // instance identifiers. - InstanceIdentifier num = 1 ; + InstanceIdentifier num = 1; - m_OffsetTable[0] = num ; - for (unsigned int i = 0 ; i < MeasurementVectorSize ; i++) + m_OffsetTable[0] = num; + for (unsigned int i = 0; i < MeasurementVectorSize; i++) { - num *= m_Size[i] ; - m_OffsetTable[i + 1] = num ; + num *= m_Size[i]; + m_OffsetTable[i + 1] = num; } - m_NumberOfInstances = num ; + m_NumberOfInstances = num; // adjust the sizes of min max value containers unsigned int dim; @@ -86,7 +86,7 @@ Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> } // initialize the frequency container - m_FrequencyContainer->Initialize(m_OffsetTable[VMeasurementVectorSize]) ; + m_FrequencyContainer->Initialize(m_OffsetTable[VMeasurementVectorSize]); this->SetToZero(); } @@ -106,26 +106,26 @@ Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> ::Initialize(const SizeType &size, MeasurementVectorType& lowerBound, MeasurementVectorType& upperBound) { - this->Initialize(size) ; - for ( unsigned int i = 0 ; i < MeasurementVectorSize ; i++) + this->Initialize(size); + for ( unsigned int i = 0; i < MeasurementVectorSize; i++) { const double interval = static_cast<double>(upperBound[i] - lowerBound[i]) - / static_cast< MeasurementType >(size[i]) ; + / static_cast< MeasurementType >(size[i]); // Set the min vector and max vector - for (unsigned int j = 0; j < (size[i] - 1) ; j++) + for (unsigned int j = 0; j < (size[i] - 1); j++) { this->SetBinMin(i, j, (MeasurementType)(lowerBound[i] + - (static_cast<double>(j) * interval))) ; + (static_cast<double>(j) * interval))); this->SetBinMax(i, j, (MeasurementType)(lowerBound[i] + ((static_cast<double>(j + 1)) * interval))); } // Set min vector and max vector for the final bin clipped at upperbound this->SetBinMin(i, size[i] - 1, (MeasurementType)(lowerBound[i] + - ((static_cast<double>( size[i] - 1)) * interval))) ; + ((static_cast<double>( size[i] - 1)) * interval))); this->SetBinMax(i, size[i] - 1, - (MeasurementType)(upperBound[i])) ; + (MeasurementType)(upperBound[i])); } } @@ -141,8 +141,6 @@ Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> return m_TempIndex; } - - /** */ template< class TMeasurement, unsigned int VMeasurementVectorSize, class TFrequencyContainer> @@ -151,17 +149,17 @@ bool Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> { // now using something similar to binary search to find // index. - for (unsigned int dim = 0 ; dim < MeasurementVectorSize ; dim++) + for (unsigned int dim = 0; dim < MeasurementVectorSize; dim++) { - const MeasurementType tempMeasurement = measurement[dim] ; - int begin = 0 ; + const MeasurementType tempMeasurement = measurement[dim]; + int begin = 0; if (tempMeasurement < m_Min[dim][begin]) { // one of measurement is below the minimum // its ok if we extend the bins to infinity.. not ok if we don't if(!m_ClipBinsAtEnds) { - index[dim] = (long) 0 ; + index[dim] = (long) 0; continue; } else @@ -171,7 +169,7 @@ bool Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> } } - int end = m_Min[dim].size() - 1 ; + int end = m_Min[dim].size() - 1; if (tempMeasurement >= m_Max[dim][end]) { // one of measurement is below the minimum @@ -189,49 +187,47 @@ bool Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> } } - int mid = (end + 1) / 2 ; + int mid = (end + 1) / 2; MeasurementType median = m_Min[dim][mid]; while(true) { if (tempMeasurement < median ) { - end = mid - 1 ; + end = mid - 1; } else if (tempMeasurement > median) { if( tempMeasurement < m_Max[dim][mid] && tempMeasurement >= m_Min[dim][mid] ) { - index[dim] = mid ; - break ; + index[dim] = mid; + break; } - begin = mid + 1 ; + begin = mid + 1; } else { // measurement[dim] = m_Min[dim][med] - index[dim] = mid ; - break ; + index[dim] = mid; + break; } - mid = begin + (end - begin) / 2 ; - median = m_Min[dim][mid] ; + mid = begin + (end - begin) / 2; + median = m_Min[dim][mid]; } // end of while } // end of for() return true; } - - template< class TMeasurement, unsigned int VMeasurementVectorSize, class TFrequencyContainer> inline const typename Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer>::IndexType& Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> ::GetIndex(const InstanceIdentifier &id) const { - InstanceIdentifier id2 = id ; + InstanceIdentifier id2 = id; - for (int i = MeasurementVectorSize - 1 ; i > 0 ; i--) + for (int i = MeasurementVectorSize - 1; i > 0; i--) { m_TempIndex[i] = static_cast<IndexValueType>(id2 / m_OffsetTable[i]); id2 -= (m_TempIndex[i] * m_OffsetTable[i]); @@ -248,14 +244,14 @@ inline bool Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> ::IsIndexOutOfBounds(const IndexType &index) const { - for (unsigned int dim = 0 ; dim < MeasurementVectorSize ; dim++) + for (unsigned int dim = 0; dim < MeasurementVectorSize; dim++) { if (index[dim] < 0 || index[dim] >= static_cast<IndexValueType>(m_Size[dim])) { - return true ; + return true; } } - return false ; + return false; } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -265,15 +261,15 @@ inline typename Histogram<TMeasurement, VMeasurementVectorSize, Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> ::GetInstanceIdentifier(const IndexType &index) const { - InstanceIdentifier identifier = 0 ; - for (int i= MeasurementVectorSize - 1 ; i > 0 ; i-- ) + InstanceIdentifier identifier = 0; + for (int i= MeasurementVectorSize - 1; i > 0; i-- ) { identifier += index[i] * m_OffsetTable[i]; } - identifier += index[0] ; + identifier += index[0]; - return identifier ; + return identifier; } @@ -298,16 +294,18 @@ Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> return m_Min[dimension][this->m_Size[dimension]-1]; } + unsigned int binMinFromValue = 0; + for ( unsigned int i=0; i < this->m_Size[dimension]; i++ ) { if ( (value >= this->m_Min[dimension][i]) && (value < this->m_Max[dimension][i]) ) { - return this->m_Min[dimension][i]; + binMinFromValue = i; } } - return this->m_Min[dimension][0]; + return this->m_Min[dimension][binMinFromValue]; } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -331,47 +329,20 @@ Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > return m_Max[dimension][this->m_Size[dimension]-1]; } - for ( unsigned int i = 0 ; i < this->m_Size[dimension]; i++ ) + unsigned int binMaxFromValue = 0; + + for ( unsigned int i = 0; i < this->m_Size[dimension]; i++ ) { if ( (value >= this->m_Min[dimension][i]) && (value < this->m_Max[dimension][i]) ) { - return this->m_Max[dimension][i]; + binMaxFromValue = i; } } - return this->m_Max[dimension][0]; + return this->m_Max[dimension][binMaxFromValue]; } -/*template< class TMeasurement, unsigned int VMeasurementVectorSize, - class TFrequencyContainer > -inline typename Histogram< TMeasurement, VMeasurementVectorSize, - TFrequencyContainer >::MeasurementVectorType& -Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > -::GetHistogramMinFromValue(const MeasurementVectorType &measurement) -{ - for ( int i = 0; i < MeasurementVectorSize; i++ ) - { - m_TempMeasurementVector[i] = this->GetDimensionMinByValue(i,measurement[i]); - } - return m_TempMeasurementVector ; -} - -template< class TMeasurement, unsigned int VMeasurementVectorSize, - class TFrequencyContainer > -inline typename Histogram< TMeasurement, VMeasurementVectorSize, - TFrequencyContainer >::MeasurementVectorType& -Histogram<TMeasurement, VMeasurementVectorSize, TFrequencyContainer> -::GetHistogramMaxFromValue(const MeasurementVectorType &measurement) -{ - for ( int i=0; i < MeasurementVectorSize; i++ ) - { - m_TempMeasurementVector[i] = this->GetDimensionMaxByValue(i,measurement[i]); - } - return m_TempMeasurementVector ; - -} -*/ template< class TMeasurement, unsigned int VMeasurementVectorSize, class TFrequencyContainer > inline typename Histogram< TMeasurement, VMeasurementVectorSize, @@ -381,9 +352,9 @@ Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > { for ( int i=0; i < MeasurementVectorSize; i++ ) { - m_TempMeasurementVector[i] = this->GetBinMin(i, index[i]) ; + m_TempMeasurementVector[i] = this->GetBinMin(i, index[i]); } - return m_TempMeasurementVector ; + return m_TempMeasurementVector; } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -395,9 +366,9 @@ Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > { for ( unsigned int i=0; i < MeasurementVectorSize; i++ ) { - m_TempMeasurementVector[i] = this->GetBinMax(i, index[i]) ; + m_TempMeasurementVector[i] = this->GetBinMax(i, index[i]); } - return m_TempMeasurementVector ; + return m_TempMeasurementVector; } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -412,7 +383,7 @@ Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > MeasurementType value = (m_Min[i][index[i]] + m_Max[i][index[i]]); m_TempMeasurementVector[i] = static_cast< MeasurementType >( value / 2.0 ); } - return m_TempMeasurementVector ; + return m_TempMeasurementVector; } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -422,7 +393,7 @@ inline const typename Histogram< TMeasurement, VMeasurementVectorSize, Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::GetMeasurementVector(const InstanceIdentifier &identifier) const { - return this->GetMeasurementVector( this->GetIndex(identifier) ) ; + return this->GetMeasurementVector( this->GetIndex(identifier) ); } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -431,13 +402,13 @@ inline void Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::SetFrequency(const FrequencyType value) { - typename Self::Iterator iter = this->Begin() ; - typename Self::Iterator end = this->End() ; + typename Self::Iterator iter = this->Begin(); + typename Self::Iterator end = this->End(); while ( iter != end ) { - iter.SetFrequency(value) ; - ++iter ; + iter.SetFrequency(value); + ++iter; } } @@ -447,7 +418,7 @@ inline bool Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::SetFrequency(const IndexType &index, const FrequencyType value) { - return this->SetFrequency( this->GetInstanceIdentifier(index), value) ; + return this->SetFrequency( this->GetInstanceIdentifier(index), value); } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -456,7 +427,7 @@ inline bool Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::SetFrequency(const MeasurementVectorType &measurement, const FrequencyType value) { - return this->SetFrequency( this->GetInstanceIdentifier(GetIndex(measurement)), value) ; + return this->SetFrequency( this->GetInstanceIdentifier(GetIndex(measurement)), value); } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -466,7 +437,7 @@ Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::IncreaseFrequency(const IndexType &index, const FrequencyType value) { const bool result = - this->IncreaseFrequency( this->GetInstanceIdentifier(index), value) ; + this->IncreaseFrequency( this->GetInstanceIdentifier(index), value); return result; } @@ -481,8 +452,6 @@ Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > return this->IncreaseFrequency( this->GetInstanceIdentifier( index ), value ); } - - template< class TMeasurement, unsigned int VMeasurementVectorSize, class TFrequencyContainer > inline typename Histogram< TMeasurement, VMeasurementVectorSize, @@ -490,7 +459,7 @@ inline typename Histogram< TMeasurement, VMeasurementVectorSize, Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::GetFrequency(const IndexType &index) const { - return ( this->GetFrequency( this->GetInstanceIdentifier(index)) ) ; + return ( this->GetFrequency( this->GetInstanceIdentifier(index)) ); } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -501,7 +470,7 @@ Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::GetMeasurement(const unsigned long n, const unsigned int dimension) const { return static_cast< MeasurementType >((m_Min[dimension][n] + - m_Max[dimension][n]) / 2) ; + m_Max[dimension][n]) / 2); } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -511,26 +480,26 @@ inline typename Histogram< TMeasurement, VMeasurementVectorSize, Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::GetFrequency(const unsigned long n, const unsigned int dimension) const { - InstanceIdentifier nextOffset = m_OffsetTable[dimension + 1] ; - InstanceIdentifier current = m_OffsetTable[dimension] * n ; - InstanceIdentifier includeLength = m_OffsetTable[dimension] ; - InstanceIdentifier include ; - InstanceIdentifier includeEnd ; - InstanceIdentifier last = m_OffsetTable[VMeasurementVectorSize] ; - - FrequencyType frequency = 0 ; + InstanceIdentifier nextOffset = m_OffsetTable[dimension + 1]; + InstanceIdentifier current = m_OffsetTable[dimension] * n; + InstanceIdentifier includeLength = m_OffsetTable[dimension]; + InstanceIdentifier include; + InstanceIdentifier includeEnd; + InstanceIdentifier last = m_OffsetTable[VMeasurementVectorSize]; + + FrequencyType frequency = 0; while (current < last) { - include = current ; - includeEnd = include + includeLength ; + include = current; + includeEnd = include + includeLength; while(include < includeEnd) { - frequency += GetFrequency(include) ; - include++ ; + frequency += GetFrequency(include); + include++; } - current += nextOffset ; + current += nextOffset; } - return frequency ; + return frequency; } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -540,7 +509,7 @@ inline typename Histogram< TMeasurement, VMeasurementVectorSize, Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::GetTotalFrequency() const { - return m_FrequencyContainer->GetTotalFrequency() ; + return m_FrequencyContainer->GetTotalFrequency(); } template< class TMeasurement, unsigned int VMeasurementVectorSize, @@ -549,58 +518,58 @@ double Histogram< TMeasurement, VMeasurementVectorSize, TFrequencyContainer > ::Quantile(const unsigned int dimension, const double &p) const { - InstanceIdentifier n ; - const unsigned int size = this->GetSize(dimension) ; - double p_n_prev ; - double p_n ; - double f_n ; - double cumulated = 0 ; - double totalFrequency = double( this->GetTotalFrequency() ) ; - double binProportion ; - double min, max, interval ; + InstanceIdentifier n; + const unsigned int size = this->GetSize(dimension); + double p_n_prev; + double p_n; + double f_n; + double cumulated = 0; + double totalFrequency = double( this->GetTotalFrequency() ); + double binProportion; + double min, max, interval; if ( p < 0.5 ) { - n = 0 ; - p_n = NumericTraits< double >::Zero ; + n = 0; + p_n = NumericTraits< double >::Zero; do { - f_n = this->GetFrequency(n, dimension) ; - cumulated += f_n ; - p_n_prev = p_n ; - p_n = cumulated / totalFrequency ; - n++ ; + f_n = this->GetFrequency(n, dimension); + cumulated += f_n; + p_n_prev = p_n; + p_n = cumulated / totalFrequency; + n++; } - while( n < size && p_n < p) ; + while( n < size && p_n < p); - binProportion = f_n / totalFrequency ; + binProportion = f_n / totalFrequency; - min = double( this->GetBinMin(dimension, n - 1) ) ; - max = double( this->GetBinMax(dimension, n - 1) ) ; - interval = max - min ; - return min + ((p - p_n_prev) / binProportion) * interval ; + min = double( this->GetBinMin(dimension, n - 1) ); + max = double( this->GetBinMax(dimension, n - 1) ); + interval = max - min; + return min + ((p - p_n_prev) / binProportion) * interval; } else { - n = size - 1 ; + n = size - 1; InstanceIdentifier m = NumericTraits< InstanceIdentifier >::Zero; - p_n = NumericTraits< double >::One ; + p_n = NumericTraits< double >::One; do { - f_n = this->GetFrequency(n, dimension) ; - cumulated += f_n ; - p_n_prev = p_n ; - p_n = NumericTraits< double >::One - cumulated / totalFrequency ; + f_n = this->GetFrequency(n, dimension); + cumulated += f_n; + p_n_prev = p_n; + p_n = NumericTraits< double >::One - cumulated / totalFrequency; n--; m++; } while( m < size && p_n > p); - binProportion = f_n / totalFrequency ; - min = double( this->GetBinMin(dimension, n + 1) ) ; - max = double( this->GetBinMax(dimension, n + 1) ) ; - interval = max - min ; - return max - ((p_n_prev - p) / binProportion) * interval ; + binProportion = f_n / totalFrequency; + min = double( this->GetBinMin(dimension, n + 1) ); + max = double( this->GetBinMax(dimension, n + 1) ); + interval = max - min; + return max - ((p_n_prev - p) / binProportion) * interval; } } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToEntropyImageFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToEntropyImageFilter.h index 4f6ce03713..94d820bce7 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToEntropyImageFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToEntropyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramToEntropyImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-17 09:13:59 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-01 14:36:37 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkHistogramEntropyFunction_h -#define __itkHistogramEntropyFunction_h +#ifndef __itkHistogramToEntropyImageFilter_h +#define __itkHistogramToEntropyImageFilter_h #include "itkHistogramToImageFilter.h" @@ -66,8 +66,8 @@ public: ~HistogramEntropyFunction() {}; - inline OutputPixelType operator()( const TInput & A ) - { + inline OutputPixelType operator()( const TInput & A ) const + { if( A ) { const double p = static_cast<OutputPixelType>(A) / @@ -80,7 +80,7 @@ public: static_cast<OutputPixelType>(m_TotalFrequency); return static_cast<OutputPixelType>( (-1) * p * vcl_log(p) / vcl_log(2.0)); } - } + } void SetTotalFrequency( const unsigned long n ) { @@ -134,6 +134,3 @@ private: } // end namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToImageFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToImageFilter.h index 6038fe7fcd..498d897f50 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToImageFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramToImageFilter.h,v $ Language: C++ - Date: $Date: 2007-01-25 09:18:58 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-06 11:51:06 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToIntensityImageFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToIntensityImageFilter.h index bc96075bd8..441203362e 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToIntensityImageFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToIntensityImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramToIntensityImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-17 09:13:59 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-01 14:36:37 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkHistogramIntensityFunction_h -#define __itkHistogramIntensityFunction_h +#ifndef __itkHistogramToIntensityImageFilter_h +#define __itkHistogramToIntensityImageFilter_h #include "itkHistogramToImageFilter.h" @@ -42,18 +42,17 @@ class HistogramIntensityFunction public: //Intensity function returns pixels of unsigned long.. - typedef TOutput OutputPixelType ; - + typedef TOutput OutputPixelType; HistogramIntensityFunction(): m_TotalFrequency(1) {} ~HistogramIntensityFunction() {}; - inline OutputPixelType operator()( const TInput & A ) - { + inline OutputPixelType operator()( const TInput & A ) const + { return static_cast<OutputPixelType>( A ); - } + } void SetTotalFrequency( unsigned long n ) { @@ -108,6 +107,3 @@ private: } // end namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToLogProbabilityImageFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToLogProbabilityImageFilter.h index b152844278..7bfbc0a736 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToLogProbabilityImageFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToLogProbabilityImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramToLogProbabilityImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-17 09:13:59 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-06 11:51:06 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkHistogramLogProbabilityFunction_h -#define __itkHistogramLogProbabilityFunction_h +#ifndef __itkHistogramToLogProbabilityImageFilter_h +#define __itkHistogramToLogProbabilityImageFilter_h #include "itkHistogramToImageFilter.h" @@ -61,20 +61,19 @@ public: ~HistogramLogProbabilityFunction() {}; - inline OutputPixelType operator()( const TInput & A ) - { + inline OutputPixelType operator()( const TInput & A ) const + { if( A ) { - return static_cast<OutputPixelType>(log( static_cast<OutputPixelType>(A) / + return static_cast<OutputPixelType>(vcl_log( static_cast<OutputPixelType>(A) / static_cast<OutputPixelType>(m_TotalFrequency)) / vcl_log(2.0) ); } else { // Check for Log 0. Always assume that the frequency is atleast 1. - return static_cast<OutputPixelType>(log( static_cast<OutputPixelType>(A+1) / + return static_cast<OutputPixelType>(vcl_log( static_cast<OutputPixelType>(A+1) / static_cast<OutputPixelType>(m_TotalFrequency)) / vcl_log(2.0) ); } - - } + } void SetTotalFrequency( unsigned long n ) { @@ -128,6 +127,3 @@ private: } // end namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToProbabilityImageFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToProbabilityImageFilter.h index 0ad18d4df8..9b2cf62265 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToProbabilityImageFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkHistogramToProbabilityImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHistogramToProbabilityImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-17 09:13:59 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-01 14:36:37 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkHistogramProbabilityFunction_h -#define __itkHistogramProbabilityFunction_h +#ifndef __itkHistogramToProbabilityImageFilter_h +#define __itkHistogramToProbabilityImageFilter_h #include "itkHistogramToImageFilter.h" @@ -61,11 +61,11 @@ public: ~HistogramProbabilityFunction() {}; - inline OutputPixelType operator()( const TInput & A ) - { + inline OutputPixelType operator()( const TInput & A ) const + { return static_cast<OutputPixelType>( static_cast<OutputPixelType>(A) / static_cast<OutputPixelType>(m_TotalFrequency) ); - } + } void SetTotalFrequency( unsigned long n ) { @@ -119,6 +119,3 @@ private: } // end namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkHypersphereKernelMeanShiftModeSeeker.h b/Utilities/ITK/Code/Numerics/Statistics/itkHypersphereKernelMeanShiftModeSeeker.h index d536f37281..7d521d6c20 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkHypersphereKernelMeanShiftModeSeeker.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkHypersphereKernelMeanShiftModeSeeker.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHypersphereKernelMeanShiftModeSeeker.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:57 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,8 +23,8 @@ #include "itkFixedArray.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class HypersphereKernelMeanShiftModeSeeker * \brief Evolves the mode using a hyperspherical kernel defined by a @@ -46,57 +46,57 @@ class HypersphereKernelMeanShiftModeSeeker : public: /** Standard class typedefs. */ typedef HypersphereKernelMeanShiftModeSeeker Self; - typedef MeanShiftModeSeekerBase< TSample > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef MeanShiftModeSeekerBase< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(HypersphereKernelMeanShiftModeSeeker, MeanShiftModeSeekerBase); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Typedefs from the superclass */ - typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; - typedef typename Superclass::SearchResultVectorType SearchResultVectorType ; - typedef typename Superclass::MeasurementType MeasurementType ; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::SearchResultVectorType SearchResultVectorType; + typedef typename Superclass::MeasurementType MeasurementType; /** Type for the sum of measurements */ - typedef double RealMeasurementType ; + typedef double RealMeasurementType; /** Type fot the sum of measurement vectors used in computing the new * mode */ typedef Array< RealMeasurementType > MeasurementVectorSumType; /** Sets the radius of the kernel */ - void SetSearchRadius(double radius) ; + void SetSearchRadius(double radius); /** Gets the radius of the kernel */ double GetSearchRadius() - { return m_SearchRadius ; } + { return m_SearchRadius; } /** Returns the covariance matrix of the target sample data */ - MeasurementVectorType Evolve(MeasurementVectorType instance) ; + MeasurementVectorType Evolve(MeasurementVectorType instance); protected: - HypersphereKernelMeanShiftModeSeeker() ; - virtual ~HypersphereKernelMeanShiftModeSeeker() ; + HypersphereKernelMeanShiftModeSeeker(); + virtual ~HypersphereKernelMeanShiftModeSeeker(); void PrintSelf(std::ostream& os, Indent indent) const; /** Computes the new mode with the given query point (queryPoint). The * new mode will be stored in the newPoint */ inline bool ComputeMode(MeasurementVectorType queryPoint, - MeasurementVectorType& newPoint) ; + MeasurementVectorType& newPoint); private: /** Radius of the kernel */ - double m_SearchRadius ; + double m_SearchRadius; /** Temporary measurement vector sum: internal use */ - MeasurementVectorSumType m_TempVectorSum ; + MeasurementVectorSumType m_TempVectorSum; /** Temporary measurement vector: internal use */ - MeasurementVectorType m_TempVector ; -} ; // end of class + MeasurementVectorType m_TempVector; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -106,4 +106,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkHypersphereKernelMeanShiftModeSeeker.txx b/Utilities/ITK/Code/Numerics/Statistics/itkHypersphereKernelMeanShiftModeSeeker.txx index 9f786caf33..c2ff87265c 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkHypersphereKernelMeanShiftModeSeeker.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkHypersphereKernelMeanShiftModeSeeker.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHypersphereKernelMeanShiftModeSeeker.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:57 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,14 +19,14 @@ #include "vnl/vnl_math.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > HypersphereKernelMeanShiftModeSeeker< TSample > ::HypersphereKernelMeanShiftModeSeeker() { - m_SearchRadius = 0.0 ; + m_SearchRadius = 0.0; } template< class TSample > @@ -42,7 +42,7 @@ HypersphereKernelMeanShiftModeSeeker< TSample > { Superclass::PrintSelf(os,indent); - os << indent << "Search radius: " << m_SearchRadius << std::endl ; + os << indent << "Search radius: " << m_SearchRadius << std::endl; } template< class TSample > @@ -52,8 +52,8 @@ HypersphereKernelMeanShiftModeSeeker< TSample > { if ( m_SearchRadius != radius ) { - m_SearchRadius = radius ; - this->Modified() ; + m_SearchRadius = radius; + this->Modified(); } } @@ -63,40 +63,40 @@ HypersphereKernelMeanShiftModeSeeker< TSample > ::ComputeMode(MeasurementVectorType queryPoint, MeasurementVectorType& newPoint) { - const TSample* inputSample = this->GetInputSample() ; - float frequencySum ; + const TSample* inputSample = this->GetInputSample(); + float frequencySum; - SearchResultVectorType result ; - inputSample->Search( queryPoint, m_SearchRadius, result ) ; + SearchResultVectorType result; + inputSample->Search( queryPoint, m_SearchRadius, result ); - frequencySum = 0.0f ; + frequencySum = 0.0f; MeasurementVectorTraits::SetLength( m_TempVectorSum, this->GetMeasurementVectorSize() ); - m_TempVectorSum.Fill( NumericTraits< RealMeasurementType >::Zero ) ; + m_TempVectorSum.Fill( NumericTraits< RealMeasurementType >::Zero ); - typename SearchResultVectorType::const_iterator iter = result.begin() ; + typename SearchResultVectorType::const_iterator iter = result.begin(); while ( iter != result.end() ) { - m_TempVector = inputSample->GetMeasurementVector(*iter) ; - for ( unsigned int i = 0 ; i < this->GetMeasurementVectorSize(); ++i ) + m_TempVector = inputSample->GetMeasurementVector(*iter); + for ( unsigned int i = 0; i < this->GetMeasurementVectorSize(); ++i ) { - m_TempVectorSum[i] += m_TempVector[i] ; + m_TempVectorSum[i] += m_TempVector[i]; } - frequencySum += inputSample->GetFrequency(*iter) ; - ++iter ; + frequencySum += inputSample->GetFrequency(*iter); + ++iter; } if ( frequencySum == 0 ) { - return false ; + return false; } - for ( unsigned int i = 0 ; i < this->GetMeasurementVectorSize() ; ++i ) + for ( unsigned int i = 0; i < this->GetMeasurementVectorSize(); ++i ) { - newPoint[i] = (MeasurementType) (m_TempVectorSum[i] / frequencySum) ; + newPoint[i] = (MeasurementType) (m_TempVectorSum[i] / frequencySum); } - return true ; + return true; } @@ -104,4 +104,3 @@ HypersphereKernelMeanShiftModeSeeker< TSample > } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkImageToCooccurrenceListAdaptor.h b/Utilities/ITK/Code/Numerics/Statistics/itkImageToCooccurrenceListAdaptor.h index 769d5aba2c..0e350b588e 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkImageToCooccurrenceListAdaptor.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkImageToCooccurrenceListAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageToCooccurrenceListAdaptor.h,v $ Language: C++ - Date: $Date: 2008-01-16 19:08:02 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,8 +37,8 @@ #include <algorithm> #include <iostream> -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class ImageToCooccurrenceListAdaptor * \brief Converts pixel data into a list of pairs in order to compute a cooccurrence Histogram. @@ -59,16 +59,16 @@ class ITK_EXPORT ImageToCooccurrenceListAdaptor public: typedef TImage ImageType; - typedef FixedArray< typename TImage::PixelType, 2 > MeasurementVectorType ; + typedef FixedArray< typename TImage::PixelType, 2 > MeasurementVectorType; - typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType ; - typedef typename SampleType::MeasurementVectorSizeType MeasurementVectorSizeType; + typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType; + typedef typename SampleType::MeasurementVectorSizeType MeasurementVectorSizeType; /** Standard class typedefs */ - typedef ImageToCooccurrenceListAdaptor Self; + typedef ImageToCooccurrenceListAdaptor Self; typedef ImageToListAdaptor< TImage, MeasurementVectorType > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Neighborhood iterator type. */ typedef itk::ShapedNeighborhoodIterator< @@ -76,9 +76,9 @@ public: ConstantBoundaryCondition<TImage> > ShapedNeighborhoodIteratorType; - /** Offset type used for Neighborhoods **/ + /** Offset type used for Neighborhoods */ typedef typename ShapedNeighborhoodIteratorType::OffsetType OffsetType; - typedef std::vector<OffsetType> OffsetTable; + typedef std::vector<OffsetType> OffsetTable; void UseNeighbor(const OffsetType & offset); @@ -102,19 +102,18 @@ public: << MeasurementVectorSize ); } - unsigned int GetMeasurementVectorSize() const - { - return Superclass::MeasurementVectorSize; - } - + unsigned int GetMeasurementVectorSize() const + { + return Superclass::MeasurementVectorSize; + } /** Superclass typedefs for Measurement vector, measurement, * Instance Identifier, frequency, size, size element value */ - typedef typename Superclass::PixelType PixelType ; - typedef typename Superclass::FrequencyType FrequencyType ; - typedef typename Superclass::MeasurementType MeasurementType ; - typedef typename Superclass::InstanceIdentifier InstanceIdentifier ; - typedef MeasurementVectorType ValueType ; + typedef typename Superclass::PixelType PixelType; + typedef typename Superclass::FrequencyType FrequencyType; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + typedef MeasurementVectorType ValueType; /** Image dimension. */ itkStaticConstMacro(ImageDimension, unsigned int, @@ -127,11 +126,11 @@ protected: void PrintSelf(std::ostream& os, Indent indent) const; private: - ImageToCooccurrenceListAdaptor(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented - OffsetTable m_OffsetTable; - typename SampleType::Pointer sample; -} ; // end of class ScalarImageToListAdaptor + ImageToCooccurrenceListAdaptor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + OffsetTable m_OffsetTable; + typename SampleType::Pointer m_Sample; +}; // end of class ScalarImageToListAdaptor } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkImageToCooccurrenceListAdaptor.txx b/Utilities/ITK/Code/Numerics/Statistics/itkImageToCooccurrenceListAdaptor.txx index dc5ff5bfca..06e76675de 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkImageToCooccurrenceListAdaptor.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkImageToCooccurrenceListAdaptor.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageToCooccurrenceListAdaptor.txx,v $ Language: C++ - Date: $Date: 2008-01-16 19:08:02 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,18 +14,18 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkImageToCooccurrenceListAdaptor_txx -#define _itkImageToCooccurrenceListAdaptor_txx +#ifndef __itkImageToCooccurrenceListAdaptor_txx +#define __itkImageToCooccurrenceListAdaptor_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template < class TImage > ImageToCooccurrenceListAdaptor< TImage > ::ImageToCooccurrenceListAdaptor() { - sample = SampleType::New(); - sample->SetMeasurementVectorSize( MeasurementVectorSize ); + m_Sample = SampleType::New(); + m_Sample->SetMeasurementVectorSize( MeasurementVectorSize ); } template < class TImage > @@ -49,13 +49,13 @@ ImageToCooccurrenceListAdaptor< TImage > boundaryCondition.SetConstant( -1 ); typedef itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< - ImageType > FaceCalculatorType; + ImageType > FaceCalculatorType; FaceCalculatorType faceCalculator; typename FaceCalculatorType::FaceListType faceList; typename FaceCalculatorType::FaceListType::iterator fit; - typedef typename ShapedNeighborhoodIteratorType::ConstIterator ShapeNeighborhoodIterator; + typedef typename ShapedNeighborhoodIteratorType::ConstIterator ShapeNeighborhoodIterator; typedef typename OffsetTable::iterator OffsetIterator; @@ -65,7 +65,7 @@ ImageToCooccurrenceListAdaptor< TImage > this->GetImage()->GetRequestedRegion(), radius ); - OffsetType center_offset ; + OffsetType center_offset; center_offset.Fill( 0 ); for ( fit=faceList.begin(); fit != faceList.end(); ++fit) @@ -82,25 +82,25 @@ ImageToCooccurrenceListAdaptor< TImage > } for ( it.GoToBegin(); !it.IsAtEnd(); ++it ) - { + { - const PixelType center_pixel_intensity = it.GetPixel( center_offset ); + const PixelType center_pixel_intensity = it.GetPixel( center_offset ); - ShapeNeighborhoodIterator ci = it.Begin(); - while ( ci != it.End() ) - { - const PixelType pixel_intensity = ci.Get(); + ShapeNeighborhoodIterator ci = it.Begin(); + while ( ci != it.End() ) + { + const PixelType pixel_intensity = ci.Get(); - // We have the intensity values for the center pixel and one of it's neighbours. - // We can now place these in the SampleList - coords[0] = center_pixel_intensity; - coords[1] = pixel_intensity; + // We have the intensity values for the center pixel and one of it's neighbours. + // We can now place these in the SampleList + coords[0] = center_pixel_intensity; + coords[1] = pixel_intensity; - sample->PushBack(coords) ; - ci++; - } + m_Sample->PushBack(coords); + ci++; } - } + } + } } @@ -127,7 +127,6 @@ ImageToCooccurrenceListAdaptor< TImage > } } - } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkImageToHistogramGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkImageToHistogramGenerator.h index fdfe31dcf3..a8975e5e63 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkImageToHistogramGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkImageToHistogramGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageToHistogramGenerator.h,v $ Language: C++ - Date: $Date: 2005-08-24 15:16:46 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,16 +48,16 @@ class ImageToHistogramGenerator : public Object { public: /** Standard typedefs */ - typedef ImageToHistogramGenerator Self ; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef ImageToHistogramGenerator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(ImageToHistogramGenerator, Object) ; + itkTypeMacro(ImageToHistogramGenerator, Object); /** standard New() method support */ - itkNewMacro(Self) ; + itkNewMacro(Self); typedef TImageType ImageType; typedef ImageToListAdaptor< ImageType > AdaptorType; diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkImageToHistogramGenerator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkImageToHistogramGenerator.txx index 81ecd0d317..c13ae9b57a 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkImageToHistogramGenerator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkImageToHistogramGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageToHistogramGenerator.txx,v $ Language: C++ - Date: $Date: 2007-01-17 15:13:42 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkImageToHistogramGenerator_txx -#define _itkImageToHistogramGenerator_txx +#ifndef __itkImageToHistogramGenerator_txx +#define __itkImageToHistogramGenerator_txx #include "itkImageToHistogramGenerator.h" @@ -39,8 +39,6 @@ ImageToHistogramGenerator< TImage > } - - template < class TImage > void ImageToHistogramGenerator< TImage > @@ -58,8 +56,6 @@ ImageToHistogramGenerator< TImage > return m_HistogramGenerator->GetOutput(); } - - template < class TImage > void ImageToHistogramGenerator< TImage > @@ -68,8 +64,6 @@ ImageToHistogramGenerator< TImage > m_HistogramGenerator->Update(); } - - template < class TImage > void ImageToHistogramGenerator< TImage > @@ -78,8 +72,6 @@ ImageToHistogramGenerator< TImage > m_HistogramGenerator->SetNumberOfBins( size ); } - - template < class TImage > void ImageToHistogramGenerator< TImage > @@ -126,11 +118,7 @@ ImageToHistogramGenerator< TImage > os << "HistogramGenerator = " << m_HistogramGenerator << std::endl; } - - } // end of namespace Statistics } // end of namespace itk #endif - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkImageToListAdaptor.h b/Utilities/ITK/Code/Numerics/Statistics/itkImageToListAdaptor.h index 9bab4eaa29..908acbaf2e 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkImageToListAdaptor.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkImageToListAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageToListAdaptor.h,v $ Language: C++ - Date: $Date: 2008-08-19 22:27:57 $ - Version: $Revision: 1.38 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.39 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,8 +27,8 @@ #include "itkFixedArray.h" #include "itkMacro.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class ImageToListAdaptor * \brief This class provides ListSampleBase interfaces to ITK Image @@ -67,10 +67,10 @@ class ITK_EXPORT ImageToListAdaptor : { public: /** Standard class typedefs */ - typedef ImageToListAdaptor Self; + typedef ImageToListAdaptor Self; typedef ListSampleBase< TMeasurementVector > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(ImageToListAdaptor, ListSampleBase); @@ -79,14 +79,14 @@ public: itkNewMacro(Self); /** Image typedefs */ - typedef TImage ImageType; - typedef typename ImageType::Pointer ImagePointer; - typedef typename ImageType::ConstPointer ImageConstPointer; - typedef typename ImageType::IndexType IndexType; - typedef typename ImageType::PixelType PixelType; + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::PixelType PixelType; typedef typename ImageType::PixelContainerConstPointer PixelContainerConstPointer; typedef typename ImageType::PixelContainer::ElementIdentifier - InstanceIdentifier; + InstanceIdentifier; /** Image Iterator typedef support */ typedef ImageRegionIterator< ImageType > IteratorType; @@ -94,9 +94,9 @@ public: /** Superclass typedefs for Measurement vector, measurement, * Instance Identifier, frequency, size, size element value */ - typedef typename PixelTraitsType::ValueType MeasurementType; - typedef typename Superclass::FrequencyType FrequencyType; - typedef typename Superclass::TotalFrequencyType TotalFrequencyType; + typedef typename PixelTraitsType::ValueType MeasurementType; + typedef typename Superclass::FrequencyType FrequencyType; + typedef typename Superclass::TotalFrequencyType TotalFrequencyType; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; /** the number of components in a measurement vector */ @@ -123,7 +123,7 @@ public: - typedef TMeasurementVector MeasurementVectorType; + typedef TMeasurementVector MeasurementVectorType; typedef MeasurementVectorType ValueType; /** Method to set the image */ @@ -149,32 +149,28 @@ public: Iterator(){} Iterator(InstanceIdentifier id, Pointer pContainer) - :m_Id(id),m_Container(pContainer) - {} + :m_Id(id),m_Container(pContainer) {} FrequencyType GetFrequency() const - { return 1;} + { return 1;} const MeasurementVectorType & GetMeasurementVector() const - { return m_Container->GetMeasurementVector(m_Id);} + { return m_Container->GetMeasurementVector(m_Id);} InstanceIdentifier GetInstanceIdentifier() const - { return m_Id;} + { return m_Id;} Iterator& operator++() - { ++m_Id; return *this;} + { ++m_Id; return *this;} - /*Iterator& operator+() - { m_Id += n; return *this;}*/ - Iterator& operator+(int n) - { m_Id += n; return *this;} + { m_Id += n; return *this;} Iterator& operator-(int n) - { m_Id -= n; return *this;} + { m_Id -= n; return *this;} bool operator!=(const Iterator &it) - { + { if (m_Id != it.m_Id) {return true;} @@ -182,23 +178,23 @@ public: { return true;} return false; - } + } bool operator==(const Iterator &it) - { return !(*this != it);} + { return !(*this != it);} Iterator& operator = (const Iterator &iter) - { + { m_Id = iter.m_Id; m_Container = iter.m_Container; return *this; - } + } Iterator(const Iterator &iter) - { + { m_Id = iter.m_Id; m_Container = iter.m_Container; - } + } private: InstanceIdentifier m_Id; // Current id @@ -207,38 +203,34 @@ public: class ConstIterator - { - public: + { + public: ConstIterator(){} ConstIterator(InstanceIdentifier id, ConstPointer pContainer) - :m_Id(id),m_Container(pContainer) - {} + :m_Id(id),m_Container(pContainer) {} FrequencyType GetFrequency() const - { return 1;} + { return 1;} const MeasurementVectorType & GetMeasurementVector() const - { return m_Container->GetMeasurementVector(m_Id);} + { return m_Container->GetMeasurementVector(m_Id);} InstanceIdentifier GetInstanceIdentifier() const - { return m_Id;} + { return m_Id;} ConstIterator& operator++() - { ++m_Id; return *this;} + { ++m_Id; return *this;} - /*ConstIterator& operator+() - { m_Id += n; return *this;}*/ - ConstIterator& operator+(int n) - { m_Id += n; return *this;} + { m_Id += n; return *this;} ConstIterator& operator-(int n) - { m_Id -= n; return *this;} + { m_Id -= n; return *this;} bool operator!=(const ConstIterator &it) - { + { if (m_Id != it.m_Id) {return true;} @@ -246,54 +238,52 @@ public: { return true;} return false; - } + } bool operator==(const ConstIterator &it) - { return !(*this != it);} + { return !(*this != it);} ConstIterator& operator = (const ConstIterator &iter) - { + { m_Id = iter.m_Id; m_Container = iter.m_Container; return *this; - } + } ConstIterator(const ConstIterator &iter) - { + { m_Id = iter.m_Id; m_Container = iter.m_Container; - } + } private: InstanceIdentifier m_Id; // Current id ConstPointer m_Container; }; - - Iterator Begin() - { + { Iterator iter(0, this); return iter; - } + } - Iterator End() - { + Iterator End() + { Iterator iter(this->Size(), this); return iter; - } + } ConstIterator Begin() const - { + { ConstIterator iter(0, this); return iter; - } + } ConstIterator End() const - { + { ConstIterator iter(this->Size(), this); return iter; - } + } protected: ImageToListAdaptor(); @@ -311,9 +301,9 @@ private: void operator=(const Self&); //purposely not implemented PixelContainerConstPointer m_PixelContainer; - bool m_UseBuffer; - IndexType m_ImageBeginIndex; - IndexType m_ImageEndIndex; + bool m_UseBuffer; + IndexType m_ImageBeginIndex; + IndexType m_ImageEndIndex; ImageConstPointer m_Image; }; // end of class ImageToListAdaptor @@ -351,8 +341,6 @@ ImageToListAdaptor< TImage, TMeasurementVector > return NumericTraits< FrequencyType >::One; } - - } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkImageToListAdaptor.txx b/Utilities/ITK/Code/Numerics/Statistics/itkImageToListAdaptor.txx index 90e6ae6e38..00fcefac2e 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkImageToListAdaptor.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkImageToListAdaptor.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageToListAdaptor.txx,v $ Language: C++ - Date: $Date: 2008-08-19 22:27:57 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,11 +14,11 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkImageToListAdaptor_txx -#define _itkImageToListAdaptor_txx +#ifndef __itkImageToListAdaptor_txx +#define __itkImageToListAdaptor_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template < class TImage, class TMeasurementVector > ImageToListAdaptor< TImage, TMeasurementVector > @@ -105,6 +105,3 @@ ImageToListAdaptor< TImage, TMeasurementVector > } // end of namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkJointDomainImageToListAdaptor.h b/Utilities/ITK/Code/Numerics/Statistics/itkJointDomainImageToListAdaptor.h index f10e148708..ae1c9ef313 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkJointDomainImageToListAdaptor.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkJointDomainImageToListAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkJointDomainImageToListAdaptor.h,v $ Language: C++ - Date: $Date: 2007-08-23 20:01:10 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-03-04 15:23:50 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,8 +26,8 @@ #include "itkEuclideanDistance.h" #include "itkListSample.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class ImageJointDomainTraits * \brief This class provides the type defintion for the measurement @@ -39,23 +39,26 @@ namespace Statistics{ template< class TImage > struct ImageJointDomainTraits { - typedef ImageJointDomainTraits Self ; - typedef PixelTraits< typename TImage::PixelType > PixelTraitsType ; - typedef typename PixelTraitsType::ValueType RangeDomainMeasurementType ; - typedef typename TImage::IndexType::IndexValueType IndexValueType ; - itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension) ; + typedef ImageJointDomainTraits Self; + typedef PixelTraits< typename TImage::PixelType > PixelTraitsType; + typedef typename PixelTraitsType::ValueType RangeDomainMeasurementType; + typedef typename TImage::IndexType::IndexValueType IndexValueType; + + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); itkStaticConstMacro(Dimension, unsigned int, TImage::ImageDimension + - PixelTraitsType::Dimension ) ; - typedef float CoordinateRepType ; - typedef Point< CoordinateRepType, itkGetStaticConstMacro(ImageDimension) > PointType ; + PixelTraitsType::Dimension ); + + typedef float CoordinateRepType; + typedef Point< CoordinateRepType, itkGetStaticConstMacro(ImageDimension) > + PointType; typedef JoinTraits< RangeDomainMeasurementType, CoordinateRepType > - JoinTraitsType ; - typedef typename JoinTraitsType::ValueType MeasurementType ; + JoinTraitsType; + typedef typename JoinTraitsType::ValueType MeasurementType; typedef FixedArray< MeasurementType, itkGetStaticConstMacro(Dimension) > - MeasurementVectorType ; -} ; // end of ImageJointDomainTraits + MeasurementVectorType; +}; // end of ImageJointDomainTraits /** \class JointDomainImageToListAdaptor * \brief This adaptor returns measurement vectors composed of an @@ -93,33 +96,34 @@ class ITK_EXPORT JointDomainImageToListAdaptor typename ImageJointDomainTraits< TImage >::MeasurementVectorType > { public: - typedef ImageJointDomainTraits< TImage > ImageJointDomainTraitsType ; + typedef ImageJointDomainTraits< TImage > ImageJointDomainTraitsType; typedef typename ImageJointDomainTraitsType::MeasurementVectorType - MeasurementVectorType ; + MeasurementVectorType; typedef typename ImageJointDomainTraitsType::MeasurementType - MeasurementType ; + MeasurementType; typedef typename ImageJointDomainTraitsType::RangeDomainMeasurementType - RangeDomainMeasurementType ; - typedef typename ImageJointDomainTraitsType::PointType PointType ; + RangeDomainMeasurementType; + typedef typename ImageJointDomainTraitsType::PointType + PointType; typedef typename ImageJointDomainTraitsType::CoordinateRepType - CoordinateRepType ; + CoordinateRepType; /** Standard class typedefs */ - typedef JointDomainImageToListAdaptor Self; + typedef JointDomainImageToListAdaptor Self; typedef ImageToListAdaptor< TImage, MeasurementVectorType > - Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer<const Self> ConstPointer; + Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(JointDomainImageToListAdaptor, ImageToListAdaptor) ; + itkTypeMacro(JointDomainImageToListAdaptor, ImageToListAdaptor); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** the number of components in a measurement vector */ itkStaticConstMacro(MeasurementVectorSize, unsigned int, - ImageJointDomainTraitsType::Dimension) ; + ImageJointDomainTraitsType::Dimension); typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; @@ -141,33 +145,33 @@ public: /** typedefs for Measurement vector, measurement, * Instance Identifier, frequency, size, size element value */ - typedef typename Superclass::FrequencyType FrequencyType ; - typedef typename Superclass::InstanceIdentifier InstanceIdentifier ; + typedef typename Superclass::FrequencyType FrequencyType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; - typedef typename TImage::IndexType ImageIndexType ; - typedef typename TImage::IndexType::IndexValueType ImageIndexValueType ; - typedef typename TImage::SizeType ImageSizeType ; - typedef typename TImage::RegionType ImageRegionType ; - typedef ImageRegionConstIteratorWithIndex< TImage > ImageIteratorType ; + typedef typename TImage::IndexType ImageIndexType; + typedef typename TImage::IndexType::IndexValueType ImageIndexValueType; + typedef typename TImage::SizeType ImageSizeType; + typedef typename TImage::RegionType ImageRegionType; + typedef ImageRegionConstIteratorWithIndex< TImage > ImageIteratorType; - typedef MeasurementVectorType ValueType ; + typedef MeasurementVectorType ValueType; itkStaticConstMacro(RangeDomainDimension, unsigned int, itk::PixelTraits< - typename TImage::PixelType >::Dimension) ; + typename TImage::PixelType >::Dimension); typedef FixedArray< RangeDomainMeasurementType, itkGetStaticConstMacro( RangeDomainDimension ) > - RangeDomainMeasurementVectorType ; + RangeDomainMeasurementVectorType; - typedef std::vector< InstanceIdentifier > InstanceIdentifierVectorType ; + typedef std::vector< InstanceIdentifier > InstanceIdentifierVectorType; typedef FixedArray< float, itkGetStaticConstMacro(MeasurementVectorSize) > - NormalizationFactorsType ; + NormalizationFactorsType; /** Sets the normalization factors */ - void SetNormalizationFactors(NormalizationFactorsType& factors) ; + void SetNormalizationFactors(NormalizationFactorsType& factors); /** Gets the measurement vector specified by the instance * identifier. This method overrides superclass method. */ @@ -187,56 +191,56 @@ public: InstanceIdentifierVectorType& result) const; protected: - JointDomainImageToListAdaptor() ; + JointDomainImageToListAdaptor(); virtual ~JointDomainImageToListAdaptor() {} void PrintSelf(std::ostream& os, Indent indent) const; private: - JointDomainImageToListAdaptor(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + JointDomainImageToListAdaptor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - NormalizationFactorsType m_NormalizationFactors ; + NormalizationFactorsType m_NormalizationFactors; - mutable MeasurementVectorType m_TempVector ; - mutable PointType m_TempPoint ; - mutable ImageIndexType m_TempIndex ; - mutable RangeDomainMeasurementVectorType m_TempRangeVector ; -} ; // end of class JointDomainImageToListAdaptor + mutable MeasurementVectorType m_TempVector; + mutable PointType m_TempPoint; + mutable ImageIndexType m_TempIndex; + mutable RangeDomainMeasurementVectorType m_TempRangeVector; +}; // end of class JointDomainImageToListAdaptor template < class TImage > inline const typename JointDomainImageToListAdaptor< TImage >::MeasurementVectorType & JointDomainImageToListAdaptor< TImage > ::GetMeasurementVector(const InstanceIdentifier &id) const { - m_TempIndex = this->GetImage()->ComputeIndex( id ) ; + m_TempIndex = this->GetImage()->ComputeIndex( id ); - this->GetImage()->TransformIndexToPhysicalPoint( m_TempIndex, m_TempPoint ) ; + this->GetImage()->TransformIndexToPhysicalPoint( m_TempIndex, m_TempPoint ); - for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i ) + for ( unsigned int i = 0; i < TImage::ImageDimension; ++i ) { - m_TempVector[i] = m_TempPoint[i] / m_NormalizationFactors[i] ; + m_TempVector[i] = m_TempPoint[i] / m_NormalizationFactors[i]; } if( this->GetUseBuffer() ) { m_TempRangeVector = *(reinterpret_cast<const RangeDomainMeasurementVectorType* > - (&(*this->GetPixelContainer())[id])) ; + (&(*this->GetPixelContainer())[id])); } else { m_TempRangeVector = *(reinterpret_cast< const RangeDomainMeasurementVectorType* > - (&(this->GetImage()->GetPixel( m_TempIndex ) ) ) ) ; + (&(this->GetImage()->GetPixel( m_TempIndex ) ) ) ); } - for ( unsigned int i = TImage::ImageDimension ; i < MeasurementVectorType::Length ; ++i ) + for ( unsigned int i = TImage::ImageDimension; i < MeasurementVectorType::Length; ++i ) { m_TempVector[i] = m_TempRangeVector[i - TImage::ImageDimension] - / m_NormalizationFactors[i] ; + / m_NormalizationFactors[i]; } - return m_TempVector ; + return m_TempVector; } template < class TImage > @@ -246,34 +250,34 @@ JointDomainImageToListAdaptor< TImage > const double radius, ImageRegionType& region) const { - ImageIndexType beginIndex ; - ImageSizeType size ; + ImageIndexType beginIndex; + ImageSizeType size; - for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i ) + for ( unsigned int i = 0; i < TImage::ImageDimension; ++i ) { - m_TempPoint[i] = m_NormalizationFactors[i] * (mv[i] - radius) ; + m_TempPoint[i] = m_NormalizationFactors[i] * (mv[i] - radius); size[i] = (unsigned long)(2.0 * m_NormalizationFactors[i] * radius - / this->GetImage()->GetSpacing()[i]) ; + / this->GetImage()->GetSpacing()[i]); } - this->GetImage()->TransformPhysicalPointToIndex(m_TempPoint , beginIndex ) ; + this->GetImage()->TransformPhysicalPointToIndex(m_TempPoint , beginIndex ); - for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i ) + for ( unsigned int i = 0; i < TImage::ImageDimension; ++i ) { if ( beginIndex[i] < this->GetImageBeginIndex()[i] ) { - beginIndex[i] = this->GetImageBeginIndex()[i] ; - size[i] -= (this->GetImageBeginIndex()[i] - beginIndex[i]) ; + beginIndex[i] = this->GetImageBeginIndex()[i]; + size[i] -= (this->GetImageBeginIndex()[i] - beginIndex[i]); } if ( static_cast<typename ImageIndexType::IndexValueType>(beginIndex[i] + size[i] - 1) > this->GetImageEndIndex()[i] ) { - size[i] = this->GetImageEndIndex()[i] - beginIndex[i] + 1 ; + size[i] = this->GetImageEndIndex()[i] - beginIndex[i] + 1; } } - region.SetIndex( beginIndex ) ; - region.SetSize( size ) ; + region.SetIndex( beginIndex ); + region.SetSize( size ); } template < class TImage > @@ -283,36 +287,36 @@ JointDomainImageToListAdaptor< TImage > const double radius, InstanceIdentifierVectorType& result) const { - ImageRegionType region ; - this->ComputeRegion( mv, radius, region ) ; + ImageRegionType region; + this->ComputeRegion( mv, radius, region ); - result.clear() ; - ImageIteratorType iter( this->GetImage(), region ) ; - iter.GoToBegin() ; - double squaredRadius = radius * radius ; + result.clear(); + ImageIteratorType iter( this->GetImage(), region ); + iter.GoToBegin(); + double squaredRadius = radius * radius; InstanceIdentifier instanceID; while ( !iter.IsAtEnd() ) { - instanceID = this->GetImage()->ComputeOffset(iter.GetIndex()) ; - m_TempVector = this->GetMeasurementVector( instanceID ) ; - bool isWithinRange = true ; - double sum = 0.0 ; - for ( unsigned int i = 0 ; i < MeasurementVectorSize ; ++i ) + instanceID = this->GetImage()->ComputeOffset(iter.GetIndex()); + m_TempVector = this->GetMeasurementVector( instanceID ); + bool isWithinRange = true; + double sum = 0.0; + for ( unsigned int i = 0; i < MeasurementVectorSize; ++i ) { - const double temp = (m_TempVector[i] - mv[i]) ; - sum += temp * temp ; + const double temp = (m_TempVector[i] - mv[i]); + sum += temp * temp; if ( sum > squaredRadius ) { - isWithinRange = false ; - break ; + isWithinRange = false; + break; } } if ( isWithinRange ) { - result.push_back(instanceID) ; + result.push_back(instanceID); } - ++iter ; + ++iter; } } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkJointDomainImageToListAdaptor.txx b/Utilities/ITK/Code/Numerics/Statistics/itkJointDomainImageToListAdaptor.txx index 6cd5005019..7aac5e5718 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkJointDomainImageToListAdaptor.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkJointDomainImageToListAdaptor.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkJointDomainImageToListAdaptor.txx,v $ Language: C++ - Date: $Date: 2006-10-14 19:58:32 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 15:23:51 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,19 +14,19 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkJointDomainImageToListAdaptor_txx -#define _itkJointDomainImageToListAdaptor_txx +#ifndef __itkJointDomainImageToListAdaptor_txx +#define __itkJointDomainImageToListAdaptor_txx #include "itkJointDomainImageToListAdaptor.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template < class TImage > JointDomainImageToListAdaptor< TImage > ::JointDomainImageToListAdaptor() { - m_NormalizationFactors.Fill( 1.0f ) ; + m_NormalizationFactors.Fill( 1.0f ); } template < class TImage > @@ -44,8 +44,8 @@ JointDomainImageToListAdaptor< TImage > { if ( m_NormalizationFactors != factors ) { - m_NormalizationFactors = factors ; - this->Modified() ; + m_NormalizationFactors = factors; + this->Modified(); } } @@ -54,6 +54,3 @@ JointDomainImageToListAdaptor< TImage > } // end of namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkKdTree.h b/Utilities/ITK/Code/Numerics/Statistics/itkKdTree.h index 87581c511d..08700c5a5f 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkKdTree.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkKdTree.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKdTree.h,v $ Language: C++ - Date: $Date: 2008-04-26 00:08:19 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-03-04 15:23:51 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,8 +32,8 @@ #include "itkEuclideanDistance.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class KdTreeNode * \brief This class defines the interface of its derived classes. @@ -129,9 +129,9 @@ struct KdTreeNode template< class TSample > struct KdTreeNonterminalNode: public KdTreeNode< TSample > { - typedef KdTreeNode< TSample > Superclass; - typedef typename Superclass::MeasurementType MeasurementType; - typedef typename Superclass::CentroidType CentroidType; + typedef KdTreeNode< TSample > Superclass; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::CentroidType CentroidType; typedef typename Superclass::InstanceIdentifier InstanceIdentifier; KdTreeNonterminalNode(unsigned int partitionDimension, @@ -142,40 +142,40 @@ struct KdTreeNonterminalNode: public KdTreeNode< TSample > virtual ~KdTreeNonterminalNode() {} virtual bool IsTerminal() const - { return false; } + { return false; } void GetParameters(unsigned int &partitionDimension, MeasurementType &partitionValue) const; Superclass* Left() - { return m_Left; } + { return m_Left; } Superclass* Right() - { return m_Right; } + { return m_Right; } const Superclass* Left() const - { return m_Left; } + { return m_Left; } const Superclass* Right() const - { return m_Right; } + { return m_Right; } unsigned int Size() const - { return 0; } + { return 0; } void GetWeightedCentroid( CentroidType & ) - { /* do nothing */ } + {} void GetCentroid( CentroidType & ) - { /* do nothing */ } + {} // Returns the identifier of the only MeasurementVector associated with // this node in the tree. This MeasurementVector will be used later during // the distance computation when querying the tree. InstanceIdentifier GetInstanceIdentifier(size_t) const - { return this->m_InstanceIdentifier; } + { return this->m_InstanceIdentifier; } void AddInstanceIdentifier(InstanceIdentifier valueId) - { this->m_InstanceIdentifier = valueId; } + { this->m_InstanceIdentifier = valueId; } private: unsigned int m_PartitionDimension; @@ -202,10 +202,10 @@ private: template< class TSample > struct KdTreeWeightedCentroidNonterminalNode: public KdTreeNode< TSample > { - typedef KdTreeNode< TSample > Superclass; - typedef typename Superclass::MeasurementType MeasurementType; - typedef typename Superclass::CentroidType CentroidType; - typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + typedef KdTreeNode< TSample > Superclass; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::CentroidType CentroidType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; KdTreeWeightedCentroidNonterminalNode(unsigned int partitionDimension, @@ -217,7 +217,7 @@ struct KdTreeWeightedCentroidNonterminalNode: public KdTreeNode< TSample > virtual ~KdTreeWeightedCentroidNonterminalNode() {} virtual bool IsTerminal() const - { return false; } + { return false; } void GetParameters(unsigned int &partitionDimension, MeasurementType &partitionValue) const; @@ -229,26 +229,25 @@ struct KdTreeWeightedCentroidNonterminalNode: public KdTreeNode< TSample > } Superclass* Left() - { return m_Left; } + { return m_Left; } Superclass* Right() - { return m_Right; } - + { return m_Right; } const Superclass* Left() const - { return m_Left; } + { return m_Left; } const Superclass* Right() const - { return m_Right; } + { return m_Right; } unsigned int Size() const - { return m_Size; } + { return m_Size; } void GetWeightedCentroid(CentroidType ¢roid) { centroid = m_WeightedCentroid; } void GetCentroid(CentroidType ¢roid) - { centroid = m_Centroid; } + { centroid = m_Centroid; } InstanceIdentifier GetInstanceIdentifier(size_t) const { return this->m_InstanceIdentifier; } @@ -283,9 +282,9 @@ private: template< class TSample > struct KdTreeTerminalNode: public KdTreeNode< TSample > { - typedef KdTreeNode< TSample > Superclass; - typedef typename Superclass::MeasurementType MeasurementType; - typedef typename Superclass::CentroidType CentroidType; + typedef KdTreeNode< TSample > Superclass; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::CentroidType CentroidType; typedef typename Superclass::InstanceIdentifier InstanceIdentifier; KdTreeTerminalNode() {} @@ -293,38 +292,37 @@ struct KdTreeTerminalNode: public KdTreeNode< TSample > virtual ~KdTreeTerminalNode() {} bool IsTerminal() const - { return true; } + { return true; } void GetParameters(unsigned int &, MeasurementType &) const {} Superclass* Left() - { return 0; } + { return 0; } Superclass* Right() - { return 0; } - + { return 0; } const Superclass* Left() const - { return 0; } + { return 0; } const Superclass* Right() const - { return 0; } + { return 0; } unsigned int Size() const - { return static_cast<unsigned int>( m_InstanceIdentifiers.size() ); } + { return static_cast<unsigned int>( m_InstanceIdentifiers.size() ); } void GetWeightedCentroid(CentroidType &) - { /* do nothing */ } + {} void GetCentroid(CentroidType &) - { /* do nothing */ } + {} InstanceIdentifier GetInstanceIdentifier(size_t index) const - { return m_InstanceIdentifiers[index]; } + { return m_InstanceIdentifiers[index]; } void AddInstanceIdentifier(InstanceIdentifier id) - { m_InstanceIdentifiers.push_back(id);} + { m_InstanceIdentifiers.push_back(id);} private: std::vector< InstanceIdentifier > m_InstanceIdentifiers; @@ -367,9 +365,9 @@ class ITK_EXPORT KdTree : public Object { public: /** Standard class typedefs */ - typedef KdTree Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; + typedef KdTree Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods) */ @@ -379,11 +377,11 @@ public: itkNewMacro(Self); /** typedef alias for the source data container */ - typedef TSample SampleType; + typedef TSample SampleType; typedef typename TSample::MeasurementVectorType MeasurementVectorType; - typedef typename TSample::MeasurementType MeasurementType; - typedef typename TSample::InstanceIdentifier InstanceIdentifier; - typedef typename TSample::FrequencyType FrequencyType; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::InstanceIdentifier InstanceIdentifier; + typedef typename TSample::FrequencyType FrequencyType; typedef unsigned int MeasurementVectorSizeType; @@ -414,8 +412,8 @@ public: * method. */ class NearestNeighbors - { - public: + { + public: /** Constructor */ NearestNeighbors() {} @@ -425,22 +423,22 @@ public: /** Initialize the internal instance identifier and distance holders * with the size, k */ void resize(unsigned int k) - { + { m_Identifiers.clear(); m_Identifiers.resize(k, NumericTraits< unsigned long >::max()); m_Distances.clear(); m_Distances.resize(k, NumericTraits< double >::max()); m_FarthestNeighborIndex = 0; - } + } /** Returns the distance of the farthest neighbor from the query point */ double GetLargestDistance() - { return m_Distances[m_FarthestNeighborIndex]; } + { return m_Distances[m_FarthestNeighborIndex]; } /** Replaces the farthest neighbor's instance identifier and * distance value with the id and the distance */ void ReplaceFarthestNeighbor(InstanceIdentifier id, double distance) - { + { m_Identifiers[m_FarthestNeighborIndex] = id; m_Distances[m_FarthestNeighborIndex] = distance; double farthestDistance = NumericTraits< double >::min(); @@ -453,31 +451,31 @@ public: m_FarthestNeighborIndex = i; } } - } - + } + /** Returns the vector of k-neighbors' instance identifiers */ const InstanceIdentifierVectorType & GetNeighbors() const - { return m_Identifiers; } + { return m_Identifiers; } /** Returns the instance identifier of the index-th neighbor among * k-neighbors */ InstanceIdentifier GetNeighbor(unsigned int index) const - { return m_Identifiers[index]; } + { return m_Identifiers[index]; } /** Returns the vector of k-neighbors' instance identifiers */ const std::vector< double >& GetDistances() const - { return m_Distances; } + { return m_Distances; } - private: - /** The index of the farthest neighbor among k-neighbors */ - unsigned int m_FarthestNeighborIndex; + private: + /** The index of the farthest neighbor among k-neighbors */ + unsigned int m_FarthestNeighborIndex; - /** Storage for the instance identifiers of k-neighbors */ - InstanceIdentifierVectorType m_Identifiers; + /** Storage for the instance identifiers of k-neighbors */ + InstanceIdentifierVectorType m_Identifiers; - /** Storage for the distance values of k-neighbors from the query - * point */ - std::vector< double > m_Distances; + /** Storage for the distance values of k-neighbors from the query + * point */ + std::vector< double > m_Distances; }; /** Sets the number of measurement vectors that can be stored in a @@ -490,40 +488,40 @@ public: /** Returns the pointer to the input sample */ const TSample* GetSample() const - { return m_Sample; } + { return m_Sample; } unsigned long Size() const - { return m_Sample->Size(); } + { return m_Sample->Size(); } /** Returns the pointer to the empty terminal node. A KdTree object * has a single empty terminal node in memory. when the split process * has to create an empty terminal node, the single instance is reused * for this case */ KdTreeNodeType* GetEmptyTerminalNode() - { return m_EmptyTerminalNode; } + { return m_EmptyTerminalNode; } /** Sets the root node of the KdTree that is a result of * KdTreeGenerator or WeightedCentroidKdTreeGenerator. */ void SetRoot(KdTreeNodeType* root) - { m_Root = root; } + { m_Root = root; } /** Returns the pointer to the root node. */ KdTreeNodeType* GetRoot() - { return m_Root; } + { return m_Root; } /** Returns the measurement vector identified by the instance * identifier that is an identifier defiend for the input sample */ const MeasurementVectorType & GetMeasurementVector(InstanceIdentifier id) const - { return m_Sample->GetMeasurementVector(id); } + { return m_Sample->GetMeasurementVector(id); } /** Returns the frequency of the measurement vector identified by * the instance identifier */ FrequencyType GetFrequency(InstanceIdentifier id) const - { return m_Sample->GetFrequency( id ); } + { return m_Sample->GetFrequency( id ); } /** Get the pointer to the distance metric. */ DistanceMetricType* GetDistanceMetric() - { return m_DistanceMetric.GetPointer(); } + { return m_DistanceMetric.GetPointer(); } /** Searches the k-nearest neighbors */ void Search(const MeasurementVectorType &query, @@ -538,13 +536,13 @@ public: /** Returns the number of measurement vectors that have been visited * to find the k-nearest neighbors. */ int GetNumberOfVisits() const - { return m_NumberOfVisits; } + { return m_NumberOfVisits; } /** Returns true if the intermediate k-nearest neighbors exist within * the the bounding box defined by the lowerBound and the * upperBound. Otherwise returns false. Returns false if the ball * defined by the distance between the query point and the farthest - * neighbor touch the surface of the bounding box.*/ + * neighbor touch the surface of the bounding box. */ bool BallWithinBounds(const MeasurementVectorType &query, MeasurementVectorType &lowerBound, MeasurementVectorType &upperBound, @@ -552,7 +550,7 @@ public: /** Returns true if the ball defined by the distance between the query * point and the farthest neighbor overlaps with the bounding box - * defined by the lower and the upper bounds.*/ + * defined by the lower and the upper bounds. */ bool BoundsOverlapBall(const MeasurementVectorType &query, MeasurementVectorType &lowerBound, MeasurementVectorType &upperBound, @@ -577,32 +575,32 @@ public: void PlotTree(KdTreeNodeType *node, std::ostream & os = std::cout ) const; - typedef typename TSample::Iterator Iterator; + typedef typename TSample::Iterator Iterator; typedef typename TSample::ConstIterator ConstIterator; Iterator Begin() - { + { typename TSample::ConstIterator iter = m_Sample->Begin(); return iter; - } + } Iterator End() - { + { Iterator iter = m_Sample->End(); return iter; - } + } ConstIterator Begin() const - { + { typename TSample::ConstIterator iter = m_Sample->Begin(); return iter; - } + } ConstIterator End() const - { + { ConstIterator iter = m_Sample->End(); return iter; - } + } protected: /** Constructor */ diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkKdTree.txx b/Utilities/ITK/Code/Numerics/Statistics/itkKdTree.txx index 35b1be646a..5a66a6d6e7 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkKdTree.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkKdTree.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKdTree.txx,v $ Language: C++ - Date: $Date: 2008-04-30 23:34:46 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-03-04 15:23:51 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkKdTree.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > KdTreeNonterminalNode< TSample > @@ -500,7 +500,7 @@ KdTree< TSample > double temp; unsigned int dimension; double squaredSearchRadius = radius * radius; - for (dimension = 0 ; dimension < m_MeasurementVectorSize; dimension++) + for (dimension = 0; dimension < m_MeasurementVectorSize; dimension++) { if (query[dimension] <= lowerBound[dimension]) @@ -556,7 +556,7 @@ KdTree< TSample > } os << "Terminal: level = " << level - << " dim = " << activeDimension<< std::endl ; + << " dim = " << activeDimension<< std::endl; os << " "; for (unsigned int i = 0; i < node->Size(); i++) { @@ -648,19 +648,17 @@ KdTree< TSample > if( left && ( left != m_EmptyTerminalNode ) ) { - os << "\"" << node << "\" -> \"" << left << "\" ;" << std::endl; + os << "\"" << node << "\" -> \"" << left << "\";" << std::endl; this->PlotTree( left, os ); } if( right && ( right != m_EmptyTerminalNode ) ) { - os << "\"" << node << "\" -> \"" << right << "\" ;" << std::endl; + os << "\"" << node << "\" -> \"" << right << "\";" << std::endl; this->PlotTree( right, os ); } } - - } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeBasedKmeansEstimator.h b/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeBasedKmeansEstimator.h index ec40fb4f3b..28c8d502f9 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeBasedKmeansEstimator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeBasedKmeansEstimator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKdTreeBasedKmeansEstimator.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:59 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-03-04 15:23:51 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -69,10 +69,10 @@ class ITK_EXPORT KdTreeBasedKmeansEstimator: { public: /** Standard "Self" typedef. */ - typedef KdTreeBasedKmeansEstimator Self ; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef KdTreeBasedKmeansEstimator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -81,12 +81,12 @@ public: itkTypeMacro(KdTreeBasedKmeansEstimator, Obeject); /** Types for the KdTree data structure */ - typedef typename TKdTree::KdTreeNodeType KdTreeNodeType ; - typedef typename TKdTree::MeasurementType MeasurementType ; - typedef typename TKdTree::MeasurementVectorType MeasurementVectorType ; - typedef typename TKdTree::InstanceIdentifier InstanceIdentifier ; - typedef typename TKdTree::SampleType SampleType ; - typedef typename KdTreeNodeType::CentroidType CentroidType ; + typedef typename TKdTree::KdTreeNodeType KdTreeNodeType; + typedef typename TKdTree::MeasurementType MeasurementType; + typedef typename TKdTree::MeasurementVectorType MeasurementVectorType; + typedef typename TKdTree::InstanceIdentifier InstanceIdentifier; + typedef typename TKdTree::SampleType SampleType; + typedef typename KdTreeNodeType::CentroidType CentroidType; /** Typedef for the length of a measurement vector */ @@ -94,17 +94,17 @@ public: /** Parameters type. * It defines a position in the optimization search space. */ - typedef Array< double > ParameterType ; + typedef Array< double > ParameterType; typedef std::vector< ParameterType > InternalParametersType; - typedef Array< double > ParametersType; + typedef Array< double > ParametersType; /** Set the position to initialize the optimization. */ void SetParameters(ParametersType& params) - { m_Parameters = params ; } + { m_Parameters = params; } /** Get current position of the optimization. */ ParametersType& GetParameters() - { return m_Parameters ; } + { return m_Parameters; } /** Set/Get maximum iteration limit. */ itkSetMacro( MaximumIteration, int ); @@ -118,204 +118,203 @@ public: /** Set/Get the pointer to the KdTree */ void SetKdTree(TKdTree* tree) { - m_KdTree = tree ; + m_KdTree = tree; m_MeasurementVectorSize = tree->GetMeasurementVectorSize(); m_DistanceMetric->SetMeasurementVectorSize( m_MeasurementVectorSize ); MeasurementVectorTraits::SetLength( m_TempVertex, m_MeasurementVectorSize ); } TKdTree* GetKdTree() - { return m_KdTree.GetPointer() ; } + { return m_KdTree.GetPointer(); } /** Get the length of measurement vectors in the KdTree */ itkGetConstReferenceMacro( MeasurementVectorSize, MeasurementVectorSizeType ); - itkGetConstReferenceMacro( CurrentIteration, int) ; - itkGetConstReferenceMacro( CentroidPositionChanges, double) ; + itkGetConstReferenceMacro( CurrentIteration, int); + itkGetConstReferenceMacro( CentroidPositionChanges, double); /** Start optimization * Optimization will stop when it meets either of two termination conditions, * the maximum iteration limit or epsilon (minimal changes in squared sum * of changes in centroid positions) */ - void StartOptimization() ; + void StartOptimization(); - typedef itk::hash_map< InstanceIdentifier, unsigned int > ClusterLabelsType ; + typedef itk::hash_map< InstanceIdentifier, unsigned int > ClusterLabelsType; void SetUseClusterLabels(bool flag) - { m_UseClusterLabels = flag ; } + { m_UseClusterLabels = flag; } ClusterLabelsType* GetClusterLabels() - { return &m_ClusterLabels ; } + { return &m_ClusterLabels; } protected: - KdTreeBasedKmeansEstimator() ; + KdTreeBasedKmeansEstimator(); virtual ~KdTreeBasedKmeansEstimator() {} void PrintSelf(std::ostream& os, Indent indent) const; - void FillClusterLabels(KdTreeNodeType* node, int closestIndex) ; + void FillClusterLabels(KdTreeNodeType* node, int closestIndex); - /** vector of k-means candidates */ + /** \class CandidateVector + * vector of k-means candidates */ class CandidateVector - { - public: + { + public: CandidateVector() {} struct Candidate - { - CentroidType Centroid ; - CentroidType WeightedCentroid ; - int Size ; - } ; // end of struct + { + CentroidType Centroid; + CentroidType WeightedCentroid; + int Size; + }; // end of struct virtual ~CandidateVector() {} /** returns the number of candidate = k */ int Size() const - { return static_cast<int>( m_Candidates.size() ); } + { return static_cast<int>( m_Candidates.size() ); } /** Initialize the centroids with the argument. - * At each iteration, this should be called before filtering*/ + * At each iteration, this should be called before filtering */ void SetCentroids(InternalParametersType& centroids) - { + { this->m_MeasurementVectorSize = MeasurementVectorTraits::GetLength( centroids[0] ); - m_Candidates.resize(centroids.size()) ; - for (unsigned int i = 0 ; i < centroids.size() ; i++) + m_Candidates.resize(centroids.size()); + for (unsigned int i = 0; i < centroids.size(); i++) { - Candidate candidate ; - candidate.Centroid = centroids[i] ; - MeasurementVectorTraits::SetLength( candidate.WeightedCentroid, m_MeasurementVectorSize ); - candidate.WeightedCentroid.Fill(0.0) ; - candidate.Size = 0 ; - m_Candidates[i] = candidate ; + Candidate candidate; + candidate.Centroid = centroids[i]; + MeasurementVectorTraits::SetLength( candidate.WeightedCentroid, m_MeasurementVectorSize ); + candidate.WeightedCentroid.Fill(0.0); + candidate.Size = 0; + m_Candidates[i] = candidate; } - } + } /** gets the centroids (k-means) */ void GetCentroids(InternalParametersType& centroids) - { - unsigned int i ; - centroids.resize(this->Size()) ; - for (i = 0 ; i < (unsigned int)this->Size() ; i++) + { + unsigned int i; + centroids.resize(this->Size()); + for (i = 0; i < (unsigned int)this->Size(); i++) { - centroids[i] = m_Candidates[i].Centroid ; + centroids[i] = m_Candidates[i].Centroid; } - } - + } + /** updates the centroids using the vector sum of measurement vectors * that belongs to each centroid and the number of measurement vectors */ void UpdateCentroids() - { - unsigned int i, j ; - for (i = 0 ; i < (unsigned int)this->Size() ; i++) + { + unsigned int i, j; + for (i = 0; i < (unsigned int)this->Size(); i++) { - if (m_Candidates[i].Size > 0) + if (m_Candidates[i].Size > 0) + { + for (j = 0; j < m_MeasurementVectorSize; j++) { - for (j = 0 ; j < m_MeasurementVectorSize; j++) - { - m_Candidates[i].Centroid[j] = - m_Candidates[i].WeightedCentroid[j] / - double(m_Candidates[i].Size) ; - } + m_Candidates[i].Centroid[j] = + m_Candidates[i].WeightedCentroid[j] / + double(m_Candidates[i].Size); } + } } - } - + } + /** gets the index-th candidates */ Candidate& operator[](int index) - { return m_Candidates[index] ; } + { return m_Candidates[index]; } - private: /** internal storage for the candidates */ - std::vector< Candidate > m_Candidates ; + std::vector< Candidate > m_Candidates; /** Length of each measurement vector */ MeasurementVectorSizeType m_MeasurementVectorSize; - } ; // end of class + }; // end of class /** gets the sum of squared difference between the previous position * and current postion of all centroid. This is the primary termination * condition for this algorithm. If the return value is less than * the value that was set by the SetCentroidPositionChangesThreshold - * method.*/ + * method. */ double GetSumOfSquaredPositionChanges(InternalParametersType &previous, - InternalParametersType ¤t) ; + InternalParametersType ¤t); /** get the index of the closest candidate to the "measurements" * measurement vector */ int GetClosestCandidate(ParameterType &measurements, - std::vector< int > &validIndexes) ; + std::vector< int > &validIndexes); - /** returns true if the "pointA is farther than pointB to the boundary */ + /** returns true if the pointA is farther than pointB to the boundary */ bool IsFarther(ParameterType &pointA, ParameterType &pointB, MeasurementVectorType &lowerBound, - MeasurementVectorType &upperBound) ; + MeasurementVectorType &upperBound); /** recursive pruning algorithm. the "validIndexes" vector contains * only the indexes of the surviving candidates for the "node" */ void Filter(KdTreeNodeType* node, std::vector< int > validIndexes, MeasurementVectorType &lowerBound, - MeasurementVectorType &upperBound) ; + MeasurementVectorType &upperBound); /** copies the source parameters (k-means) to the target */ - void CopyParameters(InternalParametersType &source, InternalParametersType &target) ; + void CopyParameters(InternalParametersType &source, InternalParametersType &target); /** copies the source parameters (k-means) to the target */ - void CopyParameters(ParametersType &source, InternalParametersType &target) ; + void CopyParameters(ParametersType &source, InternalParametersType &target); /** copies the source parameters (k-means) to the target */ - void CopyParameters(InternalParametersType &source, ParametersType &target) ; + void CopyParameters(InternalParametersType &source, ParametersType &target); /** imports the "measurements" measurement vector data to the "point" */ - void GetPoint(ParameterType &point, - MeasurementVectorType measurements) - { - for (unsigned int i = 0 ; i < m_MeasurementVectorSize ; i++) + void GetPoint(ParameterType &point, MeasurementVectorType measurements) + { + for (unsigned int i = 0; i < m_MeasurementVectorSize; i++) { - point[i] = measurements[i] ; + point[i] = measurements[i]; } - } + } void PrintPoint(ParameterType &point) - { - std::cout << "[ " ; - for (unsigned int i = 0 ; i < m_MeasurementVectorSize ; i++) + { + std::cout << "[ "; + for (unsigned int i = 0; i < m_MeasurementVectorSize; i++) { - std::cout << point[i] << " " ; + std::cout << point[i] << " "; } - std::cout << "]" ; - } + std::cout << "]"; + } private: /** current number of iteration */ - int m_CurrentIteration ; + int m_CurrentIteration; /** maximum number of iteration. termination criterion */ - int m_MaximumIteration ; + int m_MaximumIteration; /** sum of squared centroid position changes at the current iteration */ - double m_CentroidPositionChanges ; + double m_CentroidPositionChanges; /** threshold for the sum of squared centroid position changes. * termination criterion */ - double m_CentroidPositionChangesThreshold ; + double m_CentroidPositionChangesThreshold; /** pointer to the k-d tree */ - typename TKdTree::Pointer m_KdTree ; + typename TKdTree::Pointer m_KdTree; /** pointer to the euclidean distance funtion */ - typename EuclideanDistance< ParameterType >::Pointer m_DistanceMetric ; + typename EuclideanDistance< ParameterType >::Pointer m_DistanceMetric; /** k-means */ - ParametersType m_Parameters ; + ParametersType m_Parameters; - CandidateVector m_CandidateVector ; + CandidateVector m_CandidateVector; - ParameterType m_TempVertex ; + ParameterType m_TempVertex; - bool m_UseClusterLabels ; - bool m_GenerateClusterLabels ; - ClusterLabelsType m_ClusterLabels ; + bool m_UseClusterLabels; + bool m_GenerateClusterLabels; + ClusterLabelsType m_ClusterLabels; MeasurementVectorSizeType m_MeasurementVectorSize; -} ; // end of class +}; // end of class } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeBasedKmeansEstimator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeBasedKmeansEstimator.txx index 6cfb5b7acb..b5c11a4271 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeBasedKmeansEstimator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeBasedKmeansEstimator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKdTreeBasedKmeansEstimator.txx,v $ Language: C++ - Date: $Date: 2005-09-01 23:06:00 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-03-04 15:23:51 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkKdTreeBasedKmeansEstimator_txx -#define _itkKdTreeBasedKmeansEstimator_txx +#ifndef __itkKdTreeBasedKmeansEstimator_txx +#define __itkKdTreeBasedKmeansEstimator_txx #include "itkKdTreeBasedKmeansEstimator.h" #include "itkStatisticsAlgorithm.h" @@ -27,15 +27,15 @@ template< class TKdTree > KdTreeBasedKmeansEstimator< TKdTree > ::KdTreeBasedKmeansEstimator() { - m_CentroidPositionChangesThreshold = 0.0 ; - m_KdTree = 0 ; - m_UseClusterLabels = false ; - m_MaximumIteration = 100 ; - m_DistanceMetric = EuclideanDistance< ParameterType >::New() ; - - m_CentroidPositionChanges = 0.0 ; - m_TempVertex.Fill( 0.0 ) ; - m_CurrentIteration = 0 ; + m_CentroidPositionChangesThreshold = 0.0; + m_KdTree = 0; + m_UseClusterLabels = false; + m_MaximumIteration = 100; + m_DistanceMetric = EuclideanDistance< ParameterType >::New(); + + m_CentroidPositionChanges = 0.0; + m_TempVertex.Fill( 0.0 ); + m_CurrentIteration = 0; m_MeasurementVectorSize = 0; } @@ -57,20 +57,20 @@ KdTreeBasedKmeansEstimator< TKdTree > os << indent << "Threshold for the Sum of Centroid Position Changes: " << m_CentroidPositionChangesThreshold << std::endl; - os << indent << "Kd Tree:" ; + os << indent << "Kd Tree:"; if ( m_KdTree.IsNotNull() ) { - os << m_KdTree << std::endl ; + os << m_KdTree << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "Distance Metric: " << m_DistanceMetric << std::endl ; - os << indent << "Parameters: " << m_Parameters << std::endl ; - os << indent << "Temp Vertex: " << m_TempVertex << std::endl ; - os << indent << "MeasurementVectorSize: " << m_MeasurementVectorSize << std::endl ; + os << indent << "Distance Metric: " << m_DistanceMetric << std::endl; + os << indent << "Parameters: " << m_Parameters << std::endl; + os << indent << "Temp Vertex: " << m_TempVertex << std::endl; + os << indent << "MeasurementVectorSize: " << m_MeasurementVectorSize << std::endl; } @@ -80,17 +80,17 @@ KdTreeBasedKmeansEstimator< TKdTree > ::GetSumOfSquaredPositionChanges(InternalParametersType &previous, InternalParametersType ¤t) { - double temp ; - double sum = 0.0 ; - unsigned int i ; + double temp; + double sum = 0.0; + unsigned int i; - for (i = 0 ; i < (unsigned int)previous.size() ; i++) + for (i = 0; i < (unsigned int)previous.size(); i++) { - temp = m_DistanceMetric->Evaluate(previous[i], current[i]) ; - sum += temp ; + temp = m_DistanceMetric->Evaluate(previous[i], current[i]); + sum += temp; } - return sum ; + return sum; } template< class TKdTree > @@ -100,23 +100,23 @@ KdTreeBasedKmeansEstimator< TKdTree > std::vector< int > &validIndexes) { - int closest = 0 ; - double closestDistance = NumericTraits< double >::max() ; - double tempDistance ; - std::vector< int >::iterator iter = validIndexes.begin() ; + int closest = 0; + double closestDistance = NumericTraits< double >::max(); + double tempDistance; + std::vector< int >::iterator iter = validIndexes.begin(); while (iter != validIndexes.end()) { tempDistance = m_DistanceMetric->Evaluate(m_CandidateVector[*iter].Centroid, - measurements) ; + measurements); if (tempDistance < closestDistance) { - closest = *iter ; - closestDistance = tempDistance ; + closest = *iter; + closestDistance = tempDistance; } - ++iter ; + ++iter; } - return closest ; + return closest; } template< class TKdTree > @@ -129,25 +129,25 @@ KdTreeBasedKmeansEstimator< TKdTree > { // calculates the vertex of the Cell bounded by the lowerBound // and the upperBound - for (unsigned int i = 0 ; i < m_MeasurementVectorSize ; i++) + for (unsigned int i = 0; i < m_MeasurementVectorSize; i++) { if ((pointA[i] - pointB[i]) < 0.0) { - m_TempVertex[i] = lowerBound[i] ; + m_TempVertex[i] = lowerBound[i]; } else { - m_TempVertex[i] = upperBound[i] ; + m_TempVertex[i] = upperBound[i]; } } if (m_DistanceMetric->Evaluate(pointA, m_TempVertex) >= m_DistanceMetric->Evaluate(pointB, m_TempVertex)) { - return true ; + return true; } - return false ; + return false; } template< class TKdTree > @@ -158,9 +158,9 @@ KdTreeBasedKmeansEstimator< TKdTree > MeasurementVectorType &lowerBound, MeasurementVectorType &upperBound) { - unsigned int i, j ; - typename TKdTree::InstanceIdentifier tempId ; - int closest ; + unsigned int i, j; + typename TKdTree::InstanceIdentifier tempId; + int closest; ParameterType individualPoint; MeasurementVectorTraits::SetLength( individualPoint, this->m_MeasurementVectorSize ); @@ -170,41 +170,41 @@ KdTreeBasedKmeansEstimator< TKdTree > if (node == m_KdTree->GetEmptyTerminalNode()) { // empty node - return ; + return; } - for (i = 0 ; i < (unsigned int)node->Size() ; i++) + for (i = 0; i < (unsigned int)node->Size(); i++) { - tempId = node->GetInstanceIdentifier(i) ; + tempId = node->GetInstanceIdentifier(i); this->GetPoint(individualPoint, - m_KdTree->GetMeasurementVector(tempId)) ; + m_KdTree->GetMeasurementVector(tempId)); closest = - this->GetClosestCandidate(individualPoint, validIndexes) ; - for (j = 0 ; j < m_MeasurementVectorSize ; j++) + this->GetClosestCandidate(individualPoint, validIndexes); + for (j = 0; j < m_MeasurementVectorSize; j++) { m_CandidateVector[closest].WeightedCentroid[j] += - individualPoint[j] ; + individualPoint[j]; } - m_CandidateVector[closest].Size += 1 ; + m_CandidateVector[closest].Size += 1; if ( m_GenerateClusterLabels ) { - m_ClusterLabels[tempId] = closest ; + m_ClusterLabels[tempId] = closest; } } } else { - CentroidType centroid ; - CentroidType weightedCentroid ; + CentroidType centroid; + CentroidType weightedCentroid; ParameterType closestPosition; - node->GetWeightedCentroid(weightedCentroid) ; - node->GetCentroid(centroid) ; + node->GetWeightedCentroid(weightedCentroid); + node->GetCentroid(centroid); closest = - this->GetClosestCandidate(centroid, validIndexes) ; - closestPosition = m_CandidateVector[closest].Centroid ; - std::vector< int >::iterator iter = validIndexes.begin() ; + this->GetClosestCandidate(centroid, validIndexes); + closestPosition = m_CandidateVector[closest].Centroid; + std::vector< int >::iterator iter = validIndexes.begin(); while (iter != validIndexes.end()) { @@ -213,48 +213,48 @@ KdTreeBasedKmeansEstimator< TKdTree > closestPosition, lowerBound, upperBound)) { - iter = validIndexes.erase(iter) ; - continue ; + iter = validIndexes.erase(iter); + continue; } if (iter != validIndexes.end()) { - ++iter ; + ++iter; } } if (validIndexes.size() == 1) { - for (j = 0 ; j < m_MeasurementVectorSize ; j++) + for (j = 0; j < m_MeasurementVectorSize; j++) { m_CandidateVector[closest].WeightedCentroid[j] += - weightedCentroid[j] ; + weightedCentroid[j]; } - m_CandidateVector[closest].Size += node->Size() ; + m_CandidateVector[closest].Size += node->Size(); if ( m_GenerateClusterLabels ) { - this->FillClusterLabels(node, closest) ; + this->FillClusterLabels(node, closest); } } else { - unsigned int partitionDimension ; - MeasurementType partitionValue ; - MeasurementType tempValue ; - node->GetParameters(partitionDimension, partitionValue) ; + unsigned int partitionDimension; + MeasurementType partitionValue; + MeasurementType tempValue; + node->GetParameters(partitionDimension, partitionValue); - tempValue = upperBound[partitionDimension] ; - upperBound[partitionDimension] = partitionValue ; + tempValue = upperBound[partitionDimension]; + upperBound[partitionDimension] = partitionValue; this->Filter(node->Left(), validIndexes, - lowerBound, upperBound) ; - upperBound[partitionDimension] = tempValue ; + lowerBound, upperBound); + upperBound[partitionDimension] = tempValue; - tempValue = lowerBound[partitionDimension] ; - lowerBound[partitionDimension] = partitionValue ; + tempValue = lowerBound[partitionDimension]; + lowerBound[partitionDimension] = partitionValue; this->Filter(node->Right(), validIndexes, - lowerBound, upperBound) ; - lowerBound[partitionDimension] = tempValue ; + lowerBound, upperBound); + lowerBound[partitionDimension] = tempValue; } } } @@ -264,7 +264,7 @@ void KdTreeBasedKmeansEstimator< TKdTree > ::FillClusterLabels(KdTreeNodeType* node, int closestIndex) { - unsigned int i ; + unsigned int i; if ( node->IsTerminal() ) { @@ -272,18 +272,18 @@ KdTreeBasedKmeansEstimator< TKdTree > if (node == m_KdTree->GetEmptyTerminalNode()) { // empty node - return ; + return; } - for (i = 0 ; i < (unsigned int)node->Size() ; i++) + for (i = 0; i < (unsigned int)node->Size(); i++) { - m_ClusterLabels[node->GetInstanceIdentifier(i)] = closestIndex ; + m_ClusterLabels[node->GetInstanceIdentifier(i)] = closestIndex; } } else { - this->FillClusterLabels(node->Left(), closestIndex) ; - this->FillClusterLabels(node->Right(), closestIndex) ; + this->FillClusterLabels(node->Left(), closestIndex); + this->FillClusterLabels(node->Right(), closestIndex); } } @@ -292,14 +292,14 @@ void KdTreeBasedKmeansEstimator< TKdTree > ::CopyParameters(ParametersType &source, InternalParametersType &target) { - unsigned int i, j ; - int index = 0 ; - for (i = 0 ; i < (unsigned int)(source.size() / m_MeasurementVectorSize) ; i++) + unsigned int i, j; + int index = 0; + for (i = 0; i < (unsigned int)(source.size() / m_MeasurementVectorSize); i++) { - for (j = 0 ; j < m_MeasurementVectorSize ; j++) + for (j = 0; j < m_MeasurementVectorSize; j++) { - target[i][j] = source[index] ; - ++index ; + target[i][j] = source[index]; + ++index; } } } @@ -309,14 +309,14 @@ void KdTreeBasedKmeansEstimator< TKdTree > ::CopyParameters(InternalParametersType &source, ParametersType &target) { - unsigned int i, j ; - int index = 0 ; - for (i = 0 ; i < (unsigned int )source.size() ; i++) + unsigned int i, j; + int index = 0; + for (i = 0; i < (unsigned int )source.size(); i++) { - for (j = 0 ; j < m_MeasurementVectorSize ; j++) + for (j = 0; j < m_MeasurementVectorSize; j++) { - target[index] = source[i][j] ; - ++index ; + target[index] = source[i][j]; + ++index; } } } @@ -326,12 +326,12 @@ void KdTreeBasedKmeansEstimator< TKdTree > ::CopyParameters(InternalParametersType &source, InternalParametersType &target) { - unsigned int i, j ; - for (i = 0 ; i < (unsigned int)source.size() ; i++) + unsigned int i, j; + for (i = 0; i < (unsigned int)source.size(); i++) { - for (j = 0 ; j < m_MeasurementVectorSize ; j++) + for (j = 0; j < m_MeasurementVectorSize; j++) { - target[i][j] = source[i][j] ; + target[i][j] = source[i][j]; } } } @@ -341,7 +341,7 @@ void KdTreeBasedKmeansEstimator< TKdTree > ::StartOptimization() { - unsigned int i ; + unsigned int i; MeasurementVectorType lowerBound; MeasurementVectorType upperBound; MeasurementVectorTraits::SetLength( lowerBound, this->m_MeasurementVectorSize ); @@ -351,12 +351,12 @@ KdTreeBasedKmeansEstimator< TKdTree > m_KdTree->GetSample()->Begin(), m_KdTree->GetSample()->End(), lowerBound, - upperBound) ; + upperBound); - InternalParametersType previousPosition ; - //previousPosition.resize(m_Parameters.size() / m_MeasurementVectorSize) ; - InternalParametersType currentPosition ; - //currentPosition.resize(m_Parameters.size() / m_MeasurementVectorSize) ; + InternalParametersType previousPosition; + //previousPosition.resize(m_Parameters.size() / m_MeasurementVectorSize); + InternalParametersType currentPosition; + //currentPosition.resize(m_Parameters.size() / m_MeasurementVectorSize); for( i=0; i< m_Parameters.size()/ m_MeasurementVectorSize; i++ ) @@ -370,67 +370,60 @@ KdTreeBasedKmeansEstimator< TKdTree > } - this->CopyParameters(m_Parameters, currentPosition) ; - m_CurrentIteration = 0 ; - std::vector< int > validIndexes ; + this->CopyParameters(m_Parameters, currentPosition); + m_CurrentIteration = 0; + std::vector< int > validIndexes; - for (i = 0 ; i < (unsigned int)(m_Parameters.size() / m_MeasurementVectorSize) ; i++) + for (i = 0; i < (unsigned int)(m_Parameters.size() / m_MeasurementVectorSize); i++) { - validIndexes.push_back(i) ; + validIndexes.push_back(i); } - m_GenerateClusterLabels = false ; + m_GenerateClusterLabels = false; while(true) { - this->CopyParameters(currentPosition, previousPosition) ; - m_CandidateVector.SetCentroids(currentPosition) ; + this->CopyParameters(currentPosition, previousPosition); + m_CandidateVector.SetCentroids(currentPosition); this->Filter(m_KdTree->GetRoot(), validIndexes, - lowerBound, upperBound) ; - m_CandidateVector.UpdateCentroids() ; - m_CandidateVector.GetCentroids(currentPosition) ; + lowerBound, upperBound); + m_CandidateVector.UpdateCentroids(); + m_CandidateVector.GetCentroids(currentPosition); if(m_CurrentIteration >= m_MaximumIteration) { - break ; + break; } m_CentroidPositionChanges = this->GetSumOfSquaredPositionChanges(previousPosition, - currentPosition) ; + currentPosition); if (m_CentroidPositionChanges <= m_CentroidPositionChangesThreshold) { - break ; + break; } - m_CurrentIteration++ ; + m_CurrentIteration++; } if ( m_UseClusterLabels ) { - m_GenerateClusterLabels = true ; - m_ClusterLabels.clear() ; - m_ClusterLabels.resize(m_KdTree->GetSample()->Size()) ; - for (i = 0 ; i < (unsigned int)(m_Parameters.size() / m_MeasurementVectorSize) ; i++) + m_GenerateClusterLabels = true; + m_ClusterLabels.clear(); + m_ClusterLabels.resize(m_KdTree->GetSample()->Size()); + for (i = 0; i < (unsigned int)(m_Parameters.size() / m_MeasurementVectorSize); i++) { - validIndexes.push_back(i) ; + validIndexes.push_back(i); } this->Filter(m_KdTree->GetRoot(), validIndexes, - lowerBound, upperBound) ; + lowerBound, upperBound); } - this->CopyParameters(currentPosition, m_Parameters) ; + this->CopyParameters(currentPosition, m_Parameters); } } // end of namespace Statistics } // end namespace itk #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeGenerator.h index 1a62d868b3..1a590c8eb5 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKdTreeGenerator.h,v $ Language: C++ - Date: $Date: 2008-04-25 22:36:09 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-04 15:23:51 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -28,8 +28,8 @@ #include "itkKdTree.h" #include "itkStatisticsAlgorithm.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class KdTreeGenerator * \brief This class generates a KdTree object without centroid information. @@ -70,9 +70,9 @@ class ITK_EXPORT KdTreeGenerator : public Object { public: /** Standard class typedefs */ - typedef KdTreeGenerator Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; + typedef KdTreeGenerator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods) */ @@ -83,7 +83,7 @@ public: /** typedef alias for the source data container */ typedef typename TSample::MeasurementVectorType MeasurementVectorType; - typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::MeasurementType MeasurementType; /** Typedef for the length of each measurement vector */ typedef unsigned int MeasurementVectorSizeType; @@ -115,11 +115,11 @@ public: /** Returns the pointer to the generated k-d tree. */ OutputPointer GetOutput() - { return m_Tree; } + { return m_Tree; } /** Runs this k-d tree construction algorithm. */ void Update() - { this->GenerateData(); } + { this->GenerateData(); } /** Runs this k-d tree construction algorithm. */ void GenerateData(); @@ -142,7 +142,7 @@ protected: /** Returns the smart pointer to the internal Subsample object. */ SubsamplePointer GetSubsample() - { return m_Subsample; } + { return m_Subsample; } /** Nonterminal node generation routine */ virtual KdTreeNodeType* GenerateNonterminalNode(unsigned int beginIndex, diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeGenerator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeGenerator.txx index 16cd546837..babbf0fd31 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeGenerator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkKdTreeGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKdTreeGenerator.txx,v $ Language: C++ - Date: $Date: 2008-08-20 13:02:09 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-03-04 15:23:51 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,8 +17,8 @@ #ifndef __itkKdTreeGenerator_txx #define __itkKdTreeGenerator_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > KdTreeGenerator< TSample > diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkListSample.h b/Utilities/ITK/Code/Numerics/Statistics/itkListSample.h index 4a7c66a5de..f1007da592 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkListSample.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkListSample.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkListSample.h,v $ Language: C++ - Date: $Date: 2007-02-16 14:53:28 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-03-04 15:23:51 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,8 +25,8 @@ #include <vector> -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class ListSample * \brief This class is the native implementation of the ListSampleBase @@ -47,33 +47,33 @@ class ITK_EXPORT ListSample : public ListSampleBase< TMeasurementVector > { public: /** Standard class typedef. */ - typedef ListSample Self; + typedef ListSample Self; typedef ListSampleBase< TMeasurementVector > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard macros */ itkTypeMacro(ListSample, ListSampleBase); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** Typedefs inherited from the superclass */ - typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; - typedef typename Superclass::MeasurementType MeasurementType; - typedef typename Superclass::FrequencyType FrequencyType ; - typedef typename Superclass::TotalFrequencyType TotalFrequencyType ; - typedef typename Superclass::InstanceIdentifier InstanceIdentifier; - typedef typename Superclass::SearchResultVectorType SearchResultVectorType ; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::FrequencyType FrequencyType; + typedef typename Superclass::TotalFrequencyType TotalFrequencyType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + typedef typename Superclass::SearchResultVectorType SearchResultVectorType; /** Value type of a measurement (component of the measurement * vector) */ - typedef MeasurementVectorType ValueType ; + typedef MeasurementVectorType ValueType; /** internal data container type */ - typedef std::vector< MeasurementVectorType > InternalDataContainerType ; + typedef std::vector< MeasurementVectorType > InternalDataContainerType; /** Resize the container. If this sample is connected to a Subsample or * MembershipSample, then this function won't change the size of @@ -81,19 +81,19 @@ public: * resize the container before using the sample in a Subsample or * MembershipSample. */ void Resize( unsigned int n ) - { m_InternalContainer.resize(n) ; } + { m_InternalContainer.resize(n); } - /** Removes all the elements in the Sample*/ + /** Removes all the elements in the Sample */ void Clear() - { m_InternalContainer.clear() ; } + { m_InternalContainer.clear(); } /** Inserts a measurement at the end of the list */ void PushBack( MeasurementVectorType mv ) - { m_InternalContainer.push_back( mv ) ; } + { m_InternalContainer.push_back( mv ); } - /** Get the number of measurement vectors in the sample*/ + /** Get the number of measurement vectors in the sample */ unsigned int Size() const - { return static_cast<unsigned int>( m_InternalContainer.size() ); } + { return static_cast<unsigned int>( m_InternalContainer.size() ); } /** Get the measurement associated with the specified * InstanceIdentifier */ @@ -102,25 +102,25 @@ public: /** Set a component a measurement to a particular value. */ void SetMeasurement(const InstanceIdentifier &id, const unsigned int &dim, - const MeasurementType &value) ; + const MeasurementType &value); /** Replace a measurement with a different measurement */ void SetMeasurementVector(const InstanceIdentifier &id, - const MeasurementVectorType &mv) ; + const MeasurementVectorType &mv); /** Get the frequency of a measurement. Returns 1 if the measurement * exist. */ - FrequencyType GetFrequency(const InstanceIdentifier &id) const ; + FrequencyType GetFrequency(const InstanceIdentifier &id) const; /** Get the total frequency of the sample. This is equivalent to * the size of the sample. */ TotalFrequencyType GetTotalFrequency() const - { return static_cast<TotalFrequencyType>( m_InternalContainer.size() ); } + { return static_cast<TotalFrequencyType>( m_InternalContainer.size() ); } class ConstIterator; class Iterator - { + { friend class ConstIterator; @@ -130,164 +130,161 @@ public: Iterator(typename InternalDataContainerType::iterator iter, InstanceIdentifier iid) - :m_Iter(iter), m_InstanceIdentifier(iid) - {} + :m_Iter(iter), m_InstanceIdentifier(iid) {} FrequencyType GetFrequency() const - { return 1 ;} + { return 1;} const MeasurementVectorType & GetMeasurementVector() const - { return (MeasurementVectorType&) *m_Iter ;} + { return (MeasurementVectorType&) *m_Iter;} InstanceIdentifier GetInstanceIdentifier() const - { return m_InstanceIdentifier ;} + { return m_InstanceIdentifier;} Iterator& operator++() - { + { ++m_Iter; ++m_InstanceIdentifier; return *this; - } + } Iterator& operator--() - { - --m_Iter ; + { + --m_Iter; --m_InstanceIdentifier; - return *this ; - } + return *this; + } bool operator!=(const Iterator &it) - { + { return (m_Iter != it.m_Iter); - } + } bool operator==(const Iterator &it) - { + { return (m_Iter == it.m_Iter); - } + } Iterator& operator =(const Iterator & iter) - { + { m_Iter = iter.m_Iter; - m_InstanceIdentifier = iter.m_InstanceIdentifier ; - return *this ; - } + m_InstanceIdentifier = iter.m_InstanceIdentifier; + return *this; + } Iterator(const Iterator &iter) - { + { m_Iter = iter.m_Iter; - m_InstanceIdentifier = iter.m_InstanceIdentifier ; - } + m_InstanceIdentifier = iter.m_InstanceIdentifier; + } private: - typename InternalDataContainerType::iterator m_Iter ; - InstanceIdentifier m_InstanceIdentifier ; - } ; + typename InternalDataContainerType::iterator m_Iter; + InstanceIdentifier m_InstanceIdentifier; + }; class ConstIterator - { - public: + { + public: ConstIterator(){} ConstIterator(typename InternalDataContainerType::const_iterator iter, InstanceIdentifier iid) - :m_Iter(iter), m_InstanceIdentifier(iid) - {} + :m_Iter(iter), m_InstanceIdentifier(iid) {} FrequencyType GetFrequency() const - { return 1 ;} + { return 1;} const MeasurementVectorType & GetMeasurementVector() const - { return static_cast<const MeasurementVectorType&>(*m_Iter) ;} + { return static_cast<const MeasurementVectorType&>(*m_Iter);} InstanceIdentifier GetInstanceIdentifier() const - { return m_InstanceIdentifier ;} + { return m_InstanceIdentifier;} ConstIterator& operator++() - { + { ++m_Iter; ++m_InstanceIdentifier; return *this; - } + } ConstIterator& operator--() - { + { --m_Iter; --m_InstanceIdentifier; - return *this ; - } + return *this; + } bool operator!=(const ConstIterator &it) - { + { return (m_Iter != it.m_Iter); - } + } bool operator==(const ConstIterator &it) - { + { return (m_Iter == it.m_Iter); - } + } ConstIterator& operator = (const ConstIterator iter) - { + { m_Iter = iter.m_Iter; - m_InstanceIdentifier = iter.m_InstanceIdentifier ; - return *this ; - } + m_InstanceIdentifier = iter.m_InstanceIdentifier; + return *this; + } ConstIterator& operator = (const Iterator & iter) - { + { m_Iter = iter.m_Iter; - m_InstanceIdentifier = iter.m_InstanceIdentifier ; - return *this ; - } - + m_InstanceIdentifier = iter.m_InstanceIdentifier; + return *this; + } ConstIterator(const ConstIterator &iter) - { + { m_Iter = iter.m_Iter; - m_InstanceIdentifier = iter.m_InstanceIdentifier ; - } + m_InstanceIdentifier = iter.m_InstanceIdentifier; + } ConstIterator(const Iterator &iter) - { + { m_Iter = iter.m_Iter; - m_InstanceIdentifier = iter.m_InstanceIdentifier ; - } + m_InstanceIdentifier = iter.m_InstanceIdentifier; + } private: - typename InternalDataContainerType::const_iterator m_Iter ; - InstanceIdentifier m_InstanceIdentifier ; - } ; + typename InternalDataContainerType::const_iterator m_Iter; + InstanceIdentifier m_InstanceIdentifier; + }; /** returns an iterator that points to the beginning of the container */ Iterator Begin() - { + { Iterator iter(m_InternalContainer.begin(), 0); return iter; - } + } /** returns an iterator that points to the end of the container */ - Iterator End() - { + Iterator End() + { Iterator iter(m_InternalContainer.end(), m_InternalContainer.size()); return iter; - } + } /** returns an iterator that points to the beginning of the container */ ConstIterator Begin() const - { + { ConstIterator iter(m_InternalContainer.begin(), 0); return iter; - } + } /** returns an iterator that points to the end of the container */ ConstIterator End() const - { + { ConstIterator iter(m_InternalContainer.end(), m_InternalContainer.size()); return iter; - } + } virtual MeasurementVectorSizeType GetMeasurementVectorSize() const { @@ -300,16 +297,16 @@ public: } protected: - ListSample() ; + ListSample(); virtual ~ListSample() {} void PrintSelf(std::ostream& os, Indent indent) const; private: - ListSample(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + ListSample(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - InternalDataContainerType m_InternalContainer ; + InternalDataContainerType m_InternalContainer; }; diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkListSample.txx b/Utilities/ITK/Code/Numerics/Statistics/itkListSample.txx index 11a01b2698..ef57cb2696 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkListSample.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkListSample.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkListSample.txx,v $ Language: C++ - Date: $Date: 2008-04-28 00:21:00 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-04 15:23:53 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkListSample.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TMeasurementVector > ListSample< TMeasurementVector > @@ -36,7 +36,7 @@ ListSample< TMeasurementVector > { if ( identifier < m_InternalContainer.size() ) { - return m_InternalContainer[identifier] ; + return m_InternalContainer[identifier]; } itkExceptionMacro("Identifier " << identifier << " is out of range 0:" << m_InternalContainer.size() ); @@ -51,7 +51,7 @@ ListSample< TMeasurementVector > { if ( identifier < m_InternalContainer.size() ) { - m_InternalContainer[identifier][dim] = value ; + m_InternalContainer[identifier][dim] = value; } } @@ -63,7 +63,7 @@ ListSample< TMeasurementVector > { if ( identifier < m_InternalContainer.size() ) { - m_InternalContainer[identifier] = mv ; + m_InternalContainer[identifier] = mv; } } @@ -74,11 +74,11 @@ ListSample< TMeasurementVector > { if ( identifier < m_InternalContainer.size() ) { - return 1.0 ; + return 1.0; } else { - return 0.0 ; + return 0.0; } } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleBase.h b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleBase.h index 9c4a0227e1..35c13a3cb8 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleBase.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkListSampleBase.h,v $ Language: C++ - Date: $Date: 2007-08-17 18:05:08 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-04 15:23:53 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include <vector> -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class ListSampleBase * \brief This class is the base class for Samples that store measurements in a list @@ -49,68 +49,68 @@ class ITK_EXPORT ListSampleBase : public Sample< TMeasurementVector > { public: /** Standard class typedef. */ - typedef ListSampleBase Self; + typedef ListSampleBase Self; typedef Sample< TMeasurementVector > Superclass; /** Standard macros */ itkTypeMacro(ListSampleBase, Sample); /** Typedefs inherited from the superclass */ - typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; - typedef typename Superclass::MeasurementType MeasurementType; - typedef typename Superclass::FrequencyType FrequencyType ; - typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::FrequencyType FrequencyType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; /** Vector of InstanceIdentifiers used for returning search * results. */ - typedef std::vector< InstanceIdentifier > SearchResultVectorType ; + typedef std::vector< InstanceIdentifier > SearchResultVectorType; /** Search for measurements within the specified radius of a search * point. A vector of InstanceIdentifiers is returned. */ inline void Search(MeasurementVectorType center, double radius, SearchResultVectorType& result) const - { + { if (radius == 0.0) { - itkGenericExceptionMacro("Search radius should be greater than zero.") ; + itkGenericExceptionMacro("Search radius should be greater than zero."); } - unsigned int j ; - double squaredRadius ; - double distance ; - double coordinateDistance ; + unsigned int j; + double squaredRadius; + double distance; + double coordinateDistance; - MeasurementVectorType tempVector ; + MeasurementVectorType tempVector; - squaredRadius = radius * radius ; + squaredRadius = radius * radius; - result.clear() ; - for ( InstanceIdentifier identifier = 0 ; identifier < this->Size() ; ++identifier ) + result.clear(); + for ( InstanceIdentifier identifier = 0; identifier < this->Size(); ++identifier ) { - distance = 0.0 ; - tempVector = this->GetMeasurementVector( identifier ) ; - for (j = 0 ; j < this->GetMeasurementVectorSize() && distance < squaredRadius ; j++) + distance = 0.0; + tempVector = this->GetMeasurementVector( identifier ); + for (j = 0; j < this->GetMeasurementVectorSize() && distance < squaredRadius; j++) { - coordinateDistance = (double)tempVector[j] - center[j] ; + coordinateDistance = (double)tempVector[j] - center[j]; if (vnl_math_abs(coordinateDistance) > radius ) { - distance = squaredRadius ; + distance = squaredRadius; } } - for (j = 0 ; j < this->GetMeasurementVectorSize() && distance < squaredRadius ; j++) + for (j = 0; j < this->GetMeasurementVectorSize() && distance < squaredRadius; j++) { - coordinateDistance = (double)tempVector[j] - center[j] ; - distance += coordinateDistance * coordinateDistance ; + coordinateDistance = (double)tempVector[j] - center[j]; + distance += coordinateDistance * coordinateDistance; } if (distance < squaredRadius) { - result.push_back( identifier ) ; + result.push_back( identifier ); } } - } + } protected: ListSampleBase() {} @@ -122,8 +122,8 @@ protected: private: - ListSampleBase(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + ListSampleBase(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented }; diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramFilter.h index ca916a1f53..b9e341caa5 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkListSampleToHistogramFilter.h,v $ Language: C++ - Date: $Date: 2007-09-27 15:45:40 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 15:23:53 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include "itkListSampleBase.h" #include "itkHistogram.h" -namespace itk{ - namespace Statistics{ +namespace itk { +namespace Statistics { /** \class ListSampleToHistogramFilter * \brief Imports data from ListSample object to Histogram object @@ -40,40 +40,40 @@ class ITK_EXPORT ListSampleToHistogramFilter : public: /** Standard typedefs */ typedef ListSampleToHistogramFilter Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(ListSampleToHistogramFilter, Object) ; + itkTypeMacro(ListSampleToHistogramFilter, Object); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** plug in the ListSample object */ void SetListSample(const TListSample* list) - { m_List = list ; } + { m_List = list; } /** plug in the Histogram object */ void SetHistogram(THistogram* histogram) - { m_Histogram = histogram ; } + { m_Histogram = histogram; } /** starts import procedure */ void Update() - { this->Run() ; } + { this->Run(); } /** starts import procedure */ - void Run() ; + void Run(); protected: - ListSampleToHistogramFilter() ; + ListSampleToHistogramFilter(); virtual ~ListSampleToHistogramFilter() {} private: - const TListSample* m_List ; - THistogram* m_Histogram ; -} ; // end of class + const TListSample* m_List; + THistogram* m_Histogram; +}; // end of class - } // end of namespace Statistics +} // end of namespace Statistics } // end of namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramFilter.txx b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramFilter.txx index 974e920d7f..1d50afb23d 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramFilter.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkListSampleToHistogramFilter.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:59 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-03-04 15:23:55 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkListSampleToHistogramFilter.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TListSample, class THistogram > ListSampleToHistogramFilter< TListSample, THistogram > @@ -33,11 +33,11 @@ void ListSampleToHistogramFilter< TListSample, THistogram > ::Run() { - typename TListSample::ConstIterator iter = m_List->Begin() ; - typename TListSample::ConstIterator last = m_List->End() ; - typename THistogram::IndexType index ; - typename TListSample::MeasurementVectorType lvector ; - typename THistogram::MeasurementVectorType hvector ; + typename TListSample::ConstIterator iter = m_List->Begin(); + typename TListSample::ConstIterator last = m_List->End(); + typename THistogram::IndexType index; + typename TListSample::MeasurementVectorType lvector; + typename THistogram::MeasurementVectorType hvector; // Sanity check to see if lengths of the vector passed in and the // histogram's MV lengths are the same @@ -48,14 +48,14 @@ ListSampleToHistogramFilter< TListSample, THistogram > THistogram::MeasurementVectorSize); } - unsigned int i ; + unsigned int i; while (iter != last) { - lvector = iter.GetMeasurementVector() ; - for ( i = 0 ; i < THistogram::MeasurementVectorSize ; i++) + lvector = iter.GetMeasurementVector(); + for ( i = 0; i < THistogram::MeasurementVectorSize; i++) { hvector[i] = - (typename THistogram::MeasurementType) lvector[i] ; + (typename THistogram::MeasurementType) lvector[i]; } m_Histogram->GetIndex(hvector,index); @@ -64,10 +64,10 @@ ListSampleToHistogramFilter< TListSample, THistogram > // if the measurement vector is out of bound then // the GetIndex method returns index with the sizes of each dimension // and doesn't increase the frequency - // id = m_Histogram->GetInstanceIdentifier(index) ; - m_Histogram->IncreaseFrequency(index, 1) ; + // id = m_Histogram->GetInstanceIdentifier(index); + m_Histogram->IncreaseFrequency(index, 1); } - ++iter ; + ++iter; } } @@ -75,5 +75,3 @@ ListSampleToHistogramFilter< TListSample, THistogram > } // end of namespace itk #endif - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.h index f8809a6031..fa20b5de41 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkListSampleToHistogramGenerator.h,v $ Language: C++ - Date: $Date: 2006-03-14 22:52:18 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-03-04 15:23:55 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,8 +24,8 @@ #include "itkDenseFrequencyContainer.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class ListSampleToHistogramGenerator * \brief Generates a Histogram using the data from the ListSample object @@ -74,15 +74,15 @@ class ITK_EXPORT ListSampleToHistogramGenerator : public: /** Standard typedefs */ typedef ListSampleToHistogramGenerator Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(ListSampleToHistogramGenerator, Object) ; + itkTypeMacro(ListSampleToHistogramGenerator, Object); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** the number of components in a measurement vector */ itkStaticConstMacro(MeasurementVectorSize, unsigned int, @@ -94,9 +94,9 @@ public: typedef Histogram< HistogramMeasurementRealType, itkGetStaticConstMacro(MeasurementVectorSize), - TFrequencyContainer > HistogramType ; + TFrequencyContainer > HistogramType; - typedef typename HistogramType::SizeType HistogramSizeType ; + typedef typename HistogramType::SizeType HistogramSizeType; typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; /** plug in the ListSample object */ @@ -110,20 +110,20 @@ public: << list->GetMeasurementVectorSize() << " but histogram dimension is " << MeasurementVectorSize); } - m_List = list ; + m_List = list; } void SetMarginalScale(float scale) - { m_MarginalScale = scale ; } + { m_MarginalScale = scale; } void SetNumberOfBins(HistogramSizeType sizes) - { m_Sizes = sizes ; } + { m_Sizes = sizes; } const HistogramType* GetOutput() const - { return m_Histogram ; } + { return m_Histogram; } void Update() - { this->GenerateData() ; } + { this->GenerateData(); } itkSetMacro(AutoMinMax,bool); itkGetConstReferenceMacro(AutoMinMax,bool); @@ -170,21 +170,21 @@ public: protected: - ListSampleToHistogramGenerator() ; + ListSampleToHistogramGenerator(); virtual ~ListSampleToHistogramGenerator() {} - void GenerateData() ; + void GenerateData(); void PrintSelf(std::ostream& os, Indent indent) const; private: - const TListSample* m_List ; - typename HistogramType::Pointer m_Histogram ; - HistogramSizeType m_Sizes ; - float m_MarginalScale ; - MeasurementVectorType m_HistogramMin; - MeasurementVectorType m_HistogramMax; - bool m_AutoMinMax; - -} ; // end of class + const TListSample* m_List; + typename HistogramType::Pointer m_Histogram; + HistogramSizeType m_Sizes; + float m_MarginalScale; + MeasurementVectorType m_HistogramMin; + MeasurementVectorType m_HistogramMax; + bool m_AutoMinMax; + +}; // end of class } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.txx index 04f9d4e64f..9f93bf48da 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkListSampleToHistogramGenerator.txx,v $ Language: C++ - Date: $Date: 2007-04-24 14:15:25 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-04 15:23:55 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include <exception> -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TListSample, class THistogramMeasurement, @@ -32,9 +32,9 @@ ListSampleToHistogramGenerator< TListSample, TMeasurementVectorLength > ::ListSampleToHistogramGenerator() { - m_Sizes.Fill(0) ; - m_Histogram = HistogramType::New() ; - m_MarginalScale = 100 ; + m_Sizes.Fill(0); + m_Histogram = HistogramType::New(); + m_MarginalScale = 100; m_HistogramMin.Fill(0); m_HistogramMax.Fill(0); m_AutoMinMax = true; @@ -64,19 +64,19 @@ ListSampleToHistogramGenerator< TListSample, if( m_AutoMinMax && m_List->Size() != 0 ) { FindSampleBound(m_List, m_List->Begin(), - m_List->End(), lower, upper) ; + m_List->End(), lower, upper); - float margin ; + float margin; - for ( unsigned int i = 0 ; i < MeasurementVectorSize ; i++ ) + for ( unsigned int i = 0; i < MeasurementVectorSize; i++ ) { if ( !NumericTraits< THistogramMeasurement >::is_integer ) { margin = ( (THistogramMeasurement)(upper[i] - lower[i]) / (THistogramMeasurement) m_Sizes[i] ) / - (THistogramMeasurement) m_MarginalScale ; - h_upper[i] = (THistogramMeasurement) (upper[i] + margin) ; + (THistogramMeasurement) m_MarginalScale; + h_upper[i] = (THistogramMeasurement) (upper[i] + margin); if(h_upper[i] <= upper[i]) { // an overflow has occurred therefore set upper to upper @@ -91,7 +91,7 @@ ListSampleToHistogramGenerator< TListSample, else { h_upper[i] = ((THistogramMeasurement) upper[i]) + - NumericTraits< THistogramMeasurement >::One ; + NumericTraits< THistogramMeasurement >::One; if(h_upper[i] <= upper[i]) { // an overflow has occurred therefore set upper to upper @@ -103,26 +103,26 @@ ListSampleToHistogramGenerator< TListSample, // computation and clearly the user intended to include min and max. } } - h_lower[i] = ( THistogramMeasurement) lower[i] ; + h_lower[i] = ( THistogramMeasurement) lower[i]; } } // initialize the Histogram object using the sizes and // the upper and lower bound from the FindSampleBound function - m_Histogram->Initialize(m_Sizes, h_lower, h_upper) ; + m_Histogram->Initialize(m_Sizes, h_lower, h_upper); - typename TListSample::ConstIterator iter = m_List->Begin() ; - typename TListSample::ConstIterator last = m_List->End() ; - typename HistogramType::IndexType index ; - typename TListSample::MeasurementVectorType lvector ; - typename HistogramType::MeasurementVectorType hvector ; + typename TListSample::ConstIterator iter = m_List->Begin(); + typename TListSample::ConstIterator last = m_List->End(); + typename HistogramType::IndexType index; + typename TListSample::MeasurementVectorType lvector; + typename HistogramType::MeasurementVectorType hvector; unsigned int i; while (iter != last) { - lvector = iter.GetMeasurementVector() ; - for ( i = 0 ; i < HistogramType::MeasurementVectorSize ; i++) + lvector = iter.GetMeasurementVector(); + for ( i = 0; i < HistogramType::MeasurementVectorSize; i++) { - hvector[i] = (THistogramMeasurement) lvector[i] ; + hvector[i] = (THistogramMeasurement) lvector[i]; } m_Histogram->GetIndex(hvector,index); @@ -134,9 +134,9 @@ ListSampleToHistogramGenerator< TListSample, // bin value. // If the index isn't valid, we don't increase the frequency. // See the comments in Histogram->GetIndex() for more info. - m_Histogram->IncreaseFrequency(index, 1) ; + m_Histogram->IncreaseFrequency(index, 1); } - ++iter ; + ++iter; } } @@ -163,5 +163,3 @@ ListSampleToHistogramGenerator< TListSample, } // end of namespace itk #endif - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkLogLikelihoodGoodnessOfFitFunction.h b/Utilities/ITK/Code/Numerics/Statistics/itkLogLikelihoodGoodnessOfFitFunction.h index 88e321829e..8f3a34aa14 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkLogLikelihoodGoodnessOfFitFunction.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkLogLikelihoodGoodnessOfFitFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLogLikelihoodGoodnessOfFitFunction.h,v $ Language: C++ - Date: $Date: 2008-10-24 08:14:13 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-04 15:23:56 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkGoodnessOfFitFunctionBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class LogLikelihoodGoodnessOfFitFunction * \brief calculates loglikelihood ratio statistics @@ -44,34 +44,34 @@ class LogLikelihoodGoodnessOfFitFunction { public: /** Standard class typedefs */ - typedef LogLikelihoodGoodnessOfFitFunction Self; + typedef LogLikelihoodGoodnessOfFitFunction Self; typedef GoodnessOfFitFunctionBase< TInputHistogram > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer< const Self > ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(LogLikelihoodGoodnessOfFitFunction, - GoodnessOfFitFunctionBase) ; + GoodnessOfFitFunctionBase); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** typedefs from InputHistogram */ itkStaticConstMacro(MeasurementVectorSize, unsigned int, - TInputHistogram::MeasurementVectorSize) ; - typedef typename TInputHistogram::MeasurementType MeasurementType ; - typedef typename TInputHistogram::MeasurementVectorType MeasurementVectorType ; + TInputHistogram::MeasurementVectorSize); + typedef typename TInputHistogram::MeasurementType MeasurementType; + typedef typename TInputHistogram::MeasurementVectorType MeasurementVectorType; protected: - LogLikelihoodGoodnessOfFitFunction() ; - virtual ~LogLikelihoodGoodnessOfFitFunction(){} ; + LogLikelihoodGoodnessOfFitFunction(); + virtual ~LogLikelihoodGoodnessOfFitFunction(){}; /** calculates the loglikelihood ratio statistics */ - virtual void GenerateData() ; + virtual void GenerateData(); private: - bool m_Initialized ; -} ; // end of class + bool m_Initialized; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -81,4 +81,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkLogLikelihoodGoodnessOfFitFunction.txx b/Utilities/ITK/Code/Numerics/Statistics/itkLogLikelihoodGoodnessOfFitFunction.txx index 616955dd2d..888a5839d5 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkLogLikelihoodGoodnessOfFitFunction.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkLogLikelihoodGoodnessOfFitFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLogLikelihoodGoodnessOfFitFunction.txx,v $ Language: C++ - Date: $Date: 2006-03-19 04:37:20 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 15:23:56 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,15 +19,15 @@ #include "itkLogLikelihoodGoodnessOfFitFunction.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TInputHistogram > LogLikelihoodGoodnessOfFitFunction< TInputHistogram > ::LogLikelihoodGoodnessOfFitFunction() { - this->SetUseExpectedHistogram(true) ; - m_Initialized = false ; + this->SetUseExpectedHistogram(true); + m_Initialized = false; } template< class TInputHistogram > @@ -35,20 +35,20 @@ void LogLikelihoodGoodnessOfFitFunction< TInputHistogram > ::GenerateData() { - const TInputHistogram* observedHistogram = this->GetObservedHistogram() ; - const TInputHistogram* expectedHistogram = this->GetExpectedHistogram() ; + const TInputHistogram* observedHistogram = this->GetObservedHistogram(); + const TInputHistogram* expectedHistogram = this->GetExpectedHistogram(); - float p, px, sum = 0.0f ; + float p, px, sum = 0.0f; double ratio; - typename TInputHistogram::ConstIterator e_iter = expectedHistogram->Begin() ; - typename TInputHistogram::ConstIterator e_last = expectedHistogram->End() ; - typename TInputHistogram::ConstIterator o_iter = observedHistogram->Begin() ; + typename TInputHistogram::ConstIterator e_iter = expectedHistogram->Begin(); + typename TInputHistogram::ConstIterator e_last = expectedHistogram->End(); + typename TInputHistogram::ConstIterator o_iter = observedHistogram->Begin(); while ( e_iter != e_last ) { - p = e_iter.GetFrequency() ; - px = o_iter.GetFrequency() ; + p = e_iter.GetFrequency(); + px = o_iter.GetFrequency(); - ratio = px / p ; + ratio = px / p; if ( ratio > this->GetEpsilon() && px > 0 ) { @@ -56,18 +56,17 @@ LogLikelihoodGoodnessOfFitFunction< TInputHistogram > } else { - sum += px * this->GetLogEpsilon() ; + sum += px * this->GetLogEpsilon(); } - ++e_iter ; - ++o_iter ; + ++e_iter; + ++o_iter; } sum *= 2.0; - this->GetOutput() = sum ; + this->GetOutput() = sum; } } // end of namespace Statistics } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMahalanobisDistanceMembershipFunction.h b/Utilities/ITK/Code/Numerics/Statistics/itkMahalanobisDistanceMembershipFunction.h index b19052d1a3..1468b4d111 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMahalanobisDistanceMembershipFunction.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMahalanobisDistanceMembershipFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMahalanobisDistanceMembershipFunction.h,v $ Language: C++ - Date: $Date: 2005-11-21 02:40:48 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-03-04 15:23:56 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -28,8 +28,8 @@ #include "itkMembershipFunctionBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class MahalanobisDistanceMembershipFunction * \brief MahalanobisDistanceMembershipFunction class represents MahalanobisDistance Density Function. @@ -47,16 +47,16 @@ class ITK_EXPORT MahalanobisDistanceMembershipFunction : public: /** Standard class typedefs */ typedef MahalanobisDistanceMembershipFunction Self; - typedef MembershipFunctionBase< TVector > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef MembershipFunctionBase< TVector > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Strandard macros */ itkTypeMacro(MahalanobisDistanceMembershipFunction, MembershipFunctionBase); itkNewMacro(Self); /** Typedef alias for the measurement vectors */ - typedef TVector MeasurementVectorType ; + typedef TVector MeasurementVectorType; /** Typedef to represent the length of measurement vectors */ typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; @@ -71,8 +71,8 @@ public: virtual void SetMeasurementVectorSize( const MeasurementVectorSizeType ); /** Method to set mean */ - void SetMean(const MeanVectorType &mean) ; - void SetMean(const Array< double > &mean) ; + void SetMean(const MeanVectorType &mean); + void SetMean(const Array< double > &mean); /** Method to get mean */ const MeanVectorType & GetMean() const; @@ -107,7 +107,7 @@ public: double Evaluate(const MeasurementVectorType &measurement) const; protected: - MahalanobisDistanceMembershipFunction(void) ; + MahalanobisDistanceMembershipFunction(void); virtual ~MahalanobisDistanceMembershipFunction(void) {} void PrintSelf(std::ostream& os, Indent indent) const; diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMahalanobisDistanceMembershipFunction.txx b/Utilities/ITK/Code/Numerics/Statistics/itkMahalanobisDistanceMembershipFunction.txx index 631b490a02..f018120499 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMahalanobisDistanceMembershipFunction.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMahalanobisDistanceMembershipFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMahalanobisDistanceMembershipFunction.txx,v $ Language: C++ - Date: $Date: 2008-01-15 12:37:56 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-04 15:23:57 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkMahalanobisDistanceMembershipFunction.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template < class TVector > MahalanobisDistanceMembershipFunction< TVector > @@ -73,7 +73,7 @@ MahalanobisDistanceMembershipFunction< TVector > this->m_MeasurementVectorSize = mean.size(); } - m_Mean = mean ; + m_Mean = mean; } @@ -105,7 +105,7 @@ MahalanobisDistanceMembershipFunction< TVector >::MeanVectorType & MahalanobisDistanceMembershipFunction< TVector > ::GetMean() const { - return m_Mean ; + return m_Mean; } template < class TVector > @@ -131,8 +131,6 @@ MahalanobisDistanceMembershipFunction< TVector > this->CalculateInverseCovariance(); } - - template < class TVector > void MahalanobisDistanceMembershipFunction< TVector > @@ -159,8 +157,6 @@ MahalanobisDistanceMembershipFunction< TVector > m_InverseCovariance = invcov; } - - template < class TVector > void MahalanobisDistanceMembershipFunction< TVector > @@ -223,7 +219,7 @@ MahalanobisDistanceMembershipFunction< TVector > // Compute |y - mean | * inverse(cov) * |y - mean|^T temp = dot_product( m_TempMat.as_ref(), m_TempVec.as_ref() ); - return temp ; + return temp; } template < class TVector > @@ -231,14 +227,14 @@ void MahalanobisDistanceMembershipFunction< TVector > ::PrintSelf(std::ostream& os, Indent indent) const { - unsigned int i ; + unsigned int i; Superclass::PrintSelf(os,indent); if ( this->m_MeasurementVectorSize && m_Mean.size() == this->m_MeasurementVectorSize ) { - os << indent << "Mean: [" ; - for (i=0 ; (i + 1) < this->m_MeasurementVectorSize; i++) + os << indent << "Mean: ["; + for (i=0; (i + 1) < this->m_MeasurementVectorSize; i++) { os << m_Mean[i] << ", "; } @@ -246,7 +242,7 @@ MahalanobisDistanceMembershipFunction< TVector > } else { - os << indent << "Mean: not set or size does not match" << std::endl ; + os << indent << "Mean: not set or size does not match" << std::endl; } os << indent << "Number of Samples: " << m_NumberOfSamples << std::endl; @@ -258,6 +254,4 @@ MahalanobisDistanceMembershipFunction< TVector > } // end namespace Statistics } // end of namespace itk - - #endif diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.h index 8f004abbd9..be71a88a98 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.h,v $ Language: C++ - Date: $Date: 2005-08-24 15:16:50 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-20 16:21:47 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,94 +21,96 @@ #include "itkMacro.h" namespace itk { - namespace Statistics { +namespace Statistics { /** \class MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator -* \brief This class computes a grey-level co-occurence matrix (histogram) from -* a given image and mask. GLCM's are used for image texture description. -* -* For details about the general method, see the documentation for the -* ScalarImageToGreyLevelCooccurrenceMatrixGenerator class. -* -* This class differs in that a mask may be set. The GLCM will only be populated -* with co-occurence measurements where both the pixel in question and the -* offset pixel both fall in the masked region. The mask must be the same size -* as the input image. -* -* If no mask is set, the behavior is exactly the same as the -* ScalarImageToGreyLevelCooccurrenceMatrixGenerator class. -* -* \sa ScalarImageToGreyLevelCooccurrenceMatrixGenerator -* \sa GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator -* \sa ScalarImageTextureCalculator -* -* Author: Zachary Pincus -*/ + * \brief This class computes a grey-level co-occurence matrix (histogram) from + * a given image and mask. GLCM's are used for image texture description. + * + * For details about the general method, see the documentation for the + * ScalarImageToGreyLevelCooccurrenceMatrixGenerator class. + * + * This class differs in that a mask may be set. The GLCM will only be populated + * with co-occurence measurements where both the pixel in question and the + * offset pixel both fall in the masked region. The mask must be the same size + * as the input image. + * + * If no mask is set, the behavior is exactly the same as the + * ScalarImageToGreyLevelCooccurrenceMatrixGenerator class. + * + * \sa ScalarImageToGreyLevelCooccurrenceMatrixGenerator + * \sa GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator + * \sa ScalarImageTextureCalculator + * + * Author: Zachary Pincus + */ template< class TImageType, class THistogramFrequencyContainer = DenseFrequencyContainer > class MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator : public ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, THistogramFrequencyContainer > - { - public: - /** Standard typedefs */ - typedef MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator Self; - typedef ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; +{ +public: + /** Standard typedefs */ + typedef MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator Self; + typedef ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; - /** Run-time type information (and related methods). */ - itkTypeMacro(MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator, Object); + /** Run-time type information (and related methods). */ + itkTypeMacro(MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator, Object); - /** standard New() method support */ - itkNewMacro(Self) ; + /** standard New() method support */ + itkNewMacro(Self); - typedef TImageType ImageType; - typedef typename ImageType::Pointer ImagePointer; - typedef typename ImageType::ConstPointer ImageConstPointer; - typedef typename ImageType::PixelType PixelType; - typedef typename ImageType::RegionType RegionType; - typedef typename ImageType::SizeType RadiusType; - typedef typename ImageType::OffsetType OffsetType; - typedef VectorContainer<unsigned char, OffsetType> OffsetVector; - typedef typename OffsetVector::Pointer OffsetVectorPointer; - typedef typename OffsetVector::ConstPointer OffsetVectorConstPointer; + typedef TImageType ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::RegionType RegionType; + typedef typename ImageType::SizeType RadiusType; + typedef typename ImageType::OffsetType OffsetType; + typedef VectorContainer<unsigned char, OffsetType> OffsetVector; + typedef typename OffsetVector::Pointer OffsetVectorPointer; + typedef typename OffsetVector::ConstPointer OffsetVectorConstPointer; - typedef typename NumericTraits<PixelType>::RealType MeasurementType; + typedef typename NumericTraits<PixelType>::RealType MeasurementType; - typedef Histogram< MeasurementType, 2, THistogramFrequencyContainer > - HistogramType; - typedef typename HistogramType::Pointer HistogramPointer; - typedef typename HistogramType::ConstPointer HistogramConstPointer; - typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; + typedef Histogram< MeasurementType, 2, THistogramFrequencyContainer > + HistogramType; + typedef typename HistogramType::Pointer HistogramPointer; + typedef typename HistogramType::ConstPointer HistogramConstPointer; + typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; - /** Connects the mask image for which the histogram is going to be computed */ - itkSetConstObjectMacro( ImageMask, ImageType ); - itkGetConstObjectMacro( ImageMask, ImageType ); + /** Connects the mask image for which the histogram is going to be computed */ + itkSetConstObjectMacro( ImageMask, ImageType ); + itkGetConstObjectMacro( ImageMask, ImageType ); - /** Set the pixel value of the mask that should be considered "inside" the + /** Set the pixel value of the mask that should be considered "inside" the object. Defaults to one. */ - itkSetMacro( InsidePixelValue, PixelType ); - itkGetMacro( InsidePixelValue, PixelType ); + itkSetMacro( InsidePixelValue, PixelType ); + itkGetMacro( InsidePixelValue, PixelType ); - protected: - MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator(); - virtual ~MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator() {}; - void PrintSelf(std::ostream& os, Indent indent) const; - void FillHistogram( RadiusType radius, RegionType region ); - - private: - ImageConstPointer m_ImageMask; - PixelType m_InsidePixelValue; - - }; +protected: + MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator(); + virtual ~MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + void FillHistogram( RadiusType radius, RegionType region ); + +private: + MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + ImageConstPointer m_ImageMask; + PixelType m_InsidePixelValue; + +}; - - } // end of namespace Statistics + +} // end of namespace Statistics } // end of namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx index d8a32410fd..bb9acfb5c5 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx,v $ Language: C++ - Date: $Date: 2005-04-20 20:31:57 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 15:23:58 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator_txx -#define _itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator_txx +#ifndef __itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator_txx +#define __itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator_txx #include "itkMaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator.h" @@ -24,103 +24,103 @@ #include "itkConstNeighborhoodIterator.h" namespace itk { - namespace Statistics { +namespace Statistics { - template< class TImageType, class THistogramFrequencyContainer > - MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer >:: - MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator() : - m_ImageMask(NULL), m_InsidePixelValue(NumericTraits<PixelType>::One) - { - // Empty - } +template< class TImageType, class THistogramFrequencyContainer > +MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer >:: +MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator() : + m_ImageMask(NULL), m_InsidePixelValue(NumericTraits<PixelType>::One) +{ + // Empty +} - template< class TImageType, class THistogramFrequencyContainer > - void - MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer >:: - FillHistogram(RadiusType radius, RegionType region) - { - if (m_ImageMask.IsNull()) - { - // If there's no mask set, just use the (faster) superclass method - Superclass::FillHistogram(radius, region); - return; - } +template< class TImageType, class THistogramFrequencyContainer > +void +MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer >:: +FillHistogram(RadiusType radius, RegionType region) +{ + if (m_ImageMask.IsNull()) + { + // If there's no mask set, just use the (faster) superclass method + Superclass::FillHistogram(radius, region); + return; + } - // Iterate over all of those pixels and offsets, adding each - // co-occurrence pair to the histogram + // Iterate over all of those pixels and offsets, adding each + // co-occurrence pair to the histogram - typedef ConstNeighborhoodIterator<ImageType> NeighborhoodIteratorType; - NeighborhoodIteratorType neighborIt, maskNeighborIt; - neighborIt = NeighborhoodIteratorType(radius, this->GetInput(), region); - maskNeighborIt = NeighborhoodIteratorType(radius, m_ImageMask, region); + typedef ConstNeighborhoodIterator<ImageType> NeighborhoodIteratorType; + NeighborhoodIteratorType neighborIt, maskNeighborIt; + neighborIt = NeighborhoodIteratorType(radius, this->GetInput(), region); + maskNeighborIt = NeighborhoodIteratorType(radius, m_ImageMask, region); - for (neighborIt.GoToBegin(), maskNeighborIt.GoToBegin(); - !neighborIt.IsAtEnd(); ++neighborIt, ++maskNeighborIt) - { + for (neighborIt.GoToBegin(), maskNeighborIt.GoToBegin(); + !neighborIt.IsAtEnd(); ++neighborIt, ++maskNeighborIt) + { - if (maskNeighborIt.GetCenterPixel() != m_InsidePixelValue) - { - continue; // Go to the next loop if we're not in the mask - } + if (maskNeighborIt.GetCenterPixel() != m_InsidePixelValue) + { + continue; // Go to the next loop if we're not in the mask + } - const PixelType centerPixelIntensity = neighborIt.GetCenterPixel(); - if (centerPixelIntensity < this->GetMin() || - centerPixelIntensity > this->GetMax()) - { - continue; // don't put a pixel in the histogram if the value - // is out-of-bounds. - } + const PixelType centerPixelIntensity = neighborIt.GetCenterPixel(); + if (centerPixelIntensity < this->GetMin() || + centerPixelIntensity > this->GetMax()) + { + continue; // don't put a pixel in the histogram if the value + // is out-of-bounds. + } - typename OffsetVector::ConstIterator offsets; - for(offsets = this->GetOffsets()->Begin(); offsets != this->GetOffsets()->End(); offsets++) - { - - if (maskNeighborIt.GetPixel(offsets.Value()) != m_InsidePixelValue) - { - continue; // Go to the next loop if we're not in the mask - } + typename OffsetVector::ConstIterator offsets; + for(offsets = this->GetOffsets()->Begin(); offsets != this->GetOffsets()->End(); offsets++) + { - bool pixelInBounds; - const PixelType pixelIntensity = - neighborIt.GetPixel(offsets.Value(), pixelInBounds); + if (maskNeighborIt.GetPixel(offsets.Value()) != m_InsidePixelValue) + { + continue; // Go to the next loop if we're not in the mask + } - if (!pixelInBounds) - { - continue; // don't put a pixel in the histogram if it's out-of-bounds. - } + bool pixelInBounds; + const PixelType pixelIntensity = + neighborIt.GetPixel(offsets.Value(), pixelInBounds); - if (pixelIntensity < this->GetMin() || - pixelIntensity > this->GetMax()) - { - continue; // don't put a pixel in the histogram if the value - // is out-of-bounds. - } + if (!pixelInBounds) + { + continue; // don't put a pixel in the histogram if it's out-of-bounds. + } - // Now make both possible co-occurrence combinations and increment the - // histogram with them. - MeasurementVectorType cooccur; - cooccur[0] = centerPixelIntensity; - cooccur[1] = pixelIntensity; - this->GetOutput()->IncreaseFrequency(cooccur, 1); - cooccur[1] = centerPixelIntensity; - cooccur[0] = pixelIntensity; - this->GetOutput()->IncreaseFrequency(cooccur, 1); - } + if (pixelIntensity < this->GetMin() || + pixelIntensity > this->GetMax()) + { + continue; // don't put a pixel in the histogram if the value + // is out-of-bounds. } + + // Now make both possible co-occurrence combinations and increment the + // histogram with them. + MeasurementVectorType cooccur; + cooccur[0] = centerPixelIntensity; + cooccur[1] = pixelIntensity; + this->GetOutput()->IncreaseFrequency(cooccur, 1); + cooccur[1] = centerPixelIntensity; + cooccur[0] = pixelIntensity; + this->GetOutput()->IncreaseFrequency(cooccur, 1); } + } +} - template< class TImageType, class THistogramFrequencyContainer > - void - MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer >:: - PrintSelf(std::ostream& os, Indent indent) const - { - Superclass::PrintSelf(os,indent); - } +template< class TImageType, class THistogramFrequencyContainer > +void +MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer >:: +PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} - } // end of namespace Statistics +} // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMeanCalculator.h b/Utilities/ITK/Code/Numerics/Statistics/itkMeanCalculator.h index acfbeca8dc..e5ee63de01 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMeanCalculator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMeanCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanCalculator.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:54:59 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 15:23:58 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,8 +22,8 @@ #include "itkArray.h" -namespace itk{ - namespace Statistics{ +namespace itk { +namespace Statistics { /** \class MeanCalculator * \brief calculates sample mean @@ -49,14 +49,14 @@ class MeanCalculator : { public: /**Standard class typedefs. */ - typedef MeanCalculator Self; - typedef SampleAlgorithmBase< TSample > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef MeanCalculator Self; + typedef SampleAlgorithmBase< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /**Standard Macros */ itkTypeMacro(MeanCalculator, SampleAlgorithmBase); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Length of a measurement vector */ typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; @@ -68,22 +68,22 @@ public: typedef Array< double > OutputType; /** Returns the mean vector */ - OutputType* GetOutput() ; + OutputType* GetOutput(); protected: - MeanCalculator() ; + MeanCalculator(); virtual ~MeanCalculator() {} void PrintSelf(std::ostream& os, Indent indent) const; /** Calculates the mean and save it */ - void GenerateData() ; + void GenerateData(); private: /** Internal mean value storage */ - OutputType m_Output ; -} ; // end of class - - } // end of namespace Statistics + OutputType m_Output; +}; // end of class + +} // end of namespace Statistics } // end of namespace itk #ifndef ITK_MANUAL_INSTANTIATION @@ -91,4 +91,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMeanCalculator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkMeanCalculator.txx index cb7b8c0396..a957034e86 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMeanCalculator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMeanCalculator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanCalculator.txx,v $ Language: C++ - Date: $Date: 2006-08-14 15:40:56 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-03-04 15:23:58 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,14 +17,14 @@ #ifndef __itkMeanCalculator_txx #define __itkMeanCalculator_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > MeanCalculator< TSample > ::MeanCalculator() { - m_Output.Fill(0.0) ; + m_Output.Fill(0.0); } template< class TSample > @@ -42,7 +42,7 @@ typename MeanCalculator< TSample >::OutputType* MeanCalculator< TSample > ::GetOutput() { - return &m_Output ; + return &m_Output; } template< class TSample > @@ -50,9 +50,9 @@ void MeanCalculator< TSample > ::GenerateData() { - typename TSample::ConstIterator iter = this->GetInputSample()->Begin() ; - typename TSample::ConstIterator end = this->GetInputSample()->End() ; - double totalFrequency = 0.0 ; + typename TSample::ConstIterator iter = this->GetInputSample()->Begin(); + typename TSample::ConstIterator end = this->GetInputSample()->End(); + double totalFrequency = 0.0; this->SetMeasurementVectorSize( this->GetInputSample()->GetMeasurementVectorSize()); @@ -67,20 +67,19 @@ MeanCalculator< TSample > while (iter != end) { - double frequency = iter.GetFrequency() ; - totalFrequency += frequency ; - for (unsigned int dim = 0 ; dim < measurementVectorSize ; dim++) + double frequency = iter.GetFrequency(); + totalFrequency += frequency; + for (unsigned int dim = 0; dim < measurementVectorSize; dim++) { - m_Output[dim] += iter.GetMeasurementVector()[dim] * frequency ; + m_Output[dim] += iter.GetMeasurementVector()[dim] * frequency; } - ++iter ; + ++iter; } - m_Output /= totalFrequency ; + m_Output /= totalFrequency; } } // end of namespace Statistics } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeCacheMethod.h b/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeCacheMethod.h index 7de8e7c645..4f55677a79 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeCacheMethod.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeCacheMethod.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanShiftModeCacheMethod.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:00 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-04 15:23:58 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,8 +23,8 @@ #include "itkObject.h" #include "itkMeasurementVectorTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class MeanShiftModeCacheMethod * \brief This class stores mappings between a query point and its @@ -60,88 +60,88 @@ class MeanShiftModeCacheMethod : public: /** Standard class typedefs. */ typedef MeanShiftModeCacheMethod Self; - typedef Object Superclass ; - typedef SmartPointer<Self> Pointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(MeanShiftModeCacheMethod, Object); - itkNewMacro(Self) ; + itkNewMacro(Self); - typedef TMeasurementVector MeasurementVectorType ; + typedef TMeasurementVector MeasurementVectorType; struct LessMeasurementVector - { + { bool operator()(const MeasurementVectorType& mv1, const MeasurementVectorType& mv2) const - { + { // It is assumed that mv1 and mv2 are of the same length. For efficieny, // no checking is performed here. - for ( unsigned int i = 0 ; + for ( unsigned int i = 0; i < MeasurementVectorTraits::GetLength( &mv1 ); ++i ) { if (mv1[i] < mv2[i]) { - return true ; + return true; } } - return false ; - } - } ; // end of struct + return false; + } + }; // end of struct - typedef std::map< MeasurementVectorType, MeasurementVectorType, LessMeasurementVector > CacheTableType ; + typedef std::map< MeasurementVectorType, MeasurementVectorType, LessMeasurementVector > CacheTableType; void SetMaximumConsecutiveFailures(unsigned int number) - { m_MaximumConsecutiveFailures = number ; } + { m_MaximumConsecutiveFailures = number; } unsigned int GetMaximumConsecutiveFailures() - { return m_MaximumConsecutiveFailures ; } + { return m_MaximumConsecutiveFailures; } void SetHitRatioThreshold(float threshold) - { m_HitRatioThreshold = threshold ; } + { m_HitRatioThreshold = threshold; } void SetMaximumEntries(unsigned int number) - { m_MaximumEntries = number ; } + { m_MaximumEntries = number; } unsigned int GetMaximumEntries() - { return m_MaximumEntries ; } + { return m_MaximumEntries; } bool SetMeasurementVector(MeasurementVectorType& source, - MeasurementVectorType& target) ; + MeasurementVectorType& target); bool GetMeasurementVector(MeasurementVectorType& source, - MeasurementVectorType& target) ; + MeasurementVectorType& target); - bool IsFull() ; + bool IsFull(); - void DestroyCacheTable() ; + void DestroyCacheTable(); protected: - MeanShiftModeCacheMethod() ; - virtual ~MeanShiftModeCacheMethod() ; + MeanShiftModeCacheMethod(); + virtual ~MeanShiftModeCacheMethod(); void PrintSelf(std::ostream& os, Indent indent) const; private: - unsigned int m_MaximumEntries ; - float m_HitRatioThreshold ; - unsigned int m_MaximumConsecutiveFailures ; + unsigned int m_MaximumEntries; + float m_HitRatioThreshold; + unsigned int m_MaximumConsecutiveFailures; - unsigned int m_NumberOfRequests ; - unsigned int m_ConsecutiveFailures ; - unsigned int m_HitsSuccess ; + unsigned int m_NumberOfRequests; + unsigned int m_ConsecutiveFailures; + unsigned int m_HitsSuccess; - unsigned long m_TotalHitsSuccess ; - unsigned long m_TotalHitsFailure ; + unsigned long m_TotalHitsSuccess; + unsigned long m_TotalHitsFailure; - unsigned long m_TotalTableSize ; - unsigned int m_TimesOfRebuilding ; + unsigned long m_TotalTableSize; + unsigned int m_TimesOfRebuilding; - unsigned int m_TimesOfRebuildingByHitRatio ; - unsigned int m_TimesOfRebuildingByConsecutiveFailures ; + unsigned int m_TimesOfRebuildingByHitRatio; + unsigned int m_TimesOfRebuildingByConsecutiveFailures; - CacheTableType m_CacheTable ; -} ; // end of class + CacheTableType m_CacheTable; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -151,4 +151,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeCacheMethod.txx b/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeCacheMethod.txx index 2ee8ff5840..465d91ad3d 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeCacheMethod.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeCacheMethod.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanShiftModeCacheMethod.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:00 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-04 15:24:00 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,28 +17,28 @@ #ifndef __itkMeanShiftModeCacheMethod_txx #define __itkMeanShiftModeCacheMethod_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TMeasurementVector > MeanShiftModeCacheMethod< TMeasurementVector > ::MeanShiftModeCacheMethod() { - m_MaximumEntries = 200 ; - m_MaximumConsecutiveFailures = 5 ; - m_HitRatioThreshold = 0.75 ; + m_MaximumEntries = 200; + m_MaximumConsecutiveFailures = 5; + m_HitRatioThreshold = 0.75; - m_HitsSuccess = 0 ; - m_NumberOfRequests = 0 ; - m_ConsecutiveFailures = 0 ; + m_HitsSuccess = 0; + m_NumberOfRequests = 0; + m_ConsecutiveFailures = 0; - m_TotalHitsSuccess = 0 ; - m_TotalHitsFailure = 0 ; + m_TotalHitsSuccess = 0; + m_TotalHitsFailure = 0; - m_TotalTableSize = 0 ; - m_TimesOfRebuilding = 0 ; - m_TimesOfRebuildingByHitRatio = 0 ; - m_TimesOfRebuildingByConsecutiveFailures = 0 ; + m_TotalTableSize = 0; + m_TimesOfRebuilding = 0; + m_TimesOfRebuildingByHitRatio = 0; + m_TimesOfRebuildingByConsecutiveFailures = 0; } template< class TMeasurementVector > @@ -54,42 +54,42 @@ MeanShiftModeCacheMethod< TMeasurementVector > { Superclass::PrintSelf(os,indent); - os << indent << "Maximum entries: " << m_MaximumEntries << std::endl ; + os << indent << "Maximum entries: " << m_MaximumEntries << std::endl; os << indent << "Maximum consecutive failures: " - << m_MaximumConsecutiveFailures << std::endl ; + << m_MaximumConsecutiveFailures << std::endl; os << indent << "Hit ratio threshold: " - << m_HitRatioThreshold << std::endl ; + << m_HitRatioThreshold << std::endl; os << indent << "Last consecutive failures: " - << m_ConsecutiveFailures << std::endl ; + << m_ConsecutiveFailures << std::endl; os << indent << "Last successful hits: " - << m_HitsSuccess << std::endl ; + << m_HitsSuccess << std::endl; os << indent << "Last number of requests: " - << m_NumberOfRequests << std::endl ; + << m_NumberOfRequests << std::endl; - os << indent << "Total successful hits: " << m_TotalHitsSuccess << std::endl ; - os << indent << "Total failed hits: " << m_TotalHitsFailure << std::endl ; + os << indent << "Total successful hits: " << m_TotalHitsSuccess << std::endl; + os << indent << "Total failed hits: " << m_TotalHitsFailure << std::endl; os << indent << "Total table size before destuction: " - << m_TotalTableSize << std::endl ; + << m_TotalTableSize << std::endl; os << indent << "Number of cache rebuildings: " - << m_TimesOfRebuilding << std::endl ; - os << indent << "Average cache table size: " ; + << m_TimesOfRebuilding << std::endl; + os << indent << "Average cache table size: "; if ( m_TimesOfRebuilding > 0 ) { - os << (float)(m_TotalTableSize / m_TimesOfRebuilding) << std::endl ; + os << (float)(m_TotalTableSize / m_TimesOfRebuilding) << std::endl; } else { - os << m_TotalTableSize << std::endl ; + os << m_TotalTableSize << std::endl; } os << indent << "Number of cache rebuildings caused by hit ratio threshold: " - << m_TimesOfRebuildingByHitRatio << std::endl ; + << m_TimesOfRebuildingByHitRatio << std::endl; os << indent << "Number of cache rebuildings caused by consecutive failures: " - << m_TimesOfRebuildingByConsecutiveFailures << std::endl ; + << m_TimesOfRebuildingByConsecutiveFailures << std::endl; - os << indent << "Cache table: " << &m_CacheTable << std::endl ; + os << indent << "Cache table: " << &m_CacheTable << std::endl; } template< class TMeasurementVector > @@ -104,12 +104,12 @@ MeanShiftModeCacheMethod< TMeasurementVector > if ( this->IsFull() ) { - return false ; + return false; } else { - m_CacheTable[source] = target ; - return true ; + m_CacheTable[source] = target; + return true; } } @@ -119,37 +119,37 @@ MeanShiftModeCacheMethod< TMeasurementVector > ::GetMeasurementVector(MeasurementVectorType& source, MeasurementVectorType& target) { - typename CacheTableType::iterator iter = m_CacheTable.find( source ) ; - ++m_NumberOfRequests ; + typename CacheTableType::iterator iter = m_CacheTable.find( source ); + ++m_NumberOfRequests; if ( iter != m_CacheTable.end() ) { - target = iter->second ; - ++m_HitsSuccess ; - ++m_TotalHitsSuccess ; - m_ConsecutiveFailures = 0 ; - return true ; + target = iter->second; + ++m_HitsSuccess; + ++m_TotalHitsSuccess; + m_ConsecutiveFailures = 0; + return true; } else { - ++m_TotalHitsFailure ; + ++m_TotalHitsFailure; if ( this->IsFull() ) { - ++m_ConsecutiveFailures ; + ++m_ConsecutiveFailures; if ( float(m_HitsSuccess / m_NumberOfRequests) < m_HitRatioThreshold ) { - ++m_TimesOfRebuildingByHitRatio ; - this->DestroyCacheTable() ; - return false ; + ++m_TimesOfRebuildingByHitRatio; + this->DestroyCacheTable(); + return false; } if ( m_ConsecutiveFailures > m_MaximumConsecutiveFailures ) { - ++m_TimesOfRebuildingByConsecutiveFailures ; - this->DestroyCacheTable() ; - return false ; + ++m_TimesOfRebuildingByConsecutiveFailures; + this->DestroyCacheTable(); + return false; } } - return false ; + return false; } } @@ -160,11 +160,11 @@ MeanShiftModeCacheMethod< TMeasurementVector > { if ( m_CacheTable.size() < m_MaximumEntries ) { - return false ; + return false; } else { - return true ; + return true; } } @@ -173,12 +173,12 @@ void MeanShiftModeCacheMethod< TMeasurementVector > ::DestroyCacheTable() { - ++m_TimesOfRebuilding ; - m_TotalTableSize += m_CacheTable.size() ; - m_NumberOfRequests = 0 ; - m_HitsSuccess = 0 ; - m_ConsecutiveFailures = 0 ; - m_CacheTable.clear() ; + ++m_TimesOfRebuilding; + m_TotalTableSize += m_CacheTable.size(); + m_NumberOfRequests = 0; + m_HitsSuccess = 0; + m_ConsecutiveFailures = 0; + m_CacheTable.clear(); } @@ -186,4 +186,3 @@ MeanShiftModeCacheMethod< TMeasurementVector > } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeSeekerBase.h b/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeSeekerBase.h index caeeb41caf..d2d86a19ac 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeSeekerBase.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeSeekerBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanShiftModeSeekerBase.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:02 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-04 15:24:01 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,8 +24,8 @@ #include "itkNumericTraits.h" #include "itkMeanShiftModeCacheMethod.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class MeanShiftModeSeekerBase * \brief Evolves the mode. This is the base class for any mean shift @@ -62,41 +62,41 @@ class MeanShiftModeSeekerBase : { public: /** Standard class typedefs. */ - typedef MeanShiftModeSeekerBase Self; - typedef Object Superclass ; - typedef SmartPointer<Self> Pointer; + typedef MeanShiftModeSeekerBase Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(MeanShiftModeSeekerBase, Object); /** Typedefs from the TSample template argument */ - typedef typename TSample::MeasurementVectorType MeasurementVectorType ; - typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType ; - typedef typename TSample::MeasurementType MeasurementType ; - typedef typename TSample::InstanceIdentifier InstanceIdentifier ; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::InstanceIdentifier InstanceIdentifier; - typedef std::vector< InstanceIdentifier > SearchResultVectorType ; - typedef MeanShiftModeCacheMethod< MeasurementVectorType > CacheMethodType ; + typedef std::vector< InstanceIdentifier > SearchResultVectorType; + typedef MeanShiftModeCacheMethod< MeasurementVectorType > CacheMethodType; - void SetInputSample(const TSample* sample) ; + void SetInputSample(const TSample* sample); const TSample* GetInputSample() const - { return m_InputSample.GetPointer() ; } + { return m_InputSample.GetPointer(); } void SetMaximumIteration(unsigned int number) - { m_MaximumIteration = number ; } + { m_MaximumIteration = number; } unsigned int GetMaximumIteration() - { return m_MaximumIteration ; } + { return m_MaximumIteration; } - void SetCacheMethod(CacheMethodType* method) ; + void SetCacheMethod(CacheMethodType* method); CacheMethodType* GetCacheMethod() - { return m_CacheMethod.GetPointer() ; } + { return m_CacheMethod.GetPointer(); } /** Returns the covariance matrix of the target sample data */ - MeasurementVectorType Evolve(MeasurementVectorType instance) ; + MeasurementVectorType Evolve(MeasurementVectorType instance); /** Get the length of a measurement vector */ virtual MeasurementVectorSizeType GetMeasurementVectorSize() const @@ -112,19 +112,18 @@ public: } protected: - MeanShiftModeSeekerBase() ; - virtual ~MeanShiftModeSeekerBase() ; + MeanShiftModeSeekerBase(); + virtual ~MeanShiftModeSeekerBase(); void PrintSelf(std::ostream& os, Indent indent) const; virtual bool ComputeMode(MeasurementVectorType queryPoint, - MeasurementVectorType& newPoint) = 0 ; + MeasurementVectorType& newPoint) = 0; - private: - typename TSample::ConstPointer m_InputSample ; - unsigned int m_MaximumIteration ; - typename CacheMethodType::Pointer m_CacheMethod ; -} ; // end of class + typename TSample::ConstPointer m_InputSample; + unsigned int m_MaximumIteration; + typename CacheMethodType::Pointer m_CacheMethod; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -134,4 +133,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeSeekerBase.txx b/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeSeekerBase.txx index 4ec57ed0c0..f87429eb58 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeSeekerBase.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMeanShiftModeSeekerBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanShiftModeSeekerBase.txx,v $ Language: C++ - Date: $Date: 2005-08-01 19:23:35 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 15:24:02 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,15 +17,15 @@ #ifndef __itkMeanShiftModeSeekerBase_txx #define __itkMeanShiftModeSeekerBase_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > MeanShiftModeSeekerBase< TSample > ::MeanShiftModeSeekerBase() { - m_MaximumIteration = 0 ; - m_CacheMethod = 0 ; + m_MaximumIteration = 0; + m_CacheMethod = 0; } @@ -42,27 +42,27 @@ MeanShiftModeSeekerBase< TSample > { Superclass::PrintSelf(os,indent); - os << indent << "InputSample: " ; + os << indent << "InputSample: "; if ( m_InputSample.IsNotNull() ) { os << m_InputSample << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "CacheMethod: " ; + os << indent << "CacheMethod: "; if ( m_CacheMethod.IsNotNull() ) { os << m_CacheMethod << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "Maximum iterations: " << m_MaximumIteration << std::endl ; + os << indent << "Maximum iterations: " << m_MaximumIteration << std::endl; } template< class TSample > @@ -72,8 +72,8 @@ MeanShiftModeSeekerBase< TSample > { if ( m_InputSample != sample ) { - m_InputSample = sample ; - this->Modified() ; + m_InputSample = sample; + this->Modified(); } } @@ -84,8 +84,8 @@ MeanShiftModeSeekerBase< TSample > { if ( m_CacheMethod != method ) { - m_CacheMethod = method ; - this->Modified() ; + m_CacheMethod = method; + this->Modified(); } } @@ -101,11 +101,11 @@ MeanShiftModeSeekerBase< TSample > "Length mismatch: MeanShiftModeSeekerBase::Evolve" ); } - MeasurementVectorType queryPoint = instance ; + MeasurementVectorType queryPoint = instance; MeasurementVectorType newPoint; - MeasurementVectorType previousPoint = queryPoint ; + MeasurementVectorType previousPoint = queryPoint; - unsigned int currentIteration = 0 ; + unsigned int currentIteration = 0; bool retCode = false; while ( true ) @@ -114,49 +114,48 @@ MeanShiftModeSeekerBase< TSample > { if ( this->GetDebug() ) { - std::cout << "DEBUG: max exceeded." << std::endl ; + std::cout << "DEBUG: max exceeded." << std::endl; } - return queryPoint ; + return queryPoint; } if ( m_CacheMethod.IsNotNull() ) { if ( !m_CacheMethod->GetMeasurementVector(queryPoint, newPoint) ) { - retCode = this->ComputeMode( queryPoint, newPoint ) ; + retCode = this->ComputeMode( queryPoint, newPoint ); if ( retCode ) { - m_CacheMethod->SetMeasurementVector( queryPoint, newPoint ) ; + m_CacheMethod->SetMeasurementVector( queryPoint, newPoint ); } } } else { - retCode = this->ComputeMode( queryPoint, newPoint ) ; + retCode = this->ComputeMode( queryPoint, newPoint ); } if ( !retCode ) { - return queryPoint ; + return queryPoint; } if ( queryPoint != newPoint && newPoint != previousPoint ) { - previousPoint = queryPoint ; - queryPoint = newPoint ; + previousPoint = queryPoint; + queryPoint = newPoint; } else { - return queryPoint ; + return queryPoint; } - ++currentIteration ; + ++currentIteration; } // end of while - return queryPoint ; //This is here to avoid compiler warning, but should never occur. + return queryPoint; //This is here to avoid compiler warning, but should never occur. } } // end of namespace Statistics } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMeasurementVectorTraits.h b/Utilities/ITK/Code/Numerics/Statistics/itkMeasurementVectorTraits.h index e4cca69c95..29ead60508 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMeasurementVectorTraits.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMeasurementVectorTraits.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeasurementVectorTraits.h,v $ Language: C++ - Date: $Date: 2007-01-26 23:43:03 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 15:24:02 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -256,7 +256,7 @@ public: static MeasurementVectorLength Assert( const Array< TValueType > &a, const MeasurementVectorLength l, const char *errMsg="Length Mismatch") { - if( ((l!=0) && (a.Size()!=l)) || (a.Size()==0) ) + if( ((l != 0) && (a.Size() != l)) || (a.Size() == 0) ) { itkGenericExceptionMacro( << errMsg ); } @@ -271,7 +271,7 @@ public: static MeasurementVectorLength Assert( const Array< TValueType > *a, const MeasurementVectorLength l, const char *errMsg="Length Mismatch") { - if( ((l!=0) && (a->Size()!=l)) || (a->Size()==0) ) + if( ((l != 0) && (a->Size() != l)) || (a->Size() == 0) ) { itkGenericExceptionMacro( << errMsg ); } @@ -286,7 +286,7 @@ public: static MeasurementVectorLength Assert( const VariableLengthVector< TValueType > &a, const MeasurementVectorLength l, const char *errMsg="Length Mismatch") { - if( ((l!=0) && (a.Size()!=l)) || (a.Size()==0) ) + if( ((l !=0 ) && (a.Size() != l)) || (a.Size() == 0) ) { itkGenericExceptionMacro( << errMsg ); } @@ -301,7 +301,7 @@ public: static MeasurementVectorLength Assert( const VariableLengthVector< TValueType > *a, const MeasurementVectorLength l, const char *errMsg="Length Mismatch") { - if( ((l!=0) && (a->Size()!=l)) || (a->Size()==0) ) + if( ((l !=0 ) && (a->Size() != l)) || (a->Size() == 0) ) { itkGenericExceptionMacro( << errMsg ); } @@ -311,11 +311,11 @@ public: } return 0; } - template< class TValueType > + template< class TValueType > static MeasurementVectorLength Assert( const std::vector< TValueType > &a, const MeasurementVectorLength l, const char *errMsg="Length Mismatch") { - if( ((l!=0) && (a.size()!=l)) || (a.size()==0) ) + if( ((l != 0) && (a.size() != l)) || (a.size() == 0) ) { itkGenericExceptionMacro( << errMsg ); } @@ -330,7 +330,7 @@ public: static MeasurementVectorLength Assert( const std::vector< TValueType > *a, const MeasurementVectorLength l, const char *errMsg="Length Mismatch") { - if( ((l!=0) && (a->size()!=l)) || (a->size()==0) ) + if( ((l != 0) && (a->size() != l)) || (a->size() == 0) ) { itkGenericExceptionMacro( << errMsg ); } @@ -340,9 +340,8 @@ public: } return 0; } - }; +}; } // namespace itk #endif // __itkMeasurementVectorTraits_h - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipFunctionBase.h b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipFunctionBase.h index d8599cffc7..d579f9e602 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipFunctionBase.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipFunctionBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMembershipFunctionBase.h,v $ Language: C++ - Date: $Date: 2006-02-24 16:57:21 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-04 15:24:02 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,8 +20,8 @@ #include "itkFunctionBase.h" #include "itkMeasurementVectorTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class MembershipFunctionBase * \brief MembershipFunctionBase class declares common interfaces @@ -40,10 +40,10 @@ class ITK_EXPORT MembershipFunctionBase : { public: /** Standard class typedefs */ - typedef MembershipFunctionBase Self; - typedef FunctionBase< TVector, double > Superclass ; - typedef SmartPointer< Self > Pointer ; - typedef SmartPointer<const Self> ConstPointer; + typedef MembershipFunctionBase Self; + typedef FunctionBase< TVector, double > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Strandard macros */ itkTypeMacro(MembershipFunctionBase, FunctionBase); @@ -52,7 +52,7 @@ public: typedef unsigned int MeasurementVectorSizeType; /** Method to get membership score (discriminant score) of an entity. */ - virtual double Evaluate(const TVector &x) const = 0 ; + virtual double Evaluate(const TVector &x) const = 0; /** Set/Get Macros to set the length of each measurement vector. */ itkSetMacro( MeasurementVectorSize, MeasurementVectorSizeType ); @@ -65,22 +65,15 @@ protected: void PrintSelf(std::ostream& os, Indent indent) const { - Superclass::PrintSelf(os,indent) ; + Superclass::PrintSelf(os,indent); os << indent << "Length of measurement vectors: " << m_MeasurementVectorSize << std::endl; } MeasurementVectorSizeType m_MeasurementVectorSize; -} ; // end of class +}; // end of class } // end of namespace Statistics } // end namespace itk #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSample.h b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSample.h index c71239daa0..c4e98a2624 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSample.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSample.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMembershipSample.h,v $ Language: C++ - Date: $Date: 2005-09-30 17:24:45 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-03-04 15:24:02 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,8 +23,8 @@ #include "itkExceptionObject.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class MembershipSample * \brief Container for storing the instance-identifiers of other sample with @@ -59,78 +59,79 @@ class ITK_EXPORT MembershipSample : { public: /** Standard class typedefs. */ - typedef MembershipSample Self; - typedef Sample< typename TSample::MeasurementVectorType > Superclass ; - typedef SmartPointer< Self > Pointer ; - typedef SmartPointer< const Self > ConstPointer ; + typedef MembershipSample Self; + typedef Sample< typename TSample::MeasurementVectorType > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; /** Standard macros */ itkTypeMacro(MembershipSample, Sample); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Typedefs for Measurement vector, measurement, Instance Identifier, - * frequency, size, size element value from the template argument TSample*/ + * frequency, size, size element value from the template argument + * TSample */ typedef typename TSample::MeasurementVectorType MeasurementVectorType; - typedef typename TSample::MeasurementType MeasurementType; - typedef typename TSample::InstanceIdentifier InstanceIdentifier; - typedef typename TSample::FrequencyType FrequencyType ; - typedef typename TSample::TotalFrequencyType TotalFrequencyType ; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::InstanceIdentifier InstanceIdentifier; + typedef typename TSample::FrequencyType FrequencyType; + typedef typename TSample::TotalFrequencyType TotalFrequencyType; /** vector of unique class labels that will be used for mapping internal * continuous class label with real class labels */ - typedef std::vector< unsigned int > UniqueClassLabelsType ; + typedef std::vector< unsigned int > UniqueClassLabelsType; /** Typedef for the storage that holds a class label for each instance. * The relationship between instances and class label is one-to-one */ - typedef itk::hash_map< InstanceIdentifier, unsigned int> ClassLabelHolderType ; + typedef itk::hash_map< InstanceIdentifier, unsigned int> ClassLabelHolderType; /** Typedef for each subsample that stores instance identifers of instances * that belong to a class */ - typedef Subsample< TSample > ClassSampleType ; + typedef Subsample< TSample > ClassSampleType; typedef typename ClassSampleType::Pointer ClassSamplePointer; typedef typename ClassSampleType::ConstPointer ClassSampleConstPointer; /** Plug in the actual sample data */ - void SetSample(const TSample* sample) ; + void SetSample(const TSample* sample); /** Returns the source sample pointer */ const TSample* GetSample() const; /** Sets the number of classes (class labels) */ - void SetNumberOfClasses(unsigned int numberOfClasses) ; + void SetNumberOfClasses(unsigned int numberOfClasses); /** Gets the number of classes (class labels) */ - unsigned int GetNumberOfClasses() const ; + unsigned int GetNumberOfClasses() const; /** Adds an instance from the source sample to this container. The * first argument is the class label for that instance. The second * argument is the instance identifier from the source identifier that * is going to be included this container. */ - void AddInstance(const unsigned int &classLabel, const InstanceIdentifier &id) ; + void AddInstance(const unsigned int &classLabel, const InstanceIdentifier &id); /** Gets the class label for the instance that has the instance * identifier, id. */ - unsigned int GetClassLabel(const InstanceIdentifier &id) const ; + unsigned int GetClassLabel(const InstanceIdentifier &id) const; /** Gets the internal continuous class label from the class labels that * are used for AddInstance method. */ - int GetInternalClassLabel(const unsigned int classLabel ) const ; + int GetInternalClassLabel(const unsigned int classLabel ) const; /** Gets the number of instances that belong to the class label in * this container */ - unsigned int GetClassSampleSize(const unsigned int &classLabel) const ; + unsigned int GetClassSampleSize(const unsigned int &classLabel) const; /** Gets the Subsample that includes only the instances that belongs * to the classLabel */ - const ClassSampleType* GetClassSample(const unsigned int &classLabel) const ; + const ClassSampleType* GetClassSample(const unsigned int &classLabel) const; /** Gets the class labels that corresponding to the each instance in * this container. */ ClassLabelHolderType* GetClassLabels() - { return &m_ClassLabelHolder ; } + { return &m_ClassLabelHolder; } /** returns the number of elements in each dimension */ - unsigned int Size(void) const ; + unsigned int Size(void) const; /** retunrs the measurement of the instance which is identified * by the 'id' */ @@ -139,129 +140,127 @@ public: /** returns the measurement element which is the 'n'-th element * in the 'd' dimension of the measurement vector */ MeasurementType GetMeasurement(const InstanceIdentifier &id, - const unsigned int &dimension) ; + const unsigned int &dimension); /** returns the frequency of the instance which is identified by the 'id' */ - FrequencyType GetFrequency(const InstanceIdentifier &id) const ; + FrequencyType GetFrequency(const InstanceIdentifier &id) const; /** returns the total frequency for the 'd' dimension */ - TotalFrequencyType GetTotalFrequency() const ; + TotalFrequencyType GetTotalFrequency() const; void Resize(unsigned int n) - { - m_ClassLabelHolder.resize(n) ; - } - + { + m_ClassLabelHolder.resize(n); + } class ConstIterator - { - public: + { + public: ConstIterator(InstanceIdentifier id, const Self* membershipSample) :m_Id(id), m_MembershipSample(membershipSample), - m_Sample(membershipSample->GetSample()) - {} + m_Sample(membershipSample->GetSample()) {} FrequencyType GetFrequency() const - { return m_Sample->GetFrequency(m_Id) ; } + { return m_Sample->GetFrequency(m_Id); } const MeasurementVectorType & GetMeasurementVector() const - { return m_Sample->GetMeasurementVector(m_Id) ; } + { return m_Sample->GetMeasurementVector(m_Id); } InstanceIdentifier GetInstanceIdentifier() const - { return m_Id ; } + { return m_Id; } void SetClassLabel(unsigned int classLabel) - { m_MembershipSample->AddInstance(classLabel, m_Id) ; } + { m_MembershipSample->AddInstance(classLabel, m_Id); } unsigned int GetClassLabel() const - { return m_MembershipSample->GetClassLabel(m_Id) ; } + { return m_MembershipSample->GetClassLabel(m_Id); } ConstIterator& operator++() - { - ++m_Id ; - return *this ; - } + { + ++m_Id; + return *this; + } bool operator!=(const ConstIterator& it) - { + { if (m_Id != it.m_Id || m_MembershipSample != it.m_MembershipSample || m_Sample != it.m_Sample) { - return true ; + return true; } else { - return false ; + return false; } - } + } bool operator==(const ConstIterator& it) - { + { if (m_Id == it.m_Id && m_MembershipSample == it.m_MembershipSample && m_Sample == it.m_Sample) { - return true ; + return true; } else { - return false ; + return false; } - } + } ConstIterator& operator=(const ConstIterator& it) - { + { m_Id = it.m_Id; - m_MembershipSample = it.m_MembershipSample ; - m_Sample = it.m_Sample ; - return *this ; - } + m_MembershipSample = it.m_MembershipSample; + m_Sample = it.m_Sample; + return *this; + } ConstIterator(const ConstIterator& it) - { + { m_Id = it.m_Id; - m_MembershipSample = it.m_MembershipSample ; - m_Sample = it.m_Sample ; - } + m_MembershipSample = it.m_MembershipSample; + m_Sample = it.m_Sample; + } private: // identifier for the instance - InstanceIdentifier m_Id ; + InstanceIdentifier m_Id; // Pointer to MemebershipSample object - const Self* m_MembershipSample ; - const TSample* m_Sample ; - } ; + const Self* m_MembershipSample; + const TSample* m_Sample; + }; ConstIterator Begin() const - { - ConstIterator iter(0, this) ; + { + ConstIterator iter(0, this); return iter; - } + } - ConstIterator End() const - { - ConstIterator iter(this->Size(), this) ; + ConstIterator End() const + { + ConstIterator iter(this->Size(), this); return iter; - } + } protected: - MembershipSample() ; + MembershipSample(); virtual ~MembershipSample() {} void PrintSelf(std::ostream& os, Indent indent) const; private: - MembershipSample(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + MembershipSample(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - const TSample* m_Sample ; - unsigned int m_CurrentClassLabel ; - UniqueClassLabelsType m_UniqueClassLabels ; - ClassLabelHolderType m_ClassLabelHolder ; - unsigned int m_NumberOfClasses ; - std::vector< unsigned int > m_ClassSampleSizes ; - std::vector< ClassSamplePointer > m_ClassSamples ; -} ; // end of class + const TSample* m_Sample; + unsigned int m_CurrentClassLabel; + UniqueClassLabelsType m_UniqueClassLabels; + ClassLabelHolderType m_ClassLabelHolder; + unsigned int m_NumberOfClasses; + std::vector< unsigned int > m_ClassSampleSizes; + std::vector< ClassSamplePointer > m_ClassSamples; +}; // end of class } // end of namespace Statistics @@ -273,10 +272,3 @@ private: #endif #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSample.txx b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSample.txx index 9baa69d404..116b47e3e7 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSample.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSample.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMembershipSample.txx,v $ Language: C++ - Date: $Date: 2005-09-30 14:14:18 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-03-04 15:24:02 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,15 +17,15 @@ #ifndef __itkMembershipSample_txx #define __itkMembershipSample_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > MembershipSample< TSample > ::MembershipSample() { - m_Sample = 0 ; - m_CurrentClassLabel = 0 ; + m_Sample = 0; + m_CurrentClassLabel = 0; } template< class TSample > @@ -33,7 +33,7 @@ void MembershipSample< TSample > ::SetSample(const TSample* sample) { - m_Sample = sample ; + m_Sample = sample; this->SetMeasurementVectorSize( sample->GetMeasurementVectorSize() ); } @@ -42,7 +42,7 @@ const TSample* MembershipSample< TSample > ::GetSample() const { - return m_Sample ; + return m_Sample; } template< class TSample > @@ -50,14 +50,14 @@ void MembershipSample< TSample > ::SetNumberOfClasses(unsigned int numberOfClasses) { - m_NumberOfClasses = numberOfClasses ; - m_ClassSampleSizes.resize(m_NumberOfClasses) ; - m_ClassSamples.resize(m_NumberOfClasses) ; - for ( unsigned int i = 0 ; i < m_NumberOfClasses ; i++ ) + m_NumberOfClasses = numberOfClasses; + m_ClassSampleSizes.resize(m_NumberOfClasses); + m_ClassSamples.resize(m_NumberOfClasses); + for ( unsigned int i = 0; i < m_NumberOfClasses; i++ ) { - m_ClassSamples[i] = ClassSampleType::New() ; - (m_ClassSamples[i])->SetSample(this->GetSample()) ; - m_ClassSampleSizes[i] = 0 ; + m_ClassSamples[i] = ClassSampleType::New(); + (m_ClassSamples[i])->SetSample(this->GetSample()); + m_ClassSampleSizes[i] = 0; } } @@ -66,7 +66,7 @@ unsigned int MembershipSample< TSample > ::GetNumberOfClasses() const { - return m_NumberOfClasses ; + return m_NumberOfClasses; } template< class TSample > @@ -74,17 +74,17 @@ inline void MembershipSample< TSample > ::AddInstance(const unsigned int &classLabel, const InstanceIdentifier &id) { - m_ClassLabelHolder[id] = classLabel ; - int classIndex = this->GetInternalClassLabel(classLabel) ; + m_ClassLabelHolder[id] = classLabel; + int classIndex = this->GetInternalClassLabel(classLabel); if ( classIndex == -1 ) { - m_UniqueClassLabels.push_back(classLabel) ; - classIndex = m_UniqueClassLabels.size() - 1 ; + m_UniqueClassLabels.push_back(classLabel); + classIndex = m_UniqueClassLabels.size() - 1; } - m_ClassSampleSizes[classIndex] += 1 ; + m_ClassSampleSizes[classIndex] += 1; - (m_ClassSamples[classIndex])->AddInstance(id) ; + (m_ClassSamples[classIndex])->AddInstance(id); } template< class TSample > @@ -92,7 +92,7 @@ inline unsigned int MembershipSample< TSample > ::GetClassLabel(const InstanceIdentifier &id) const { - return (*(m_ClassLabelHolder.find(id))).second ; + return (*(m_ClassLabelHolder.find(id))).second; } template< class TSample > @@ -100,15 +100,15 @@ inline int MembershipSample< TSample > ::GetInternalClassLabel(const unsigned int classLabel) const { - for ( unsigned int i = 0 ; i < m_UniqueClassLabels.size() ; i++ ) + for ( unsigned int i = 0; i < m_UniqueClassLabels.size(); i++ ) { if ( m_UniqueClassLabels[i] == classLabel ) { - return i ; + return i; } } - return -1 ; + return -1; } template< class TSample > @@ -116,8 +116,8 @@ unsigned int MembershipSample< TSample > ::GetClassSampleSize(const unsigned int &classLabel) const { - int classIndex = this->GetInternalClassLabel(classLabel) ; - return m_ClassSampleSizes[classIndex] ; + int classIndex = this->GetInternalClassLabel(classLabel); + return m_ClassSampleSizes[classIndex]; } @@ -126,8 +126,8 @@ const typename MembershipSample< TSample >::ClassSampleType* MembershipSample< TSample > ::GetClassSample(const unsigned int &classLabel) const { - int classIndex = this->GetInternalClassLabel(classLabel) ; - return m_ClassSamples[classIndex] ; + int classIndex = this->GetInternalClassLabel(classLabel); + return m_ClassSamples[classIndex]; } template< class TSample > @@ -135,7 +135,7 @@ inline unsigned int MembershipSample< TSample > ::Size(void) const { - return m_Sample->Size() ; + return m_Sample->Size(); } template< class TSample > @@ -143,7 +143,7 @@ inline const typename MembershipSample< TSample >::MeasurementVectorType & MembershipSample< TSample > ::GetMeasurementVector(const InstanceIdentifier &id) const { - return m_Sample->GetMeasurementVector(id) ; + return m_Sample->GetMeasurementVector(id); } template< class TSample > @@ -152,7 +152,7 @@ MembershipSample< TSample > ::GetMeasurement(const InstanceIdentifier &id, const unsigned int &dimension) { - return m_Sample->GetMeasurement(id, dimension) ; + return m_Sample->GetMeasurement(id, dimension); } template< class TSample > @@ -160,7 +160,7 @@ inline typename MembershipSample< TSample >::FrequencyType MembershipSample< TSample > ::GetFrequency(const InstanceIdentifier &id) const { - return m_Sample->GetFrequency(id) ; + return m_Sample->GetFrequency(id); } template< class TSample > @@ -168,7 +168,7 @@ inline typename MembershipSample< TSample >::TotalFrequencyType MembershipSample< TSample > ::GetTotalFrequency() const { - return m_Sample->GetTotalFrequency() ; + return m_Sample->GetTotalFrequency(); } template< class TSample > @@ -178,14 +178,14 @@ MembershipSample< TSample > { Superclass::PrintSelf(os,indent); - os << indent << "Sample: " ; + os << indent << "Sample: "; if ( m_Sample != 0 ) { os << m_Sample << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } os << indent << "CurrentClassLabel: " << m_CurrentClassLabel << std::endl; @@ -195,11 +195,3 @@ MembershipSample< TSample > } // end of namespace itk #endif - - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSampleGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSampleGenerator.h index 1a829587f1..a256122892 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSampleGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSampleGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMembershipSampleGenerator.h,v $ Language: C++ - Date: $Date: 2003-12-15 01:00:46 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 15:24:02 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include "itkObject.h" #include "itkMembershipSample.h" -namespace itk{ - namespace Statistics{ +namespace itk { +namespace Statistics { /** \class MembershipSampleGenerator * \brief MembershipSampleGenerator generates a MembershipSample object @@ -54,57 +54,57 @@ class ITK_EXPORT MembershipSampleGenerator : public: /** Standard class typedefs. */ typedef MembershipSampleGenerator Self; - typedef Object Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(MembershipSampleGenerator, Object); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Input sample types alias */ - typedef typename TInputSample::MeasurementVectorType MeasurementVectorType ; + typedef typename TInputSample::MeasurementVectorType MeasurementVectorType; /** Output: MembershipSample types */ - typedef MembershipSample< TInputSample > OutputType ; - typedef typename OutputType::Pointer OutputPointer ; + typedef MembershipSample< TInputSample > OutputType; + typedef typename OutputType::Pointer OutputPointer; /** Stores the input sample */ - void SetInput(const TInputSample* sample) ; + void SetInput(const TInputSample* sample); /** Returns the input sample pointer */ const TInputSample* GetInput() const; /** Stores the class mask sample */ - void SetClassMask(const TClassMaskSample* classMask) ; + void SetClassMask(const TClassMaskSample* classMask); - /** Returns the class mask sample pointer*/ + /** Returns the class mask sample pointer */ const TClassMaskSample* GetClassMask() const; - void SetNumberOfClasses(int numberOfClasses) ; + void SetNumberOfClasses(int numberOfClasses); - int GetNumberOfClasses() ; + int GetNumberOfClasses(); /** Returns the pointer to the MembershipSample object * that has been generated by this */ const OutputType * GetOutput() const; /** The actual output generation procedure. */ - void GenerateData() ; + void GenerateData(); protected: - MembershipSampleGenerator() ; + MembershipSampleGenerator(); virtual ~MembershipSampleGenerator() {} void PrintSelf(std::ostream& os, Indent indent) const; private: - typename TInputSample::ConstPointer m_Input ; - typename TClassMaskSample::ConstPointer m_ClassMask ; - int m_NumberOfClasses ; - OutputPointer m_Output ; -} ; // end of class + typename TInputSample::ConstPointer m_Input; + typename TClassMaskSample::ConstPointer m_ClassMask; + int m_NumberOfClasses; + OutputPointer m_Output; +}; // end of class - } // end namespace Statistics +} // end namespace Statistics } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSampleGenerator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSampleGenerator.txx index 4b246a7da8..a6a20f4c4f 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSampleGenerator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMembershipSampleGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMembershipSampleGenerator.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:04 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-04 15:24:02 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,16 +17,16 @@ #ifndef __itkMembershipSampleGenerator_txx #define __itkMembershipSampleGenerator_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TInputSample, class TClassMaskSample > MembershipSampleGenerator< TInputSample, TClassMaskSample > ::MembershipSampleGenerator() { - m_Input = 0 ; - m_ClassMask = 0 ; - m_Output = OutputType::New() ; + m_Input = 0; + m_ClassMask = 0; + m_Output = OutputType::New(); } template< class TInputSample, class TClassMaskSample > @@ -36,24 +36,24 @@ MembershipSampleGenerator< TInputSample, TClassMaskSample > { Superclass::PrintSelf(os,indent); - os << indent << "Input: " ; + os << indent << "Input: "; if ( m_Input.IsNotNull() ) { - os << m_Input << std::endl ; + os << m_Input << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "ClassMask: " ; + os << indent << "ClassMask: "; if ( m_ClassMask.IsNotNull() ) { - os << m_ClassMask << std::endl ; + os << m_ClassMask << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } os << indent << "Output: " << m_Output << std::endl; @@ -70,7 +70,7 @@ MembershipSampleGenerator< TInputSample, TClassMaskSample > itkExceptionMacro( << "Measurement vector length of input sample must be non-zero."); } - m_Input = sample ; + m_Input = sample; } template< class TInputSample, class TClassMaskSample > @@ -78,7 +78,7 @@ const TInputSample* MembershipSampleGenerator< TInputSample, TClassMaskSample > ::GetInput() const { - return m_Input ; + return m_Input; } template< class TInputSample, class TClassMaskSample > @@ -92,7 +92,7 @@ MembershipSampleGenerator< TInputSample, TClassMaskSample > itkExceptionMacro( << "Class mask measurement vector length of input sample must be 1."); } - m_ClassMask = classMask ; + m_ClassMask = classMask; } template< class TInputSample, class TClassMaskSample > @@ -100,7 +100,7 @@ const TClassMaskSample* MembershipSampleGenerator< TInputSample, TClassMaskSample > ::GetClassMask() const { - return m_ClassMask ; + return m_ClassMask; } template< class TInputSample, class TClassMaskSample > @@ -108,7 +108,7 @@ void MembershipSampleGenerator< TInputSample, TClassMaskSample > ::SetNumberOfClasses(int numberOfClasses) { - m_NumberOfClasses = numberOfClasses ; + m_NumberOfClasses = numberOfClasses; } template< class TInputSample, class TClassMaskSample > @@ -116,7 +116,7 @@ int MembershipSampleGenerator< TInputSample, TClassMaskSample > ::GetNumberOfClasses() { - return m_NumberOfClasses ; + return m_NumberOfClasses; } @@ -125,7 +125,7 @@ const typename MembershipSampleGenerator< TInputSample, TClassMaskSample >::Outp MembershipSampleGenerator< TInputSample, TClassMaskSample > ::GetOutput() const { - return m_Output ; + return m_Output; } template< class TInputSample, class TClassMaskSample > @@ -133,15 +133,15 @@ void MembershipSampleGenerator< TInputSample, TClassMaskSample > ::GenerateData() { - unsigned int classLabel ; - m_Output->SetSample(m_Input) ; - m_Output->SetNumberOfClasses(m_NumberOfClasses) ; - typename TClassMaskSample::ConstIterator iter = m_ClassMask->Begin() ; + unsigned int classLabel; + m_Output->SetSample(m_Input); + m_Output->SetNumberOfClasses(m_NumberOfClasses); + typename TClassMaskSample::ConstIterator iter = m_ClassMask->Begin(); while (iter != m_ClassMask->End()) { - classLabel = iter.GetMeasurementVector()[0] ; - m_Output->AddInstance(classLabel, iter.GetInstanceIdentifier()) ; - ++iter ; + classLabel = iter.GetMeasurementVector()[0]; + m_Output->AddInstance(classLabel, iter.GetInstanceIdentifier()); + ++iter; } } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMixtureModelComponentBase.h b/Utilities/ITK/Code/Numerics/Statistics/itkMixtureModelComponentBase.h index f0991f2313..26f916908d 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMixtureModelComponentBase.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMixtureModelComponentBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMixtureModelComponentBase.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:04 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-04 15:24:02 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,8 +24,8 @@ #include "itkObject.h" #include "itkMembershipFunctionBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class MixtureModelComponentBase * \brief base class for distribution modules that supports analytical way @@ -56,28 +56,28 @@ class MixtureModelComponentBase : public: /**Standard class typedefs. */ typedef MixtureModelComponentBase Self; - typedef Object Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /**Standard Macros */ itkTypeMacro(MixtureModelComponentBase, Object); - itkNewMacro(Self) ; + itkNewMacro(Self); - typedef typename TSample::MeasurementVectorType MeasurementVectorType ; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; /** typedef for the MembershipFunctionBase */ typedef MembershipFunctionBase< MeasurementVectorType > - MembershipFunctionType ; + MembershipFunctionType; /** typedef of strorage for the weights */ - typedef Array< double > WeightArrayType ; + typedef Array< double > WeightArrayType; - typedef Array< double > ParametersType ; + typedef Array< double > ParametersType; /** stores the sample pointer */ - virtual void SetSample(const TSample* sample) ; + virtual void SetSample(const TSample* sample); /** returns the sample pointer */ const TSample* GetSample() const; @@ -86,72 +86,72 @@ public: * Subclasses of this class are responsible for creating the * actual membership function objects and cast them to * MembershipFunctionBase objects */ - MembershipFunctionType* GetMembershipFunction() ; + MembershipFunctionType* GetMembershipFunction(); void SetMinimalParametersChange(double change) - { m_MinimalParametersChange = change ; } + { m_MinimalParametersChange = change; } double GetMinimalParametersChange() - { return m_MinimalParametersChange ; } + { return m_MinimalParametersChange; } - virtual void SetParameters(const ParametersType ¶meters) ; + virtual void SetParameters(const ParametersType ¶meters); virtual ParametersType GetFullParameters() - { return m_Parameters ; } + { return m_Parameters; } /** sets the parameters modified tag. if one or more of the membership * funtion's parameters are changed, then flag should be true */ - void AreParametersModified(bool flag) ; + void AreParametersModified(bool flag); /** returns the value of parameter modified tag */ - bool AreParametersModified() ; + bool AreParametersModified(); /** sets the index-th weight with the "value" */ - void SetWeight(int index, double value) ; + void SetWeight(int index, double value); /** returns the index-th weight */ - double GetWeight(int index) ; + double GetWeight(int index); /** returns the membership score of the "measurements" vector */ - double Evaluate(MeasurementVectorType& measurements) ; + double Evaluate(MeasurementVectorType& measurements); /** returns the pointer to the weights array */ - WeightArrayType* GetWeights() ; + WeightArrayType* GetWeights(); - virtual void Update() ; + virtual void Update(); protected: - MixtureModelComponentBase() ; - virtual ~MixtureModelComponentBase() ; + MixtureModelComponentBase(); + virtual ~MixtureModelComponentBase(); void PrintSelf(std::ostream& os, Indent indent) const; /** allocates the weights array */ - void CreateWeightArray() ; + void CreateWeightArray(); /** deallocates the weights array */ - void DeleteWeightArray() ; + void DeleteWeightArray(); /** stores the pointer to the membership function. * subclasses use this funtion to store their membership function * object after dynamic creation */ - void SetMembershipFunction(MembershipFunctionType* function) ; + void SetMembershipFunction(MembershipFunctionType* function); - virtual void GenerateData() ; + virtual void GenerateData(); private: /** target sample data pointer */ - const TSample* m_Sample ; + const TSample* m_Sample; - double m_MinimalParametersChange ; + double m_MinimalParametersChange; - ParametersType m_Parameters ; + ParametersType m_Parameters; /** SmartPointer to the memberhip function - usually density function */ - MembershipFunctionType* m_MembershipFunction ; + MembershipFunctionType* m_MembershipFunction; /** weights array */ - WeightArrayType* m_Weights ; + WeightArrayType* m_Weights; /** indicative flag of membership function's parameter changes */ - bool m_ParametersModified ; + bool m_ParametersModified; -} ; // end of class +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -161,4 +161,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkMixtureModelComponentBase.txx b/Utilities/ITK/Code/Numerics/Statistics/itkMixtureModelComponentBase.txx index 5409d44fa7..9c4fd2bc81 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkMixtureModelComponentBase.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkMixtureModelComponentBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMixtureModelComponentBase.txx,v $ Language: C++ - Date: $Date: 2003-12-15 01:00:46 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-04 15:24:03 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,18 +19,18 @@ #include "itkMixtureModelComponentBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > MixtureModelComponentBase< TSample > ::MixtureModelComponentBase() { - m_Sample = 0 ; - m_MembershipFunction = 0 ; - m_Weights = 0 ; - m_MinimalParametersChange = 1.0e-06 ; - m_ParametersModified = true ; + m_Sample = 0; + m_MembershipFunction = 0; + m_Weights = 0; + m_MinimalParametersChange = 1.0e-06; + m_ParametersModified = true; } template< class TSample > @@ -39,8 +39,8 @@ MixtureModelComponentBase< TSample > { if ( m_Weights != 0 ) { - delete m_Weights ; - m_Weights = 0 ; + delete m_Weights; + m_Weights = 0; } } @@ -51,34 +51,34 @@ MixtureModelComponentBase< TSample > { Superclass::PrintSelf(os,indent); - os << indent << "Sample: " ; + os << indent << "Sample: "; if ( m_Sample != 0 ) { os << m_Sample << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "Membership Function: " ; + os << indent << "Membership Function: "; if ( m_MembershipFunction != 0 ) { os << m_MembershipFunction << std::endl; } else { - os << "not instantiated yet." << std::endl ; + os << "not instantiated yet." << std::endl; } - os << indent << "Weights Array: " ; + os << indent << "Weights Array: "; if ( m_Weights != 0 ) { os << m_Weights << std::endl; } else { - os << "not allocated yet." << std::endl ; + os << "not allocated yet." << std::endl; } os << indent << "Parameters are modified: " << m_ParametersModified @@ -90,8 +90,8 @@ void MixtureModelComponentBase< TSample > ::SetSample(const TSample* sample) { - m_Sample = sample ; - this->CreateWeightArray() ; + m_Sample = sample; + this->CreateWeightArray(); } template< class TSample > @@ -99,7 +99,7 @@ const TSample* MixtureModelComponentBase< TSample > ::GetSample() const { - return m_Sample ; + return m_Sample; } template< class TSample > @@ -109,8 +109,8 @@ MixtureModelComponentBase< TSample > { if ( m_Parameters != parameters ) { - m_Parameters = parameters ; - this->AreParametersModified(true) ; + m_Parameters = parameters; + this->AreParametersModified(true); } } @@ -119,7 +119,7 @@ bool MixtureModelComponentBase< TSample > ::AreParametersModified() { - return m_ParametersModified ; + return m_ParametersModified; } template< class TSample > @@ -135,7 +135,7 @@ typename MixtureModelComponentBase< TSample >::WeightArrayType* MixtureModelComponentBase< TSample > ::GetWeights() { - return m_Weights ; + return m_Weights; } template< class TSample > @@ -145,8 +145,8 @@ MixtureModelComponentBase< TSample > { if ( m_Weights != 0 ) { - delete m_Weights ; - m_Weights = 0 ; + delete m_Weights; + m_Weights = 0; } m_Weights = new WeightArrayType(m_Sample->Size()); @@ -159,7 +159,7 @@ MixtureModelComponentBase< TSample > { if ( m_Weights != 0 ) { - delete m_Weights ; + delete m_Weights; } } @@ -168,7 +168,7 @@ void MixtureModelComponentBase< TSample > ::SetMembershipFunction(MembershipFunctionType* function) { - m_MembershipFunction = function ; + m_MembershipFunction = function; } template< class TSample > @@ -176,7 +176,7 @@ typename MixtureModelComponentBase< TSample >::MembershipFunctionType* MixtureModelComponentBase< TSample > ::GetMembershipFunction() { - return m_MembershipFunction ; + return m_MembershipFunction; } template< class TSample > @@ -184,7 +184,7 @@ inline double MixtureModelComponentBase< TSample > ::Evaluate(MeasurementVectorType& measurements) { - return m_MembershipFunction->Evaluate(measurements) ; + return m_MembershipFunction->Evaluate(measurements); } template< class TSample > @@ -194,11 +194,11 @@ MixtureModelComponentBase< TSample > { if ( m_Weights != 0 ) { - (*m_Weights)[index] = value ; + (*m_Weights)[index] = value; } else { - itkExceptionMacro("Weight array is not allocated.") ; + itkExceptionMacro("Weight array is not allocated."); } } @@ -209,11 +209,11 @@ MixtureModelComponentBase< TSample > { if ( m_Weights != 0 ) { - return (*m_Weights)[index] ; + return (*m_Weights)[index]; } else { - itkExceptionMacro("Weight array is not allocated.") ; + itkExceptionMacro("Weight array is not allocated."); } } @@ -222,7 +222,7 @@ void MixtureModelComponentBase< TSample > ::Update() { - this->GenerateData() ; + this->GenerateData(); } template< class TSample > @@ -238,4 +238,3 @@ MixtureModelComponentBase< TSample > } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkNeighborhoodSampler.h b/Utilities/ITK/Code/Numerics/Statistics/itkNeighborhoodSampler.h index 2ae7e1ee49..99b7193795 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkNeighborhoodSampler.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkNeighborhoodSampler.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNeighborhoodSampler.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:04 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-04 15:24:04 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,8 +24,8 @@ #include "itkArray.h" #include "itkSampleAlgorithmBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class NeighborhoodSampler * \brief generates a Subsample that is sampled from the input sample @@ -49,42 +49,42 @@ class ITK_EXPORT NeighborhoodSampler : public SampleAlgorithmBase< TSample > { public: /** Standard class typedefs */ - typedef NeighborhoodSampler Self ; - typedef SampleAlgorithmBase< TSample > Superclass ; - typedef SmartPointer< Self > Pointer ; - typedef SmartPointer< const Self > ConstPointer ; + typedef NeighborhoodSampler Self; + typedef SampleAlgorithmBase< TSample > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; /** Run-time type information (and related methods) */ itkTypeMacro(NeighborhoodSampler, SampleAlgorithmBase); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** MeasurementVector typedef support */ - typedef TSample SampleType ; + typedef TSample SampleType; /** Enums and typedefs from the TSample */ - typedef typename TSample::MeasurementVectorType MeasurementVectorType ; - typedef typename TSample::MeasurementType MeasurementType ; - typedef typename TSample::FrequencyType FrequencyType ; - typedef typename TSample::InstanceIdentifier InstanceIdentifier ; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::FrequencyType FrequencyType; + typedef typename TSample::InstanceIdentifier InstanceIdentifier; /** typedefs from the superclass */ - typedef typename Superclass::InputSampleType InputSampleType ; + typedef typename Superclass::InputSampleType InputSampleType; /** Type of the output subsample object */ - typedef Subsample< TSample > SubsampleType ; + typedef Subsample< TSample > SubsampleType; /** Type of the array of the radii */ - typedef double RadiusType ; + typedef double RadiusType; /** Type of the array of the radii */ typedef Array< double > CenterType; /** Sets the center of the spherical kernel */ void SetCenter(CenterType* center) - { + { if( this->GetMeasurementVectorSize() && ( center->Size() != this->GetMeasurementVectorSize() ) ) { @@ -95,53 +95,53 @@ public: if ( m_Center != center ) { - m_Center = center ; - this->Modified() ; + m_Center = center; + this->Modified(); } - } + } /** Gets the center */ CenterType* GetCenter() - { return m_Center ; } + { return m_Center; } /** Sets the radius of the kernel */ void SetRadius(RadiusType* radius) - { + { if ( m_Radius != radius ) { - m_Radius = radius ; - this->Modified() ; + m_Radius = radius; + this->Modified(); } - } + } /** Gets the radius */ RadiusType* GetRadius() - { return m_Radius ; } + { return m_Radius; } /** Output of this algorithm */ - typedef SubsampleType OutputType ; + typedef SubsampleType OutputType; /** Output of this algorithm */ - typedef typename SubsampleType::Pointer OutputPointer ; + typedef typename SubsampleType::Pointer OutputPointer; /** Gets the Subsample */ - OutputPointer GetOutput() ; + OutputPointer GetOutput(); protected: - NeighborhoodSampler() ; + NeighborhoodSampler(); virtual ~NeighborhoodSampler() {} - virtual void PrintSelf(std::ostream& os, Indent indent) const ; + virtual void PrintSelf(std::ostream& os, Indent indent) const; - void GenerateData() ; + void GenerateData(); private: - NeighborhoodSampler(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + NeighborhoodSampler(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - CenterType* m_Center ; - RadiusType* m_Radius ; - typename SubsampleType::Pointer m_Subsample ; -} ; // end of class + CenterType* m_Center; + RadiusType* m_Radius; + typename SubsampleType::Pointer m_Subsample; +}; // end of class } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkNeighborhoodSampler.txx b/Utilities/ITK/Code/Numerics/Statistics/itkNeighborhoodSampler.txx index 798d694723..8fecd879c1 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkNeighborhoodSampler.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkNeighborhoodSampler.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNeighborhoodSampler.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:04 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-04 15:24:04 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,16 +20,16 @@ #include "itkNeighborhoodSampler.h" #include "vnl/vnl_math.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > NeighborhoodSampler< TSample > ::NeighborhoodSampler() { - m_Center = 0 ; - m_Radius = 0 ; - m_Subsample = SubsampleType::New() ; + m_Center = 0; + m_Radius = 0; + m_Subsample = SubsampleType::New(); } template< class TSample > @@ -37,30 +37,30 @@ void NeighborhoodSampler< TSample > ::PrintSelf(std::ostream& os, Indent indent) const { - Superclass::PrintSelf(os,indent) ; + Superclass::PrintSelf(os,indent); - os << indent << "Center: " ; + os << indent << "Center: "; if ( m_Center != 0 ) { os << (*m_Center) << std::endl; } else { - os << "not set. " << std::endl ; + os << "not set. " << std::endl; } - os << indent << "Radius: " ; + os << indent << "Radius: "; if ( m_Radius != 0 ) { os << (*m_Radius) << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } os << indent << "Output " << m_Subsample << std::endl; - os << indent << "Output Size " << m_Subsample->Size() << std::endl ; + os << indent << "Output Size " << m_Subsample->Size() << std::endl; } template< class TSample > @@ -68,7 +68,7 @@ typename NeighborhoodSampler< TSample >::OutputPointer NeighborhoodSampler< TSample > ::GetOutput() { - return m_Subsample ; + return m_Subsample; } template< class TSample > @@ -78,7 +78,7 @@ NeighborhoodSampler< TSample > { if (m_Radius == 0 || m_Center == 0 || this->GetInputSample() == 0) { - itkExceptionMacro("Member variables have not been properly set.") ; + itkExceptionMacro("Member variables have not been properly set."); } // Assert at run time that the given center has the same length as @@ -91,44 +91,44 @@ NeighborhoodSampler< TSample > m_Center->Size() ); } - m_Subsample->SetSample(this->GetInputSample()) ; + m_Subsample->SetSample(this->GetInputSample()); - unsigned int j ; - double squaredRadius ; - double distance ; - double coordinateDistance ; - MeasurementVectorType tempVector ; + unsigned int j; + double squaredRadius; + double distance; + double coordinateDistance; + MeasurementVectorType tempVector; - squaredRadius = (*m_Radius) * (*m_Radius) ; + squaredRadius = (*m_Radius) * (*m_Radius); - m_Subsample->Clear() ; - typename TSample::ConstIterator iter = this->GetInputSample()->Begin() ; - typename TSample::ConstIterator last = this->GetInputSample()->End() ; + m_Subsample->Clear(); + typename TSample::ConstIterator iter = this->GetInputSample()->Begin(); + typename TSample::ConstIterator last = this->GetInputSample()->End(); while (iter != last) { - distance = 0.0 ; - tempVector = iter.GetMeasurementVector() ; - for (j = 0 ; j < this->GetMeasurementVectorSize() && distance < squaredRadius ; j++) + distance = 0.0; + tempVector = iter.GetMeasurementVector(); + for (j = 0; j < this->GetMeasurementVectorSize() && distance < squaredRadius; j++) { - coordinateDistance = (double)tempVector[j] - (*m_Center)[j] ; + coordinateDistance = (double)tempVector[j] - (*m_Center)[j]; if (vnl_math_abs(coordinateDistance) > (*m_Radius) ) { - distance = squaredRadius ; + distance = squaredRadius; } } - for (j = 0 ; j < this->GetMeasurementVectorSize() - && distance < squaredRadius ; j++) + for (j = 0; j < this->GetMeasurementVectorSize() + && distance < squaredRadius; j++) { - coordinateDistance = (double)tempVector[j] - (*m_Center)[j] ; - distance += coordinateDistance * coordinateDistance ; + coordinateDistance = (double)tempVector[j] - (*m_Center)[j]; + distance += coordinateDistance * coordinateDistance; } if (distance < squaredRadius) { - m_Subsample->AddInstance(iter.GetInstanceIdentifier()) ; + m_Subsample->AddInstance(iter.GetInstanceIdentifier()); } - ++iter ; + ++iter; } } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkNormalVariateGenerator.cxx b/Utilities/ITK/Code/Numerics/Statistics/itkNormalVariateGenerator.cxx index 396a6d1247..72d8925350 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkNormalVariateGenerator.cxx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkNormalVariateGenerator.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNormalVariateGenerator.cxx,v $ Language: C++ - Date: $Date: 2006-03-19 04:37:20 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-04 15:24:04 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,59 +24,59 @@ namespace Statistics { NormalVariateGenerator::NormalVariateGenerator() { - Scale = ((double) 30000000.0) ; - Rscale = ((double) (1.0 / Scale)) ; - Rcons = ((double) (1.0 / (2.0 * 1024.0 * 1024.0 * 1024.0))) ; - ELEN = 7 ; /* LEN must be 2 ** ELEN */ - LEN = 128 ; - LMASK = (4 * (LEN-1)) ; - TLEN = (8*LEN) ; - vec1 = new int[TLEN] ; - - gausssave = 0 ; - this->Initialize(0) ; + Scale = ((double) 30000000.0); + Rscale = ((double) (1.0 / Scale)); + Rcons = ((double) (1.0 / (2.0 * 1024.0 * 1024.0 * 1024.0))); + ELEN = 7; /* LEN must be 2 ** ELEN */ + LEN = 128; + LMASK = (4 * (LEN-1)); + TLEN = (8*LEN); + vec1 = new int[TLEN]; + + gausssave = 0; + this->Initialize(0); } NormalVariateGenerator::~NormalVariateGenerator() { - delete[] vec1 ; + delete[] vec1; } void NormalVariateGenerator::PrintSelf(std::ostream& os, Indent indent) const { - Superclass::PrintSelf(os, indent) ; - - os << indent << "Scale: " << Scale << std::endl ; - os << indent << "Rscale: " << Rscale << std::endl ; - os << indent << "Rcons: " << Rcons << std::endl ; - os << indent << "ELEN: " << ELEN << std::endl ; - os << indent << "LEN: " << LEN << std::endl ; - os << indent << "LMASK: " << LMASK << std::endl ; - os << indent << "TLEN: " << TLEN << std::endl ; + Superclass::PrintSelf(os, indent); + + os << indent << "Scale: " << Scale << std::endl; + os << indent << "Rscale: " << Rscale << std::endl; + os << indent << "Rcons: " << Rcons << std::endl; + os << indent << "ELEN: " << ELEN << std::endl; + os << indent << "LEN: " << LEN << std::endl; + os << indent << "LMASK: " << LMASK << std::endl; + os << indent << "TLEN: " << TLEN << std::endl; - os << indent << "gaussfaze: " << gaussfaze << std::endl ; - os << indent << "gausssave: " << gausssave << std::endl ; - os << indent << "GScale: " << GScale << std::endl ; + os << indent << "gaussfaze: " << gaussfaze << std::endl; + os << indent << "gausssave: " << gausssave << std::endl; + os << indent << "GScale: " << GScale << std::endl; - os << indent << "vec1: " << vec1 << std::endl ; - os << indent << "nslew: " << nslew << std::endl ; - os << indent << "irs: " << irs << std::endl ; - os << indent << "lseed: " << lseed << std::endl ; - os << indent << "chic1: " << chic1 << std::endl ; - os << indent << "chic2: " << chic2 << std::endl ; - os << indent << "actualRSD: " << actualRSD << std::endl ; + os << indent << "vec1: " << vec1 << std::endl; + os << indent << "nslew: " << nslew << std::endl; + os << indent << "irs: " << irs << std::endl; + os << indent << "lseed: " << lseed << std::endl; + os << indent << "chic1: " << chic1 << std::endl; + os << indent << "chic2: " << chic2 << std::endl; + os << indent << "actualRSD: " << actualRSD << std::endl; } void NormalVariateGenerator::Initialize(int randomSeed) { // m_Random Seed was originally getpid() - double fake ; - lseed = randomSeed ; - irs = randomSeed ; - gaussfaze = 1 ; - nslew = 0 ; - GScale = Rscale ; + double fake; + lseed = randomSeed; + irs = randomSeed; + gaussfaze = 1; + nslew = 0; + GScale = Rscale; // At one stage, we need to generate a random variable Z such that // (TLEN * Z*Z) has a Chi-squared-TLEN density. Now, a var with // an approximate Chi-sq-K distn can be got as @@ -93,7 +93,7 @@ void NormalVariateGenerator::Initialize(int randomSeed) chic2 = vcl_sqrt(2.0 * TLEN - fake*fake) / fake; chic1 = fake * vcl_sqrt(0.5 / TLEN); - actualRSD = 0.0 ; + actualRSD = 0.0; return; } @@ -101,9 +101,9 @@ void NormalVariateGenerator::Initialize(int randomSeed) double NormalVariateGenerator::GetVariate() { if (--gaussfaze) - return GScale * gausssave[gaussfaze] ; + return GScale * gausssave[gaussfaze]; else - return FastNorm() ; + return FastNorm(); } /* ----------------------------------------------------- */ @@ -164,49 +164,51 @@ double NormalVariateGenerator::FastNorm(void) /* Use last bits of nslew to determine scanning pattern */ stype = nslew & 3; - switch (stype) { - case 0: /* From consecutive in top to scattered in bot */ - inc = 1; - mask = LMASK; - pa = vec1; pb = pa + LEN; pc = pb + LEN; pd = pc + LEN; - p0 = vec1 + 4 * LEN; - goto scanset; - case 1: /* From consec in bot to scatt in top */ - inc = 1; - mask = LMASK; - pa = vec1 + 4 * LEN; pb = pa + LEN; pc = pb + LEN; pd = pc + LEN; - p0 = vec1; - goto scanset; - case 2: /* From consec in even to scatt in odd */ - inc = 2; - mask = 2*LMASK; skew *= 2; stride *= 2; - pa = vec1 + 1; pb = pa + 2*LEN; pc = pb + 2*LEN; pd = pc + 2*LEN; - p0 = vec1; - goto scanset; - case 3: /* From consec in odd to scatt in even */ - inc = 2; - mask = 2*LMASK; skew *= 2; stride *= 2; - pa = vec1; pb = pa + 2*LEN; pc = pb + 2*LEN; pd = pc + 2*LEN; - p0 = vec1 + 1; - goto scanset; - } /* End of scan pattern cases */ - - scanset: + switch (stype) + { + case 0: /* From consecutive in top to scattered in bot */ + inc = 1; + mask = LMASK; + pa = vec1; pb = pa + LEN; pc = pb + LEN; pd = pc + LEN; + p0 = vec1 + 4 * LEN; + goto scanset; + case 1: /* From consec in bot to scatt in top */ + inc = 1; + mask = LMASK; + pa = vec1 + 4 * LEN; pb = pa + LEN; pc = pb + LEN; pd = pc + LEN; + p0 = vec1; + goto scanset; + case 2: /* From consec in even to scatt in odd */ + inc = 2; + mask = 2*LMASK; skew *= 2; stride *= 2; + pa = vec1 + 1; pb = pa + 2*LEN; pc = pb + 2*LEN; pd = pc + 2*LEN; + p0 = vec1; + goto scanset; + case 3: /* From consec in odd to scatt in even */ + inc = 2; + mask = 2*LMASK; skew *= 2; stride *= 2; + pa = vec1; pb = pa + 2*LEN; pc = pb + 2*LEN; pd = pc + 2*LEN; + p0 = vec1 + 1; + goto scanset; + } /* End of scan pattern cases */ + +scanset: gausssave = vec1; /* Set loop count */ i = LEN; /* Use mtype to select matrix */ - switch (mtype) { - case 0: goto matrix0; - case 1: goto matrix1; - case 2: goto matrix2; - case 3: goto matrix3; - } - - matrix0: + switch (mtype) + { + case 0: goto matrix0; + case 1: goto matrix1; + case 2: goto matrix2; + case 3: goto matrix3; + } + +matrix0: pa += (inc * (LEN-1)); - mpass0: +mpass0: skew = (skew + stride) & mask; pe = p0 + skew; p = -*pa; q = -*pb; r = *pc; s = *pd; @@ -327,25 +329,27 @@ double NormalVariateGenerator::FastNorm(void) tz = -2.0 * vcl_log((r + 0.5) * Rcons); /* Sum of squares */ ts += tz; tz = vcl_sqrt(tz / tr ); - vec1 [p++] = (int) (Scale * tx * tz) ; - vec1 [p++] = (int) (Scale * ty * tz) ; + vec1 [p++] = (int) (Scale * tx * tz); + vec1 [p++] = (int) (Scale * ty * tz); if (p < TLEN) goto nextpair; /* Horrid, but good enough */ /* Calc correction factor to make sum of squares = TLEN */ ts = TLEN / ts; /* Should be close to 1.0 */ tr = vcl_sqrt(ts); - for (p = 0; p < TLEN; p++) { - tx = vec1 [p] * tr; - vec1 [p] = (int) ((tx < 0.0) ? (tx - 0.5) : (tx + 0.5)) ; - } + for (p = 0; p < TLEN; p++) + { + tx = vec1 [p] * tr; + vec1 [p] = (int) ((tx < 0.0) ? (tx - 0.5) : (tx + 0.5)); + } recalcsumsq: /* Calculate actual sum of squares for correction */ ts = 0.0; - for (p = 0; p < TLEN; p++) { - tx = vec1[p]; - ts += (tx * tx); - } + for (p = 0; p < TLEN; p++) + { + tx = vec1[p]; + ts += (tx * tx); + } /* Now ts should be Scale*Scale*TLEN or thereabouts */ ts = vcl_sqrt(ts / (Scale * Scale * TLEN)); actualRSD = 1.0 / ts; /* Reciprocal of actual Standard Devtn */ @@ -355,4 +359,3 @@ double NormalVariateGenerator::FastNorm(void) } // end of name space Statistics } // end of name space itk - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkNormalVariateGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkNormalVariateGenerator.h index 6db8dbbcec..472517cc06 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkNormalVariateGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkNormalVariateGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNormalVariateGenerator.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:47 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-04 15:24:04 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,7 +35,7 @@ namespace Statistics { * * The followings are original comments. * - * Revision date 31 May 1996 + * Revision date 31 May 1996 * This is a revised version of the algorithm decribed in * * ACM Transactions on Mathematical Software, Vol 22, No 1 @@ -50,7 +50,7 @@ namespace Statistics { * Has been tested for frequency of tail values which * should occur once in a million. OK. Other usual tests OK. * About 13 % faster than TOMS version. - * + * * FAST GENERATOR OF PSEUDO-RANDOM UNIT NORMAL VARIATES * * C.S.Wallace, Monash University, 1994 @@ -93,10 +93,10 @@ class ITK_EXPORT NormalVariateGenerator : { public: /** Standard class typedefs. */ - typedef NormalVariateGenerator Self ; + typedef NormalVariateGenerator Self; typedef RandomVariateGeneratorBase Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(NormalVariateGenerator, @@ -106,36 +106,36 @@ public: itkNewMacro(Self); /** generate random number table */ - void Initialize(int randomSeed) ; + void Initialize(int randomSeed); /** get a variate using FastNorm function */ - double GetVariate() ; + double GetVariate(); protected: - NormalVariateGenerator() ; - virtual ~NormalVariateGenerator() ; - virtual void PrintSelf(std::ostream& os, Indent indent) const ; + NormalVariateGenerator(); + virtual ~NormalVariateGenerator(); + virtual void PrintSelf(std::ostream& os, Indent indent) const; /** get a variate */ - double FastNorm (void) ; + double FastNorm (void); private: - double Scale ; - double Rscale ; - double Rcons ; - int ELEN ; - int LEN ; - int LMASK ; - int TLEN ; + double Scale; + double Rscale; + double Rcons; + int ELEN; + int LEN; + int LMASK; + int TLEN; int gaussfaze, *gausssave; double GScale; - int* vec1 ; + int* vec1; int nslew; int irs, lseed; double chic1, chic2, actualRSD; -} ; // end of class +}; // end of class } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkPointSetToListAdaptor.h b/Utilities/ITK/Code/Numerics/Statistics/itkPointSetToListAdaptor.h index 4db18514aa..dbc66c10e2 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkPointSetToListAdaptor.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkPointSetToListAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointSetToListAdaptor.h,v $ Language: C++ -Date: $Date: 2005-09-30 17:40:35 $ -Version: $Revision: 1.15 $ +Date: $Date: 2009-03-04 15:24:04 $ +Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,8 +23,8 @@ PURPOSE. See the above copyright notices for more information. #include "itkListSampleBase.h" #include "itkSmartPointer.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class PointSetToListAdaptor * \brief This class provides ListSampleBase interfaces to ITK PointSet @@ -45,47 +45,47 @@ class ITK_EXPORT PointSetToListAdaptor : { public: /** Standard class typedefs */ - typedef PointSetToListAdaptor Self; - typedef ListSampleBase< typename TPointSet::PointType > Superclass ; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef PointSetToListAdaptor Self; + typedef ListSampleBase< typename TPointSet::PointType > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(PointSetToListAdaptor, ListSampleBase) ; + itkTypeMacro(PointSetToListAdaptor, ListSampleBase); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** the number of components in a measurement vector */ itkStaticConstMacro(MeasurementVectorSize, unsigned int, TPointSet::PointDimension); /** PointSet typedefs */ - typedef TPointSet PointSetType; - typedef typename TPointSet::Pointer PointSetPointer ; - typedef typename TPointSet::PointIdentifier InstanceIdentifier; - typedef typename TPointSet::PointsContainerPointer PointsContainerPointer ; - typedef typename TPointSet::PointsContainerIterator PointsContainerIterator ; - typedef typename TPointSet::PointType PointType ; + typedef TPointSet PointSetType; + typedef typename TPointSet::Pointer PointSetPointer; + typedef typename TPointSet::PointIdentifier InstanceIdentifier; + typedef typename TPointSet::PointsContainerPointer PointsContainerPointer; + typedef typename TPointSet::PointsContainerIterator PointsContainerIterator; + typedef typename TPointSet::PointType PointType; /** Superclass typedefs for Measurement vector, measurement, * Instance Identifier, frequency, size, size element value */ - typedef typename Superclass::MeasurementType MeasurementType ; - typedef typename Superclass::MeasurementVectorType MeasurementVectorType; - typedef MeasurementVectorType ValueType ; - typedef typename Superclass::FrequencyType FrequencyType ; - typedef typename Superclass::TotalFrequencyType TotalFrequencyType ; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef MeasurementVectorType ValueType; + typedef typename Superclass::FrequencyType FrequencyType; + typedef typename Superclass::TotalFrequencyType TotalFrequencyType; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; /** Method to set the point set */ - void SetPointSet(TPointSet* pointSet) ; + void SetPointSet(TPointSet* pointSet); /** Method to get the point set */ - TPointSet* GetPointSet() ; + TPointSet* GetPointSet(); - /** returns the number of measurement vectors in this container*/ - unsigned int Size() const ; + /** returns the number of measurement vectors in this container */ + unsigned int Size() const; /** returns the measurement vector that is specified by the instance * identifier argument. */ @@ -95,13 +95,13 @@ public: * that is specified by "id". */ void SetMeasurement(const InstanceIdentifier &id, const unsigned int &dim, - const MeasurementType &value) ; + const MeasurementType &value); /** returns 1 as other subclasses of ListSampleBase does */ - FrequencyType GetFrequency(const InstanceIdentifier &id) const ; + FrequencyType GetFrequency(const InstanceIdentifier &id) const; /** returns the size of this container */ - TotalFrequencyType GetTotalFrequency() const ; + TotalFrequencyType GetTotalFrequency() const; void SetMeasurementVectorSize( const MeasurementVectorSizeType s ) { @@ -132,38 +132,38 @@ public: {} FrequencyType GetFrequency() const - { return 1 ;} + { return 1;} const MeasurementVectorType & GetMeasurementVector() const - { return (MeasurementVectorType&) m_Iter.Value() ;} + { return (MeasurementVectorType&) m_Iter.Value();} InstanceIdentifier GetInstanceIdentifier() const - { return m_Iter.Index() ;} + { return m_Iter.Index();} Iterator& operator++() - { ++m_Iter ; return *this ;} + { ++m_Iter; return *this;} Iterator& operator--() - { --m_Iter ; return *this ;} + { --m_Iter; return *this;} bool operator!=(const Iterator &it) - { return (m_Iter != it.m_Iter) ;} + { return (m_Iter != it.m_Iter);} bool operator==(const Iterator &it) - { return (m_Iter == it.m_Iter) ;} + { return (m_Iter == it.m_Iter);} Iterator& operator = (const Iterator &iter) { m_Iter = iter.m_Iter; - return iter ; + return iter; } Iterator(const Iterator &iter) { m_Iter = iter.m_Iter; } private: - PointsContainerIterator m_Iter ; - } ; + PointsContainerIterator m_Iter; + }; class ConstIterator @@ -177,66 +177,66 @@ public: {} FrequencyType GetFrequency() const - { return 1 ;} + { return 1;} const MeasurementVectorType & GetMeasurementVector() const - { return (MeasurementVectorType&) m_Iter.Value() ;} + { return (MeasurementVectorType&) m_Iter.Value();} InstanceIdentifier GetInstanceIdentifier() const - { return m_Iter.Index() ;} + { return m_Iter.Index();} ConstIterator& operator++() - { ++m_Iter ; return *this ;} + { ++m_Iter; return *this;} ConstIterator& operator--() - { --m_Iter ; return *this ;} + { --m_Iter; return *this;} bool operator!=(const ConstIterator &it) - { return (m_Iter != it.m_Iter) ;} + { return (m_Iter != it.m_Iter);} bool operator==(const ConstIterator &it) - { return (m_Iter == it.m_Iter) ;} + { return (m_Iter == it.m_Iter);} ConstIterator& operator = (const ConstIterator &iter) { m_Iter = iter.m_Iter; - return iter ; + return iter; } ConstIterator(const ConstIterator &iter) { m_Iter = iter.m_Iter; } private: - PointsContainerIterator m_Iter ; - } ; + PointsContainerIterator m_Iter; + }; /** returns an iterator that points to the beginning of the container */ Iterator Begin() - { + { Iterator iter(m_PointsContainer->Begin()); return iter; - } + } /** returns an iterator that points to the end of the container */ - Iterator End() - { + Iterator End() + { Iterator iter(m_PointsContainer->End()); return iter; - } + } /** returns a const iterator that points to the beginning of the container */ ConstIterator Begin() const - { + { ConstIterator iter(m_PointsContainer->Begin()); return iter; - } + } /** returns an iterator that points to the end of the container */ ConstIterator End() const - { + { ConstIterator iter(m_PointsContainer->End()); return iter; - } + } protected: PointSetToListAdaptor(); @@ -245,17 +245,17 @@ protected: void PrintSelf(std::ostream& os, Indent indent) const; private: - PointSetToListAdaptor(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + PointSetToListAdaptor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented /** the PointSet data source pointer */ - mutable PointSetPointer m_PointSet ; + mutable PointSetPointer m_PointSet; /** the points container which will be actually used for storing * measurement vectors */ - PointsContainerPointer m_PointsContainer ; + PointsContainerPointer m_PointsContainer; /** temporary points for conversions */ - mutable PointType m_TempPoint ; -} ; // end of class PointSetToListAdaptor + mutable PointType m_TempPoint; +}; // end of class PointSetToListAdaptor } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkPointSetToListAdaptor.txx b/Utilities/ITK/Code/Numerics/Statistics/itkPointSetToListAdaptor.txx index a95a2702a0..d52c1d85f7 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkPointSetToListAdaptor.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkPointSetToListAdaptor.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointSetToListAdaptor.txx,v $ Language: C++ -Date: $Date: 2005-09-30 14:14:18 $ -Version: $Revision: 1.12 $ +Date: $Date: 2009-03-04 15:24:04 $ +Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,13 +14,13 @@ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkPointSetToListAdaptor_txx -#define _itkPointSetToListAdaptor_txx +#ifndef __itkPointSetToListAdaptor_txx +#define __itkPointSetToListAdaptor_txx #include "itkPointSetToListAdaptor.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template < class TPointSet > PointSetToListAdaptor< TPointSet > @@ -37,14 +37,14 @@ PointSetToListAdaptor< TPointSet > { Superclass::PrintSelf(os,indent); - os << indent << "PointSet: " ; + os << indent << "PointSet: "; if ( m_PointSet.IsNotNull() ) { os << m_PointSet << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } } @@ -53,8 +53,8 @@ void PointSetToListAdaptor< TPointSet > ::SetPointSet(TPointSet* pointSet) { - m_PointSet = pointSet ; - m_PointsContainer = pointSet->GetPoints() ; + m_PointSet = pointSet; + m_PointsContainer = pointSet->GetPoints(); } template < class TPointSet > @@ -62,7 +62,7 @@ TPointSet* PointSetToListAdaptor< TPointSet > ::GetPointSet() { - return m_PointSet.GetPointer() ; + return m_PointSet.GetPointer(); } /** returns the number of measurement vectors in this container*/ @@ -71,7 +71,7 @@ unsigned int PointSetToListAdaptor< TPointSet > ::Size() const { - return m_PointsContainer->Size() ; + return m_PointsContainer->Size(); } template < class TPointSet > @@ -79,8 +79,8 @@ inline const typename PointSetToListAdaptor< TPointSet >::MeasurementVectorType PointSetToListAdaptor< TPointSet > ::GetMeasurementVector(const InstanceIdentifier &id) const { - m_PointSet->GetPoint(id, &m_TempPoint) ; - return (MeasurementVectorType&) m_TempPoint ; + m_PointSet->GetPoint(id, &m_TempPoint); + return (MeasurementVectorType&) m_TempPoint; } template < class TPointSet > @@ -88,7 +88,7 @@ inline typename PointSetToListAdaptor< TPointSet >::FrequencyType PointSetToListAdaptor< TPointSet > ::GetFrequency(const InstanceIdentifier &) const { - return 1 ; + return 1; } template < class TPointSet > @@ -96,13 +96,10 @@ typename PointSetToListAdaptor< TPointSet >::TotalFrequencyType PointSetToListAdaptor< TPointSet > ::GetTotalFrequency() const { - return this->Size() ; + return this->Size(); } } // end of namespace Statistics } // end of namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkProbabilityDistribution.h b/Utilities/ITK/Code/Numerics/Statistics/itkProbabilityDistribution.h index d831b44783..98e32d856b 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkProbabilityDistribution.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkProbabilityDistribution.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkProbabilityDistribution.h,v $ Language: C++ - Date: $Date: 2007-02-24 13:47:32 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-03-04 15:24:04 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -154,7 +154,7 @@ protected: { Superclass::PrintSelf(os,indent); os << indent << "Parameters: " << m_Parameters << std::endl; - }; + } ParametersType m_Parameters; diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkRandomVariateGeneratorBase.h b/Utilities/ITK/Code/Numerics/Statistics/itkRandomVariateGeneratorBase.h index 94edfd310a..511fb10223 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkRandomVariateGeneratorBase.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkRandomVariateGeneratorBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRandomVariateGeneratorBase.h,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:47 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-04 15:24:04 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef __itkRandomVariateGenerator_h -#define __itkRandomVariateGenerator_h +#ifndef __itkRandomVariateGeneratorBase_h +#define __itkRandomVariateGeneratorBase_h #include "itkObject.h" @@ -31,23 +31,23 @@ class ITK_EXPORT RandomVariateGeneratorBase : public Object { public: /** Standard class typedefs. */ - typedef RandomVariateGeneratorBase Self ; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef RandomVariateGeneratorBase Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(RandomVariateGeneratorBase, Object ); /** get a variate using FastNorm function */ - virtual double GetVariate() = 0 ; + virtual double GetVariate() = 0; protected: RandomVariateGeneratorBase() {} virtual ~RandomVariateGeneratorBase() {} private: -} ; // end of class +}; // end of class } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSample.h b/Utilities/ITK/Code/Numerics/Statistics/itkSample.h index 66ad27b019..f8f8191803 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSample.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSample.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSample.h,v $ Language: C++ - Date: $Date: 2006-02-21 18:53:18 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-03-04 19:29:53 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,8 +27,8 @@ #include "itkMeasurementVectorTraits.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class Sample * \brief A collection of measurements for statistical analysis @@ -64,49 +64,49 @@ class ITK_EXPORT Sample : public Object { public: /** Standard class typedefs */ - typedef Sample Self; - typedef Object Superclass ; - typedef SmartPointer< Self > Pointer ; + typedef Sample Self; + typedef Object Superclass; + typedef SmartPointer< Self > Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods) */ itkTypeMacro(Sample, Object); /** MeasurementVector typedef support */ - typedef TMeasurementVector MeasurementVectorType ; + typedef TMeasurementVector MeasurementVectorType; /** ValueType of a measurement (ValueType of a component of the * MeasurementVector */ typedef typename MeasurementVectorType::ValueType MeasurementType; - /** Frequency value type*/ - typedef float FrequencyType ; + /** Frequency value type */ + typedef float FrequencyType; - /** Total frequency type*/ - typedef NumericTraits<FrequencyType>::AccumulateType TotalFrequencyType ; + /** Total frequency type */ + typedef NumericTraits<FrequencyType>::AccumulateType TotalFrequencyType; /** InstanceIdentifier typedef. This identifier is a unique - * sequential id for each measurement vector in a Sample subclass.*/ - typedef unsigned long InstanceIdentifier ; + * sequential id for each measurement vector in a Sample subclass. */ + typedef unsigned long InstanceIdentifier; /** Typedef for the length of each measurement vector */ typedef unsigned int MeasurementVectorSizeType; /** Get the size of the sample (number of measurements) */ - virtual unsigned int Size() const = 0 ; + virtual unsigned int Size() const = 0; /** Get the measurement associated with a particular * InstanceIdentifier. */ virtual const MeasurementVectorType & - GetMeasurementVector(const InstanceIdentifier &id) const = 0 ; + GetMeasurementVector(const InstanceIdentifier &id) const = 0; /** Get the frequency of a measurement specified by instance * identifier. */ - virtual FrequencyType GetFrequency(const InstanceIdentifier &id) const = 0 ; + virtual FrequencyType GetFrequency(const InstanceIdentifier &id) const = 0; /** Get the total frequency of the sample. */ virtual TotalFrequencyType GetTotalFrequency() const - = 0 ; + = 0; /** Set/Get macros for the length of the measurement vector */ @@ -134,20 +134,20 @@ protected: virtual ~Sample() {} void PrintSelf(std::ostream& os, Indent indent) const - { + { Superclass::PrintSelf(os,indent); os << indent << "Length of measurement vectors in the sample: " << m_MeasurementVectorSize << std::endl; - } + } private: - Sample(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + Sample(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented MeasurementVectorSizeType m_MeasurementVectorSize; -} ; // end of class +}; // end of class } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleAlgorithmBase.h b/Utilities/ITK/Code/Numerics/Statistics/itkSampleAlgorithmBase.h index de9f07d0f2..98d04e9df3 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleAlgorithmBase.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleAlgorithmBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleAlgorithmBase.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:04 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-04 19:29:53 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,8 +26,8 @@ #include "itkObject.h" #include "itkMeasurementVectorTraits.h" -namespace itk{ - namespace Statistics{ +namespace itk { +namespace Statistics { /** \class SampleAlgorithmBase * \brief This class is a base class for algorithms that operate on Sample @@ -42,14 +42,14 @@ class ITK_EXPORT SampleAlgorithmBase : public Object { public: /**Standard class typedefs. */ - typedef SampleAlgorithmBase Self; - typedef Object Superclass ; - typedef SmartPointer< Self > Pointer; + typedef SampleAlgorithmBase Self; + typedef Object Superclass; + typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /**Standard Macros */ itkTypeMacro(SampleAlgorithmBase, Object); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Length of a measurement vector */ typedef unsigned int MeasurementVectorSizeType; @@ -60,14 +60,14 @@ public: /** Stores the sample pointer */ void SetInputSample( const TInputSample * sample ) - { + { if ( m_InputSample != sample ) { - m_InputSample = sample ; - m_MeasurementVectorSize = m_InputSample->GetMeasurementVectorSize(); - this->Modified() ; + m_InputSample = sample; + m_MeasurementVectorSize = m_InputSample->GetMeasurementVectorSize(); + this->Modified(); } - } + } /** Get Macro to get the length of a measurement vector. This is equal to @@ -78,31 +78,31 @@ public: itkSetMacro( MeasurementVectorSize, MeasurementVectorSizeType ) const TInputSample * GetInputSample() const - { return m_InputSample.GetPointer() ; } + { return m_InputSample.GetPointer(); } /** dummy function that calls the GenerateData() function to generate * output. It exists for future compatibility with ProcessObject * without streaming */ void Update() - { this->GenerateData() ; } + { this->GenerateData(); } protected: - SampleAlgorithmBase() ; + SampleAlgorithmBase(); virtual ~SampleAlgorithmBase() {} void PrintSelf(std::ostream& os, Indent indent) const; /** Calculates the mean and save it */ - virtual void GenerateData() ; + virtual void GenerateData(); private: /** Length of each measurement vector */ MeasurementVectorSizeType m_MeasurementVectorSize; /** Target sample data pointer */ - typename TInputSample::ConstPointer m_InputSample ; -} ; // end of class + typename TInputSample::ConstPointer m_InputSample; +}; // end of class - } // end of namespace Statistics +} // end of namespace Statistics } // end of namespace itk #ifndef ITK_MANUAL_INSTANTIATION @@ -110,4 +110,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleAlgorithmBase.txx b/Utilities/ITK/Code/Numerics/Statistics/itkSampleAlgorithmBase.txx index 99280d829c..5f25e29168 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleAlgorithmBase.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleAlgorithmBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleAlgorithmBase.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:04 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-04 19:29:53 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkSampleAlgorithmBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TInputSample > SampleAlgorithmBase< TInputSample > @@ -37,7 +37,7 @@ SampleAlgorithmBase< TInputSample > { Superclass::PrintSelf(os,indent); - os << indent << "Input Sample: " ; + os << indent << "Input Sample: "; if ( m_InputSample.IsNotNull() ) { os << m_InputSample << std::endl; @@ -45,7 +45,7 @@ SampleAlgorithmBase< TInputSample > } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } } @@ -63,4 +63,3 @@ SampleAlgorithmBase< TInputSample > } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifier.h b/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifier.h index abb0ae796e..26e6708cf5 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifier.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifier.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleClassifier.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:04 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-03-04 19:29:53 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,8 +25,8 @@ #include "itkMembershipSample.h" #include "itkClassifierBase.h" -namespace itk{ - namespace Statistics{ +namespace itk { +namespace Statistics { /** \class SampleClassifier * \brief Integration point for MembershipCalculator, DecisionRule, and @@ -74,32 +74,32 @@ class ITK_EXPORT SampleClassifier : public ClassifierBase< TSample > { public: - /** Standard class typedef*/ - typedef SampleClassifier Self; + /** Standard class typedefs */ + typedef SampleClassifier Self; typedef ClassifierBase< TSample > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard macros */ itkTypeMacro(SampleClassifier, Object); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Output type for GetClassSample method */ - typedef MembershipSample< TSample > OutputType ; + typedef MembershipSample< TSample > OutputType; /** typedefs from TSample object */ - typedef typename TSample::MeasurementType MeasurementType ; - typedef typename TSample::MeasurementVectorType MeasurementVectorType ; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; /** typedefs from Superclass */ typedef typename Superclass::MembershipFunctionPointerVector - MembershipFunctionPointerVector ; + MembershipFunctionPointerVector; - typedef unsigned int ClassLabelType ; - typedef std::vector< ClassLabelType > ClassLabelVectorType ; + typedef unsigned int ClassLabelType; + typedef std::vector< ClassLabelType > ClassLabelVectorType; /** Sets the target data that will be classified by this */ - void SetSample(const TSample* sample) ; + void SetSample(const TSample* sample); /** Returns the target data */ const TSample* GetSample() const; @@ -109,36 +109,36 @@ public: * this function, then the index of the membership function vector for a * membership function will be used as class label of measurement vectors * belong to the membership function */ - void SetMembershipFunctionClassLabels( ClassLabelVectorType& labels) ; + void SetMembershipFunctionClassLabels( ClassLabelVectorType& labels); /** Gets the user given class labels */ ClassLabelVectorType& GetMembershipFunctionClassLabels() - { return m_ClassLabels ; } + { return m_ClassLabels; } /** Returns the classification result */ - OutputType* GetOutput() ; + OutputType* GetOutput(); protected: - SampleClassifier() ; + SampleClassifier(); virtual ~SampleClassifier() {} void PrintSelf(std::ostream& os, Indent indent) const; /** Starts the classification process */ - void GenerateData() ; + void GenerateData(); private: - /** Target data sample pointer*/ - const TSample* m_Sample ; + /** Target data sample pointer */ + const TSample* m_Sample; /** Output pointer (MembershipSample) */ - typename OutputType::Pointer m_Output ; + typename OutputType::Pointer m_Output; /** User given class labels for membership functions */ - ClassLabelVectorType m_ClassLabels ; -} ; // end of class + ClassLabelVectorType m_ClassLabels; +}; // end of class - } // end of namespace Statistics +} // end of namespace Statistics } // end of namespace itk @@ -147,10 +147,3 @@ private: #endif #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifier.txx b/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifier.txx index 79104924aa..e393876cb6 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifier.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifier.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleClassifier.txx,v $ Language: C++ - Date: $Date: 2003-12-15 01:00:46 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-03-04 19:29:53 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,15 +19,15 @@ #include "itkSampleClassifier.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > SampleClassifier< TSample > ::SampleClassifier() { - m_Sample = 0 ; - m_Output = OutputType::New() ; + m_Sample = 0; + m_Output = OutputType::New(); } template< class TSample > @@ -37,14 +37,14 @@ SampleClassifier< TSample > { Superclass::PrintSelf(os,indent); - os << indent << "Sample: " ; + os << indent << "Sample: "; if ( m_Sample != 0 ) { os << m_Sample << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } os << indent << "Output: " << m_Output << std::endl; @@ -57,8 +57,8 @@ SampleClassifier< TSample > { if ( m_Sample != sample ) { - m_Sample = sample ; - m_Output->SetSample(sample) ; + m_Sample = sample; + m_Output->SetSample(sample); } } @@ -67,7 +67,7 @@ const TSample* SampleClassifier< TSample > ::GetSample() const { - return m_Sample ; + return m_Sample; } template< class TSample > @@ -75,7 +75,7 @@ void SampleClassifier< TSample > ::SetMembershipFunctionClassLabels(ClassLabelVectorType& labels) { - m_ClassLabels = labels ; + m_ClassLabels = labels; } template< class TSample > @@ -83,49 +83,49 @@ void SampleClassifier< TSample > ::GenerateData() { - unsigned int i ; - typename TSample::ConstIterator iter = this->GetSample()->Begin() ; - typename TSample::ConstIterator end = this->GetSample()->End() ; - typename TSample::MeasurementVectorType measurements ; - - m_Output->Resize( this->GetSample()->Size() ) ; - std::vector< double > discriminantScores ; - unsigned int numberOfClasses = this->GetNumberOfClasses() ; - discriminantScores.resize(numberOfClasses) ; - unsigned int classLabel ; - m_Output->SetNumberOfClasses(numberOfClasses) ; + unsigned int i; + typename TSample::ConstIterator iter = this->GetSample()->Begin(); + typename TSample::ConstIterator end = this->GetSample()->End(); + typename TSample::MeasurementVectorType measurements; + + m_Output->Resize( this->GetSample()->Size() ); + std::vector< double > discriminantScores; + unsigned int numberOfClasses = this->GetNumberOfClasses(); + discriminantScores.resize(numberOfClasses); + unsigned int classLabel; + m_Output->SetNumberOfClasses(numberOfClasses); typename Superclass::DecisionRuleType::Pointer rule = - this->GetDecisionRule() ; + this->GetDecisionRule(); if ( m_ClassLabels.size() != this->GetNumberOfMembershipFunctions() ) { while (iter != end) { - measurements = iter.GetMeasurementVector() ; - for (i = 0 ; i < numberOfClasses ; i++) + measurements = iter.GetMeasurementVector(); + for (i = 0; i < numberOfClasses; i++) { discriminantScores[i] = - (this->GetMembershipFunction(i))->Evaluate(measurements) ; + (this->GetMembershipFunction(i))->Evaluate(measurements); } - classLabel = rule->Evaluate(discriminantScores) ; - m_Output->AddInstance(classLabel, iter.GetInstanceIdentifier()) ; - ++iter ; + classLabel = rule->Evaluate(discriminantScores); + m_Output->AddInstance(classLabel, iter.GetInstanceIdentifier()); + ++iter; } } else { while (iter != end) { - measurements = iter.GetMeasurementVector() ; - for (i = 0 ; i < numberOfClasses ; i++) + measurements = iter.GetMeasurementVector(); + for (i = 0; i < numberOfClasses; i++) { discriminantScores[i] = - (this->GetMembershipFunction(i))->Evaluate(measurements) ; + (this->GetMembershipFunction(i))->Evaluate(measurements); } - classLabel = rule->Evaluate(discriminantScores) ; + classLabel = rule->Evaluate(discriminantScores); m_Output->AddInstance(m_ClassLabels[classLabel], - iter.GetInstanceIdentifier()) ; - ++iter ; + iter.GetInstanceIdentifier()); + ++iter; } } } @@ -135,18 +135,10 @@ typename SampleClassifier< TSample >::OutputType* SampleClassifier< TSample > ::GetOutput() { - return m_Output ; + return m_Output; } } // end of namespace Statistics } // end of namespace itk #endif - - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifierWithMask.h b/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifierWithMask.h index be034928b3..ade7213542 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifierWithMask.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifierWithMask.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleClassifierWithMask.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:04 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,8 +25,8 @@ #include "itkMembershipSample.h" #include "itkSampleClassifier.h" -namespace itk{ - namespace Statistics{ +namespace itk { +namespace Statistics { /** \class SampleClassifierWithMask * \brief Integration point for MembershipCalculator, DecisionRule, and @@ -61,58 +61,57 @@ class ITK_EXPORT SampleClassifierWithMask : public SampleClassifier< TSample > { public: - /** Standard class typedef*/ - typedef SampleClassifierWithMask Self; + /** Standard class typedefs */ + typedef SampleClassifierWithMask Self; typedef SampleClassifier< TSample > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard macros */ itkTypeMacro(SampleClassifierWithMask, SampleClassifier); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Superclass typedefs */ - typedef typename Superclass::OutputType OutputType ; - typedef typename Superclass::ClassLabelType ClassLabelType ; - typedef typename Superclass::ClassLabelVectorType ClassLabelVectorType ; + typedef typename Superclass::OutputType OutputType; + typedef typename Superclass::ClassLabelType ClassLabelType; + typedef typename Superclass::ClassLabelVectorType ClassLabelVectorType; /** typedefs from TSample object */ - typedef typename TSample::MeasurementType MeasurementType ; - typedef typename TSample::MeasurementVectorType MeasurementVectorType ; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; /** typedefs from Superclass */ typedef typename Superclass::MembershipFunctionPointerVector - MembershipFunctionPointerVector ; + MembershipFunctionPointerVector; - void SetMask( TMaskSample* mask ) ; + void SetMask( TMaskSample* mask ); TMaskSample* GetMask() - { return m_Mask.GetPointer() ; } + { return m_Mask.GetPointer(); } void SetSelectedClassLabels( ClassLabelVectorType& labels) - { m_SelectedClassLabels = labels ; } + { m_SelectedClassLabels = labels; } void SetOtherClassLabel( ClassLabelType label) - { m_OtherClassLabel = label ; } + { m_OtherClassLabel = label; } protected: - SampleClassifierWithMask() ; + SampleClassifierWithMask(); virtual ~SampleClassifierWithMask() {} void PrintSelf(std::ostream& os, Indent indent) const; /** Starts the classification process */ - void GenerateData() ; + void GenerateData(); private: /** Mask sample pointer*/ - typename TMaskSample::Pointer m_Mask ; - ClassLabelVectorType m_SelectedClassLabels ; - ClassLabelType m_OtherClassLabel ; -} ; // end of class + typename TMaskSample::Pointer m_Mask; + ClassLabelVectorType m_SelectedClassLabels; + ClassLabelType m_OtherClassLabel; +}; // end of class - - } // end of namespace Statistics +} // end of namespace Statistics } // end of namespace itk @@ -121,10 +120,3 @@ private: #endif #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifierWithMask.txx b/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifierWithMask.txx index dbfb25a89e..1f794f7732 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifierWithMask.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleClassifierWithMask.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleClassifierWithMask.txx,v $ Language: C++ - Date: $Date: 2004-09-09 22:29:49 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,15 +19,15 @@ #include "itkSampleClassifierWithMask.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample, class TMaskSample > SampleClassifierWithMask< TSample, TMaskSample > ::SampleClassifierWithMask() { - m_OtherClassLabel = 0 ; - m_Mask = 0 ; + m_OtherClassLabel = 0; + m_Mask = 0; } template< class TSample, class TMaskSample > @@ -37,23 +37,23 @@ SampleClassifierWithMask< TSample, TMaskSample > { Superclass::PrintSelf(os,indent); - os << indent << "Mask: " ; + os << indent << "Mask: "; if ( m_Mask.IsNotNull() ) { os << m_Mask << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "SelectedClassLabels: " ; - for ( unsigned int i = 0 ; i < m_SelectedClassLabels.size() ; ++i ) + os << indent << "SelectedClassLabels: "; + for ( unsigned int i = 0; i < m_SelectedClassLabels.size(); ++i ) { - os << " " << m_SelectedClassLabels[i] ; + os << " " << m_SelectedClassLabels[i]; } - os << std::endl ; - os << indent << "OtherClassLabel: " << m_OtherClassLabel << std::endl ; + os << std::endl; + os << indent << "OtherClassLabel: " << m_OtherClassLabel << std::endl; } template< class TSample, class TMaskSample > @@ -63,7 +63,7 @@ SampleClassifierWithMask< TSample, TMaskSample > { if ( m_Mask != mask ) { - m_Mask = mask ; + m_Mask = mask; } } @@ -72,82 +72,82 @@ void SampleClassifierWithMask< TSample, TMaskSample > ::GenerateData() { - unsigned int i ; - typename TSample::ConstIterator iter = this->GetSample()->Begin() ; - typename TSample::ConstIterator end = this->GetSample()->End() ; - typename TSample::MeasurementVectorType measurements ; - - typename TMaskSample::Iterator m_iter = this->GetMask()->Begin() ; - - OutputType* output = this->GetOutput() ; - output->Resize(this->GetSample()->Size()) ; - std::vector< double > discriminantScores ; - unsigned int numberOfClasses = this->GetNumberOfClasses() ; - discriminantScores.resize(numberOfClasses) ; - output->SetNumberOfClasses(numberOfClasses + 1) ; - unsigned int classLabel ; + unsigned int i; + typename TSample::ConstIterator iter = this->GetSample()->Begin(); + typename TSample::ConstIterator end = this->GetSample()->End(); + typename TSample::MeasurementVectorType measurements; + + typename TMaskSample::Iterator m_iter = this->GetMask()->Begin(); + + OutputType* output = this->GetOutput(); + output->Resize(this->GetSample()->Size()); + std::vector< double > discriminantScores; + unsigned int numberOfClasses = this->GetNumberOfClasses(); + discriminantScores.resize(numberOfClasses); + output->SetNumberOfClasses(numberOfClasses + 1); + unsigned int classLabel; typename Superclass::DecisionRuleType::Pointer rule = - this->GetDecisionRule() ; + this->GetDecisionRule(); typename Superclass::ClassLabelVectorType classLabels = - this->GetMembershipFunctionClassLabels() ; + this->GetMembershipFunctionClassLabels(); if ( this->GetMask()->Size() != this->GetSample()->Size() ) { - itkExceptionMacro("The sizes of the mask sample and the input sample do not match.") ; + itkExceptionMacro("The sizes of the mask sample and the input sample do not match."); } if ( classLabels.size() != this->GetNumberOfMembershipFunctions() ) { while (iter != end) { - measurements = iter.GetMeasurementVector() ; + measurements = iter.GetMeasurementVector(); if ( std::find(m_SelectedClassLabels.begin(), m_SelectedClassLabels.end(), m_iter.GetMeasurementVector()[0]) != m_SelectedClassLabels.end() ) { - for (i = 0 ; i < numberOfClasses ; i++) + for (i = 0; i < numberOfClasses; i++) { discriminantScores[i] = - (this->GetMembershipFunction(i))->Evaluate(measurements) ; + (this->GetMembershipFunction(i))->Evaluate(measurements); } - classLabel = rule->Evaluate(discriminantScores) ; + classLabel = rule->Evaluate(discriminantScores); } else { - classLabel = m_OtherClassLabel ; + classLabel = m_OtherClassLabel; } - output->AddInstance(classLabel, iter.GetInstanceIdentifier()) ; - ++iter ; - ++m_iter ; + output->AddInstance(classLabel, iter.GetInstanceIdentifier()); + ++iter; + ++m_iter; } } else { while (iter != end) { - measurements = iter.GetMeasurementVector() ; + measurements = iter.GetMeasurementVector(); if ( std::find(m_SelectedClassLabels.begin(), m_SelectedClassLabels.end(), m_iter.GetMeasurementVector()[0]) != m_SelectedClassLabels.end() ) { - for (i = 0 ; i < numberOfClasses ; i++) + for (i = 0; i < numberOfClasses; i++) { discriminantScores[i] = - (this->GetMembershipFunction(i))->Evaluate(measurements) ; + (this->GetMembershipFunction(i))->Evaluate(measurements); } - classLabel = rule->Evaluate(discriminantScores) ; + classLabel = rule->Evaluate(discriminantScores); output->AddInstance(classLabels[classLabel], - iter.GetInstanceIdentifier()) ; + iter.GetInstanceIdentifier()); } else { output->AddInstance(m_OtherClassLabel, - iter.GetInstanceIdentifier()) ; + iter.GetInstanceIdentifier()); } - ++iter ; - ++m_iter ; + ++iter; + ++m_iter; } } } @@ -156,11 +156,3 @@ SampleClassifierWithMask< TSample, TMaskSample > } // end of namespace itk #endif - - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftBlurringFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftBlurringFilter.h index ab706f0003..c793161e02 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftBlurringFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftBlurringFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleMeanShiftBlurringFilter.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:04 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include "itkListSample.h" #include "itkMeanShiftModeSeekerBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class SampleMeanShiftBlurringFilter * \brief This filter blurs the input sample data using mean shift @@ -49,41 +49,41 @@ class SampleMeanShiftBlurringFilter : { public: /** Standard class typedefs. */ - typedef SampleMeanShiftBlurringFilter Self ; - typedef SampleAlgorithmBase< TSample > Superclass ; - typedef SmartPointer<Self> Pointer ; - typedef SmartPointer<const Self> ConstPointer; + typedef SampleMeanShiftBlurringFilter Self; + typedef SampleAlgorithmBase< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(SampleMeanShiftBlurringFilter, SampleAlgorithmBase); - itkNewMacro(Self) ; + itkNewMacro(Self); - typedef typename TSample::MeasurementVectorType MeasurementVectorType ; - typedef typename Superclass::InputSampleType InputSampleType ; - typedef ListSample< MeasurementVectorType > OutputType ; - typedef MeanShiftModeSeekerBase< TSample > MeanShiftModeSeekerType ; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::InputSampleType InputSampleType; + typedef ListSample< MeasurementVectorType > OutputType; + typedef MeanShiftModeSeekerBase< TSample > MeanShiftModeSeekerType; /** Set/Gets the mean shift evolving function */ - void SetMeanShiftModeSeeker(MeanShiftModeSeekerType* function) ; + void SetMeanShiftModeSeeker(MeanShiftModeSeekerType* function); MeanShiftModeSeekerType* GetMeanShiftModeSeeker() - { return m_ModeSeeker ; } + { return m_ModeSeeker; } /** Returns the blurred sample data in a ListSample object */ - OutputType* GetOutput() ; + OutputType* GetOutput(); protected: - SampleMeanShiftBlurringFilter() ; - virtual ~SampleMeanShiftBlurringFilter() ; + SampleMeanShiftBlurringFilter(); + virtual ~SampleMeanShiftBlurringFilter(); void PrintSelf(std::ostream& os, Indent indent) const; /** Blurring the input sample and creates a ListSample with blurred data */ - void GenerateData() ; + void GenerateData(); private: - typename OutputType::Pointer m_Output ; - MeanShiftModeSeekerType* m_ModeSeeker ; -} ; // end of class + typename OutputType::Pointer m_Output; + MeanShiftModeSeekerType* m_ModeSeeker; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -93,4 +93,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftBlurringFilter.txx b/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftBlurringFilter.txx index 2ce25c5f5d..4f54677451 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftBlurringFilter.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftBlurringFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleMeanShiftBlurringFilter.txx,v $ Language: C++ - Date: $Date: 2005-08-11 13:39:31 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,15 +17,15 @@ #ifndef __itkSampleMeanShiftBlurringFilter_txx #define __itkSampleMeanShiftBlurringFilter_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > SampleMeanShiftBlurringFilter< TSample > ::SampleMeanShiftBlurringFilter() { - m_Output = OutputType::New() ; - m_ModeSeeker = 0 ; + m_Output = OutputType::New(); + m_ModeSeeker = 0; } template< class TSample > @@ -51,8 +51,8 @@ SampleMeanShiftBlurringFilter< TSample > { if ( m_ModeSeeker != seeker ) { - m_ModeSeeker = seeker ; - this->Modified() ; + m_ModeSeeker = seeker; + this->Modified(); } } @@ -61,7 +61,7 @@ typename SampleMeanShiftBlurringFilter< TSample >::OutputType* SampleMeanShiftBlurringFilter< TSample > ::GetOutput() { - return m_Output.GetPointer() ; + return m_Output.GetPointer(); } // VS6 cannot compile the following method without the following pragma @@ -74,20 +74,20 @@ void SampleMeanShiftBlurringFilter< TSample > ::GenerateData() { - typename InputSampleType::ConstIterator iter = this->GetInputSample()->Begin() ; - typename InputSampleType::ConstIterator end = this->GetInputSample()->End() ; + typename InputSampleType::ConstIterator iter = this->GetInputSample()->Begin(); + typename InputSampleType::ConstIterator end = this->GetInputSample()->End(); m_Output->SetMeasurementVectorSize( this->GetMeasurementVectorSize() ); - m_Output->Clear() ; + m_Output->Clear(); MeasurementVectorType finalPoint; MeasurementVectorType sample; while ( iter != end ) { sample = iter.GetMeasurementVector(); - finalPoint = m_ModeSeeker->Evolve( sample ) ; - m_Output->PushBack( finalPoint ) ; - ++iter ; + finalPoint = m_ModeSeeker->Evolve( sample ); + m_Output->PushBack( finalPoint ); + ++iter; } } @@ -95,4 +95,3 @@ SampleMeanShiftBlurringFilter< TSample > } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftClusteringFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftClusteringFilter.h index 923dfec1d5..b15e0bdca3 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftClusteringFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftClusteringFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleMeanShiftClusteringFilter.h,v $ Language: C++ - Date: $Date: 2003-12-09 16:53:08 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include <vector> #include "itkSampleAlgorithmBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class SampleMeanShiftClusteringFilter * \brief This filter create a cluster map from an input sample. @@ -44,44 +44,44 @@ class SampleMeanShiftClusteringFilter : public: /** Standard class typedefs. */ typedef SampleMeanShiftClusteringFilter Self; - typedef SampleAlgorithmBase< TSample > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SampleAlgorithmBase< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(SampleMeanShiftClusteringFilter, SampleAlgorithmBase); - itkNewMacro(Self) ; + itkNewMacro(Self); - typedef typename TSample::MeasurementVectorType MeasurementVectorType ; - typedef typename TSample::MeasurementType MeasurementType ; - typedef typename TSample::InstanceIdentifier InstanceIdentifier ; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::InstanceIdentifier InstanceIdentifier; - typedef std::vector< InstanceIdentifier > SearchResultVectorType ; - typedef std::vector< int > ClusterLabelsType ; + typedef std::vector< InstanceIdentifier > SearchResultVectorType; + typedef std::vector< int > ClusterLabelsType; - itkSetMacro(Threshold, double) ; - itkGetMacro(Threshold, double) ; - itkSetMacro(MinimumClusterSize, unsigned long) ; - itkGetMacro(MinimumClusterSize, unsigned long) ; + itkSetMacro(Threshold, double); + itkGetMacro(Threshold, double); + itkSetMacro(MinimumClusterSize, unsigned long); + itkGetMacro(MinimumClusterSize, unsigned long); ClusterLabelsType& GetOutput() - { return m_Output ; } + { return m_Output; } protected: - SampleMeanShiftClusteringFilter() ; - virtual ~SampleMeanShiftClusteringFilter() ; + SampleMeanShiftClusteringFilter(); + virtual ~SampleMeanShiftClusteringFilter(); void PrintSelf(std::ostream& os, Indent indent) const; - void GenerateData() ; + void GenerateData(); private: - double m_Threshold ; - ClusterLabelsType m_Output ; - MeasurementVectorType m_TempQueryPoint ; - SearchResultVectorType m_TempSearchResult ; - unsigned long m_MinimumClusterSize ; -} ; // end of class + double m_Threshold; + ClusterLabelsType m_Output; + MeasurementVectorType m_TempQueryPoint; + SearchResultVectorType m_TempSearchResult; + unsigned long m_MinimumClusterSize; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -91,4 +91,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftClusteringFilter.txx b/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftClusteringFilter.txx index 7cb2f1c70f..81d8e74364 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftClusteringFilter.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleMeanShiftClusteringFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleMeanShiftClusteringFilter.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:05 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,15 +19,15 @@ #include "vnl/vnl_math.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > SampleMeanShiftClusteringFilter< TSample > ::SampleMeanShiftClusteringFilter() { - m_Threshold = 0.5 ; - m_MinimumClusterSize = 16 ; + m_Threshold = 0.5; + m_MinimumClusterSize = 16; } template< class TSample > @@ -43,9 +43,9 @@ SampleMeanShiftClusteringFilter< TSample > { Superclass::PrintSelf(os,indent); - os << indent << "Threshold: " << m_Threshold << std::endl ; + os << indent << "Threshold: " << m_Threshold << std::endl; os << indent << "Minimum cluster size: " << m_MinimumClusterSize - << std::endl ; + << std::endl; } template< class TSample > @@ -53,80 +53,80 @@ void SampleMeanShiftClusteringFilter< TSample > ::GenerateData() { - const TSample* inputSample = this->GetInputSample() ; - m_Output.clear() ; - m_Output.resize( inputSample->Size(), 0 ) ; - int currentLabel = 1 ; - unsigned long currentClusterSize ; - SearchResultVectorType queryPoints ; - SearchResultVectorType queryPoints2 ; + const TSample* inputSample = this->GetInputSample(); + m_Output.clear(); + m_Output.resize( inputSample->Size(), 0 ); + int currentLabel = 1; + unsigned long currentClusterSize; + SearchResultVectorType queryPoints; + SearchResultVectorType queryPoints2; MeasurementVectorType tempQueryPoint; MeasurementVectorType tempPreviousQueryPoint; - bool searchLoopBegin ; - SearchResultVectorType tempSearchResult ; - SearchResultVectorType* currentQueryPoints ; - SearchResultVectorType* nextQueryPoints ; - SearchResultVectorType* tempQueryPoints ; - typename SearchResultVectorType::iterator cp_iter ; - typename SearchResultVectorType::iterator cp_end ; - typename SearchResultVectorType::iterator sr_iter ; - typename SearchResultVectorType::iterator sr_end ; - typename TSample::ConstIterator iter = inputSample->Begin() ; - typename TSample::ConstIterator end = inputSample->End() ; + bool searchLoopBegin; + SearchResultVectorType tempSearchResult; + SearchResultVectorType* currentQueryPoints; + SearchResultVectorType* nextQueryPoints; + SearchResultVectorType* tempQueryPoints; + typename SearchResultVectorType::iterator cp_iter; + typename SearchResultVectorType::iterator cp_end; + typename SearchResultVectorType::iterator sr_iter; + typename SearchResultVectorType::iterator sr_end; + typename TSample::ConstIterator iter = inputSample->Begin(); + typename TSample::ConstIterator end = inputSample->End(); while ( iter != end ) { if ( m_Output[iter.GetInstanceIdentifier()] == 0 ) { - currentClusterSize = 0 ; - currentQueryPoints = &queryPoints ; - nextQueryPoints = &queryPoints2 ; - currentQueryPoints->clear() ; - nextQueryPoints->clear() ; - currentQueryPoints->push_back( iter.GetInstanceIdentifier() ) ; - searchLoopBegin = true ; - tempPreviousQueryPoint.Fill(0) ; + currentClusterSize = 0; + currentQueryPoints = &queryPoints; + nextQueryPoints = &queryPoints2; + currentQueryPoints->clear(); + nextQueryPoints->clear(); + currentQueryPoints->push_back( iter.GetInstanceIdentifier() ); + searchLoopBegin = true; + tempPreviousQueryPoint.Fill(0); while ( currentQueryPoints->size() > 0 ) { - cp_iter = currentQueryPoints->begin() ; - cp_end = currentQueryPoints->end() ; + cp_iter = currentQueryPoints->begin(); + cp_end = currentQueryPoints->end(); while ( cp_iter != cp_end ) { - tempQueryPoint = inputSample->GetMeasurementVector( ( *cp_iter) ) ; + tempQueryPoint = inputSample->GetMeasurementVector( ( *cp_iter) ); if ( !searchLoopBegin && tempQueryPoint == tempPreviousQueryPoint ) { - break ; + break; } - tempSearchResult.clear() ; + tempSearchResult.clear(); inputSample->Search( tempQueryPoint, m_Threshold, - tempSearchResult ) ; + tempSearchResult ); - tempPreviousQueryPoint = tempQueryPoint ; + tempPreviousQueryPoint = tempQueryPoint; if ( searchLoopBegin ) { - searchLoopBegin = false ; + searchLoopBegin = false; } - sr_iter = tempSearchResult.begin() ; - sr_end = tempSearchResult.end() ; + sr_iter = tempSearchResult.begin(); + sr_end = tempSearchResult.end(); while ( sr_iter != sr_end ) { if ( m_Output[*sr_iter] == 0 ) { - m_Output[*sr_iter] = currentLabel ; - nextQueryPoints->push_back( *sr_iter ) ; - ++currentClusterSize ; + m_Output[*sr_iter] = currentLabel; + nextQueryPoints->push_back( *sr_iter ); + ++currentClusterSize; } - ++sr_iter ; + ++sr_iter; } // end of while sr_iter - ++cp_iter ; + ++cp_iter; } // end of cp_iter - tempQueryPoints = currentQueryPoints ; - currentQueryPoints = nextQueryPoints ; - nextQueryPoints = tempQueryPoints ; - nextQueryPoints->clear() ; + tempQueryPoints = currentQueryPoints; + currentQueryPoints = nextQueryPoints; + nextQueryPoints = tempQueryPoints; + nextQueryPoints->clear(); } // end of while (cp->size()) if ( currentClusterSize < m_MinimumClusterSize ) @@ -135,11 +135,11 @@ SampleMeanShiftClusteringFilter< TSample > else { itkDebugMacro(<< "cluster label = " << currentLabel - << " cluster size = " << currentClusterSize) ; - ++currentLabel ; + << " cluster size = " << currentClusterSize); + ++currentLabel; } } // end of if - ++iter ; + ++iter; } } @@ -148,4 +148,3 @@ SampleMeanShiftClusteringFilter< TSample > } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleSelectiveMeanShiftBlurringFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkSampleSelectiveMeanShiftBlurringFilter.h index 1414857fdf..4afe3b1bc8 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleSelectiveMeanShiftBlurringFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleSelectiveMeanShiftBlurringFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleSelectiveMeanShiftBlurringFilter.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:05 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,8 +22,8 @@ #include "itkArray.h" #include <vector> -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class SampleSelectiveMeanShiftBlurringFilter * \brief This filter blurs the input sample data using mean shift @@ -57,20 +57,20 @@ class SampleSelectiveMeanShiftBlurringFilter : { public: /** Standard class typedefs. */ - typedef SampleSelectiveMeanShiftBlurringFilter Self; - typedef SampleMeanShiftBlurringFilter< TSample > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SampleSelectiveMeanShiftBlurringFilter Self; + typedef SampleMeanShiftBlurringFilter< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(SampleSelectiveMeanShiftBlurringFilter, SampleMeanShiftBlurringFilter); - itkNewMacro(Self) ; + itkNewMacro(Self); - typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; - typedef typename Superclass::OutputType OutputType ; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::OutputType OutputType; typedef typename Superclass::MeanShiftModeSeekerType - MeanShiftModeSeekerType ; + MeanShiftModeSeekerType; /** Typedef for selecting components to be blurred */ @@ -78,21 +78,21 @@ public: /** Set/Gets the vector of flags that indicate which components * are selected for blurring */ - void SetComponentSelections(ComponentSelectionsType selections) ; + void SetComponentSelections(ComponentSelectionsType selections); void GetComponentSelections() - { return m_ComponentSelections ; } + { return m_ComponentSelections; } protected: - SampleSelectiveMeanShiftBlurringFilter() ; - virtual ~SampleSelectiveMeanShiftBlurringFilter() ; + SampleSelectiveMeanShiftBlurringFilter(); + virtual ~SampleSelectiveMeanShiftBlurringFilter(); void PrintSelf(std::ostream& os, Indent indent) const; /** Blurring the input sample and creates a ListSample with blurred data */ - void GenerateData() ; + void GenerateData(); private: - ComponentSelectionsType m_ComponentSelections ; -} ; // end of class + ComponentSelectionsType m_ComponentSelections; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -102,4 +102,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleSelectiveMeanShiftBlurringFilter.txx b/Utilities/ITK/Code/Numerics/Statistics/itkSampleSelectiveMeanShiftBlurringFilter.txx index 9a55d99e4f..280ce1a95b 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleSelectiveMeanShiftBlurringFilter.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleSelectiveMeanShiftBlurringFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleSelectiveMeanShiftBlurringFilter.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:05 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,8 +17,8 @@ #ifndef __itkSampleSelectiveMeanShiftBlurringFilter_txx #define __itkSampleSelectiveMeanShiftBlurringFilter_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > SampleSelectiveMeanShiftBlurringFilter< TSample > @@ -61,7 +61,7 @@ SampleSelectiveMeanShiftBlurringFilter< TSample > if ( m_ComponentSelections != selections ) { - m_ComponentSelections = selections ; + m_ComponentSelections = selections; this->Modified(); } } @@ -90,34 +90,34 @@ SampleSelectiveMeanShiftBlurringFilter< TSample > } - MeasurementVectorType queryPoint ; - MeasurementVectorType modePoint ; + MeasurementVectorType queryPoint; + MeasurementVectorType modePoint; MeasurementVectorType finalPoint; MeasurementVectorTraits::SetLength( finalPoint, this->GetMeasurementVectorSize() ); - typename Superclass::InputSampleType::ConstIterator iter = this->GetInputSample()->Begin() ; - typename Superclass::InputSampleType::ConstIterator end = this->GetInputSample()->End() ; + typename Superclass::InputSampleType::ConstIterator iter = this->GetInputSample()->Begin(); + typename Superclass::InputSampleType::ConstIterator end = this->GetInputSample()->End(); - OutputType* output = this->GetOutput() ; - output->Clear() ; - MeanShiftModeSeekerType* modeSeeker = this->GetMeanShiftModeSeeker() ; + OutputType* output = this->GetOutput(); + output->Clear(); + MeanShiftModeSeekerType* modeSeeker = this->GetMeanShiftModeSeeker(); while ( iter != end ) { - queryPoint = iter.GetMeasurementVector() ; - modePoint = modeSeeker->Evolve( queryPoint ) ; - for ( unsigned int i = 0 ; i < this->GetMeasurementVectorSize() ; ++i ) + queryPoint = iter.GetMeasurementVector(); + modePoint = modeSeeker->Evolve( queryPoint ); + for ( unsigned int i = 0; i < this->GetMeasurementVectorSize(); ++i ) { if ( m_ComponentSelections[i] ) { - finalPoint[i] = modePoint[i] ; + finalPoint[i] = modePoint[i]; } else { - finalPoint[i] = queryPoint[i] ; + finalPoint[i] = queryPoint[i]; } } - output->PushBack( finalPoint ) ; - ++iter ; + output->PushBack( finalPoint ); + ++iter; } } @@ -125,4 +125,3 @@ SampleSelectiveMeanShiftBlurringFilter< TSample > } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleToHistogramProjectionFilter.h b/Utilities/ITK/Code/Numerics/Statistics/itkSampleToHistogramProjectionFilter.h index 3752580f9d..f4e6d4d700 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleToHistogramProjectionFilter.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleToHistogramProjectionFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleToHistogramProjectionFilter.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:05 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,8 +26,8 @@ #include "itkSampleAlgorithmBase.h" #include "itkArray.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class SampleToHistogramProjectionFilter * \brief projects measurement vectors on to an axis to generate an @@ -56,26 +56,26 @@ class ITK_EXPORT SampleToHistogramProjectionFilter : { public: /** Standard class typedefs */ - typedef SampleToHistogramProjectionFilter Self; - typedef SampleAlgorithmBase< TInputSample > Superclass ; - typedef SmartPointer< Self > Pointer ; - typedef const SmartPointer< Self > ConstPointer ; + typedef SampleToHistogramProjectionFilter Self; + typedef SampleAlgorithmBase< TInputSample > Superclass; + typedef SmartPointer< Self > Pointer; + typedef const SmartPointer< Self > ConstPointer; /** Run-time type information (and related methods) */ itkTypeMacro(SampleToHistogramProjectionFilter, SampleAlgorithmBase); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** Enums and typedefs from the TInputSample */ - typedef typename TInputSample::MeasurementVectorType MeasurementVectorType ; - typedef typename TInputSample::MeasurementType MeasurementType ; - typedef typename TInputSample::FrequencyType FrequencyType ; - typedef typename TInputSample::InstanceIdentifier InstanceIdentifier ; + typedef typename TInputSample::MeasurementVectorType MeasurementVectorType; + typedef typename TInputSample::MeasurementType MeasurementType; + typedef typename TInputSample::FrequencyType FrequencyType; + typedef typename TInputSample::InstanceIdentifier InstanceIdentifier; /** typedefs from the superclass */ - typedef typename Superclass::InputSampleType InputSampleType ; + typedef typename Superclass::InputSampleType InputSampleType; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; /** 1D array typedef */ @@ -85,38 +85,38 @@ public: typedef Array< double > MeanType; /** Type of the output object */ - typedef Histogram< THistogramMeasurement, 1 > HistogramType ; + typedef Histogram< THistogramMeasurement, 1 > HistogramType; /** Sets the output histogram */ - virtual void SetHistogram(HistogramType* histogram) ; + virtual void SetHistogram(HistogramType* histogram); /** Sets the mean of the sample */ - void SetMean(MeanType* center) ; + void SetMean(MeanType* center); /** Gets the mean of the sample */ - MeanType* GetMean() ; + MeanType* GetMean(); /** Sets the standard deviation of the sample */ - void SetStandardDeviation(double* value) ; + void SetStandardDeviation(double* value); /** Gets the standard deviation of the sample */ - double* GetStandardDeviation() ; + double* GetStandardDeviation(); /** Sets the projection axis */ - void SetProjectionAxis(ArrayType* axis) ; + void SetProjectionAxis(ArrayType* axis); /** Gets the projection axis */ - ArrayType* GetProjectionAxis() ; + ArrayType* GetProjectionAxis(); /** Sets the overlap between adjacent bins. * If this value is not set, then the overlap calculation * will be skipped */ - void SetHistogramBinOverlap(double overlap) ; + void SetHistogramBinOverlap(double overlap); protected: - SampleToHistogramProjectionFilter() ; + SampleToHistogramProjectionFilter(); virtual ~SampleToHistogramProjectionFilter() {} - void PrintSelf(std::ostream& os, Indent indent) const ; + void PrintSelf(std::ostream& os, Indent indent) const; /** Calculates overlap weight for the bin based on * closeness to the adjacent bins */ @@ -124,23 +124,23 @@ protected: float dotProduct, float scale, float marginalDistance, - bool firstHalf) ; + bool firstHalf); /** Runs this algorithm to fill the output histogram */ - void GenerateData() ; + void GenerateData(); private: - SampleToHistogramProjectionFilter(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented - - bool m_HistogramUseEquiProbableBins ; - double m_HistogramBinOverlap ; - - MeanType* m_Mean ; - ArrayType* m_ProjectionAxis ; - double* m_StandardDeviation ; - HistogramType* m_Histogram ; - FrequencyType m_MinimumFrequency ; -} ; // end of class + SampleToHistogramProjectionFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + bool m_HistogramUseEquiProbableBins; + double m_HistogramBinOverlap; + + MeanType* m_Mean; + ArrayType* m_ProjectionAxis; + double* m_StandardDeviation; + HistogramType* m_Histogram; + FrequencyType m_MinimumFrequency; +}; // end of class } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSampleToHistogramProjectionFilter.txx b/Utilities/ITK/Code/Numerics/Statistics/itkSampleToHistogramProjectionFilter.txx index f3a611afbf..5a734719c8 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSampleToHistogramProjectionFilter.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSampleToHistogramProjectionFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSampleToHistogramProjectionFilter.txx,v $ Language: C++ -Date: $Date: 2007-01-26 12:11:36 $ -Version: $Revision: 1.15 $ +Date: $Date: 2009-03-04 19:29:54 $ +Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,19 +22,19 @@ PURPOSE. See the above copyright notices for more information. #include "vnl/vnl_math.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TInputSample, class THistogramMeasurement > SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > ::SampleToHistogramProjectionFilter() { - m_Mean = 0 ; - m_StandardDeviation = 0 ; - m_Histogram = 0 ; - m_ProjectionAxis = 0 ; - m_HistogramBinOverlap = 0.0 ; - m_MinimumFrequency = NumericTraits< FrequencyType >::Zero ; + m_Mean = 0; + m_StandardDeviation = 0; + m_Histogram = 0; + m_ProjectionAxis = 0; + m_HistogramBinOverlap = 0.0; + m_MinimumFrequency = NumericTraits< FrequencyType >::Zero; } template< class TInputSample, class THistogramMeasurement > @@ -42,49 +42,49 @@ void SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > ::PrintSelf(std::ostream& os, Indent indent) const { - Superclass::PrintSelf(os,indent) ; + Superclass::PrintSelf(os,indent); - os << indent << "Histogram: " ; + os << indent << "Histogram: "; if ( m_Histogram != 0 ) { os << m_Histogram << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "Mean: " ; + os << indent << "Mean: "; if ( m_Mean != 0 ) { os << (*m_Mean) << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "Standard Deviation: " ; + os << indent << "Standard Deviation: "; if ( m_StandardDeviation != 0 ) { os << (*m_StandardDeviation) << std::endl; } else { - os << "not set" << std::endl ; + os << "not set" << std::endl; } - os << indent << "ProjectionAxis: " ; + os << indent << "ProjectionAxis: "; if ( m_ProjectionAxis != 0 ) { - os << (*m_ProjectionAxis) << std::endl ; + os << (*m_ProjectionAxis) << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "HistogramBinOverlap: " << m_HistogramBinOverlap << std::endl ; + os << indent << "HistogramBinOverlap: " << m_HistogramBinOverlap << std::endl; os << indent << "Minimum Frequency " << m_MinimumFrequency << std::endl; } @@ -95,8 +95,8 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > { if ( m_Histogram != histogram ) { - m_Histogram = histogram ; - this->Modified() ; + m_Histogram = histogram; + this->Modified(); } } @@ -121,8 +121,8 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > if ( m_Mean != mean ) { - m_Mean = mean ; - this->Modified() ; + m_Mean = mean; + this->Modified(); } } @@ -131,7 +131,7 @@ typename SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > ::GetMean() { - return m_Mean ; + return m_Mean; } template< class TInputSample, class THistogramMeasurement > @@ -141,8 +141,8 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > { if ( m_StandardDeviation != value ) { - m_StandardDeviation = value ; - this->Modified() ; + m_StandardDeviation = value; + this->Modified(); } } @@ -151,7 +151,7 @@ double* SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > ::GetStandardDeviation() { - return m_StandardDeviation ; + return m_StandardDeviation; } template< class TInputSample, class THistogramMeasurement > @@ -174,8 +174,8 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > if ( m_ProjectionAxis != axis ) { - m_ProjectionAxis = axis ; - this->Modified() ; + m_ProjectionAxis = axis; + this->Modified(); } } @@ -184,7 +184,7 @@ typename SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > ::GetProjectionAxis() { - return m_ProjectionAxis ; + return m_ProjectionAxis; } template< class TInputSample, class THistogramMeasurement > @@ -194,8 +194,8 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > { if ( m_HistogramBinOverlap != overlap ) { - m_HistogramBinOverlap = overlap ; - this->Modified() ; + m_HistogramBinOverlap = overlap; + this->Modified(); } } @@ -207,21 +207,21 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > float marginalDistance, bool firstHalf) { - float minWeight ; - float maxWeight ; + float minWeight; + float maxWeight; - float binMin = m_Histogram->GetBinMin(0, binId) ; - float binMax = m_Histogram->GetBinMax(0, binId) ; + float binMin = m_Histogram->GetBinMin(0, binId); + float binMax = m_Histogram->GetBinMax(0, binId); if (firstHalf) { - minWeight = (dotProduct - binMin) / ((binMax - binMin) / 2.0) ; + minWeight = (dotProduct - binMin) / ((binMax - binMin) / 2.0); } else { minWeight = (dotProduct - binMin) / ((float(m_Histogram->GetBinMax(0, binId - 1)) - - float(m_Histogram->GetBinMin(0, binId - 1))) / 2.0) ; + float(m_Histogram->GetBinMin(0, binId - 1))) / 2.0); } if (minWeight > -1.0) @@ -230,39 +230,39 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > { maxWeight = (binMax - dotProduct) / ((float(m_Histogram->GetBinMax(0, binId + 1)) - - float(m_Histogram->GetBinMin(0, binId + 1))) / 2.0) ; + float(m_Histogram->GetBinMin(0, binId + 1))) / 2.0); } else { maxWeight = - (binMax - dotProduct) / ((binMax - binMin) / 2.0) ; + (binMax - dotProduct) / ((binMax - binMin) / 2.0); } if (maxWeight > -1.0) { if (minWeight < 1.0) { - minWeight = 1.0 / (1.0 + vcl_exp(-minWeight / scale)) ; + minWeight = 1.0 / (1.0 + vcl_exp(-minWeight / scale)); } else { - minWeight = 1.0 ; + minWeight = 1.0; } if (maxWeight < 1.0) { - maxWeight = 1.0 / (1.0 + vcl_exp(-maxWeight / scale)) ; + maxWeight = 1.0 / (1.0 + vcl_exp(-maxWeight / scale)); } else { - maxWeight = 1.0 ; + maxWeight = 1.0; } - return minWeight * maxWeight * marginalDistance ; + return minWeight * maxWeight * marginalDistance; } } - return m_MinimumFrequency ; + return m_MinimumFrequency; } template< class TInputSample, class THistogramMeasurement > @@ -283,59 +283,59 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > } - typename HistogramType::Iterator h_iter = m_Histogram->Begin() ; - typename HistogramType::Iterator h_last = m_Histogram->End() ; + typename HistogramType::Iterator h_iter = m_Histogram->Begin(); + typename HistogramType::Iterator h_last = m_Histogram->End(); while (h_iter != h_last) { - h_iter.SetFrequency(0.0) ; - ++h_iter ; + h_iter.SetFrequency(0.0); + ++h_iter; } - float scale = 1 ; + float scale = 1; if (m_HistogramBinOverlap) { - scale = vcl_log(1.0 + m_HistogramBinOverlap / 10.0 ) ; + scale = vcl_log(1.0 + m_HistogramBinOverlap / 10.0 ); } - typename HistogramType::InstanceIdentifier binId ; - unsigned int dimension ; - float coordinateDistance ; - float squaredDistance ; - float marginalDistance ; - float dotProduct ; - FrequencyType tempFrequency ; - FrequencyType frequency ; + typename HistogramType::InstanceIdentifier binId; + unsigned int dimension; + float coordinateDistance; + float squaredDistance; + float marginalDistance; + float dotProduct; + FrequencyType tempFrequency; + FrequencyType frequency; - MeasurementVectorType tempMeasurementVector ; + MeasurementVectorType tempMeasurementVector; typename TInputSample::ConstIterator s_iter = this->GetInputSample()->Begin(); typename TInputSample::ConstIterator s_last = this->GetInputSample()->End(); - unsigned long numberOfBins = (unsigned long) m_Histogram->Size() ; + unsigned long numberOfBins = (unsigned long) m_Histogram->Size(); double extent = vnl_math_abs( m_Histogram->GetBinMax(0, numberOfBins - 1UL) - - m_Histogram->GetBinMin(0, 0) ) / 2.0 ; + m_Histogram->GetBinMin(0, 0) ) / 2.0; while (s_iter != s_last) { - tempMeasurementVector = s_iter.GetMeasurementVector() ; - squaredDistance = 0.0 ; - dotProduct = 0.0 ; - frequency = s_iter.GetFrequency() ; - for (dimension = 0 ; dimension < measurementVectorSize ; dimension++) + tempMeasurementVector = s_iter.GetMeasurementVector(); + squaredDistance = 0.0; + dotProduct = 0.0; + frequency = s_iter.GetFrequency(); + for (dimension = 0; dimension < measurementVectorSize; dimension++) { coordinateDistance = - tempMeasurementVector[dimension] - (*m_Mean)[dimension] ; - squaredDistance += coordinateDistance * coordinateDistance ; - dotProduct += coordinateDistance * (*m_ProjectionAxis)[dimension] ; + tempMeasurementVector[dimension] - (*m_Mean)[dimension]; + squaredDistance += coordinateDistance * coordinateDistance; + dotProduct += coordinateDistance * (*m_ProjectionAxis)[dimension]; } marginalDistance = vcl_sqrt(vnl_math_abs(squaredDistance - dotProduct * dotProduct)) / - ((*m_StandardDeviation) * extent) ; + ((*m_StandardDeviation) * extent); - dotProduct /= (*m_StandardDeviation) ; + dotProduct /= (*m_StandardDeviation); if (m_HistogramBinOverlap < 0.001) { @@ -345,24 +345,24 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > m_Histogram-> GetBinMax(0, numberOfBins - 1UL)) ) { - binId = 0 ; + binId = 0; while ( (dotProduct > m_Histogram->GetBinMax(0, binId)) && (binId < (numberOfBins - 1UL)) ) { - binId++ ; + binId++; } - m_Histogram->IncreaseFrequency(binId, frequency) ; + m_Histogram->IncreaseFrequency(binId, frequency); } } else { - marginalDistance = 1.0 - marginalDistance ; + marginalDistance = 1.0 - marginalDistance; if ( marginalDistance > -1.0 ) { marginalDistance = - 1.0 / (1.0 + vcl_exp(-marginalDistance / scale)) ; + 1.0 / (1.0 + vcl_exp(-marginalDistance / scale)); - for (binId = 0 ; binId <= (numberOfBins / 2UL) ; + for (binId = 0; binId <= (numberOfBins / 2UL); binId++) { tempFrequency = @@ -370,15 +370,15 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > dotProduct, scale, marginalDistance, - true) ; + true); if ( tempFrequency > m_MinimumFrequency ) { - m_Histogram->IncreaseFrequency(binId, tempFrequency * frequency) ; + m_Histogram->IncreaseFrequency(binId, tempFrequency * frequency); } } // end of for - for (binId = numberOfBins / 2UL + 1UL ; - binId < numberOfBins ; + for (binId = numberOfBins / 2UL + 1UL; + binId < numberOfBins; binId++) { tempFrequency = @@ -386,16 +386,16 @@ SampleToHistogramProjectionFilter< TInputSample, THistogramMeasurement > dotProduct, scale, marginalDistance, - false) ; + false); if ( tempFrequency > m_MinimumFrequency ) { - m_Histogram->IncreaseFrequency(binId, tempFrequency * frequency) ; + m_Histogram->IncreaseFrequency(binId, tempFrequency * frequency); } } // end of for } // end of if (marginalDistance ... } // end of if (m_HistogramBinOverlap ... - ++s_iter ; + ++s_iter; } // end of while } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageTextureCalculator.h b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageTextureCalculator.h index cab5fe8cad..b6cc99849a 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageTextureCalculator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageTextureCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageTextureCalculator.h,v $ Language: C++ - Date: $Date: 2005-08-24 15:16:53 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -110,15 +110,15 @@ class ScalarImageTextureCalculator : public Object public: /** Standard typedefs */ typedef ScalarImageTextureCalculator Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(ScalarImageTextureCalculator, Object); /** standard New() method support */ - itkNewMacro(Self) ; + itkNewMacro(Self); typedef THistogramFrequencyContainer FrequencyContainerType; typedef TImageType ImageType; @@ -191,11 +191,12 @@ protected: private: typename GLCMGeneratorType::Pointer m_GLCMGenerator; - FeatureValueVectorPointer m_FeatureMeans, m_FeatureStandardDeviations; - FeatureNameVectorConstPointer m_RequestedFeatures; - OffsetVectorConstPointer m_Offsets; - bool m_FastCalculations; -}; + FeatureValueVectorPointer m_FeatureMeans; + FeatureValueVectorPointer m_FeatureStandardDeviations; + FeatureNameVectorConstPointer m_RequestedFeatures; + OffsetVectorConstPointer m_Offsets; + bool m_FastCalculations; +}; } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageTextureCalculator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageTextureCalculator.txx index a69b533e20..e08db7281b 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageTextureCalculator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageTextureCalculator.txx @@ -3,19 +3,19 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageTextureCalculator.txx,v $ Language: C++ - Date: $Date: 2005-05-10 05:33:48 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkScalarImageTextureCalculator_txx -#define _itkScalarImageTextureCalculator_txx +#ifndef __itkScalarImageTextureCalculator_txx +#define __itkScalarImageTextureCalculator_txx #include "itkScalarImageTextureCalculator.h" #include "itkNeighborhood.h" @@ -31,10 +31,10 @@ ScalarImageTextureCalculator() m_GLCMGenerator = GLCMGeneratorType::New(); m_FeatureMeans = FeatureValueVector::New(); m_FeatureStandardDeviations = FeatureValueVector::New(); - + // Set the requested features to the default value: // {Energy, Entropy, InverseDifferenceMoment, Inertia, ClusterShade, ClusterProminence} - FeatureNameVectorPointer requestedFeatures = FeatureNameVector::New(); + FeatureNameVectorPointer requestedFeatures = FeatureNameVector::New(); // can't directly set m_RequestedFeatures since it is const! requestedFeatures->push_back(Energy); requestedFeatures->push_back(Entropy); @@ -43,15 +43,15 @@ ScalarImageTextureCalculator() requestedFeatures->push_back(ClusterShade); requestedFeatures->push_back(ClusterProminence); this->SetRequestedFeatures(requestedFeatures); - + // Set the offset directions to their defaults: half of all the possible // directions 1 pixel away. (The other half is included by symmetry.) // We use a neighborhood iterator to calculate the appropriate offsets. - typedef Neighborhood<ITK_TYPENAME ImageType::PixelType, ::itk::GetImageDimension< + typedef Neighborhood<ITK_TYPENAME ImageType::PixelType, ::itk::GetImageDimension< ImageType >::ImageDimension > NeighborhoodType; NeighborhoodType hood; hood.SetRadius(1); - + // select all "previous" neighbors that are face+edge+vertex // connected to the current pixel. do not include the center pixel. unsigned int centerIndex = hood.GetCenterNeighborhoodIndex(); @@ -68,22 +68,22 @@ ScalarImageTextureCalculator() template< class TImage, class THistogramFrequencyContainer > void -ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: +ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: Compute(void) { - if (m_FastCalculations) + if (m_FastCalculations) { this->FastCompute(); } - else + else { this->FullCompute(); } -} +} template< class TImage, class THistogramFrequencyContainer > void -ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: +ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: FullCompute(void) { int numOffsets = m_Offsets->size(); @@ -95,11 +95,11 @@ FullCompute(void) { features[i] = new double [numFeatures]; } - + // For each offset, calculate each feature typename OffsetVector::ConstIterator offsetIt; int offsetNum, featureNum; - + for(offsetIt = m_Offsets->Begin(), offsetNum = 0; offsetIt != m_Offsets->End(); offsetIt++, offsetNum++) { @@ -108,23 +108,23 @@ FullCompute(void) typename GLCMCalculatorType::Pointer glcmCalc = GLCMCalculatorType::New(); glcmCalc->SetHistogram(m_GLCMGenerator->GetOutput()); glcmCalc->Compute(); - + typename FeatureNameVector::ConstIterator fnameIt; - for(fnameIt = m_RequestedFeatures->Begin(), featureNum = 0; + for(fnameIt = m_RequestedFeatures->Begin(), featureNum = 0; fnameIt != m_RequestedFeatures->End(); fnameIt++, featureNum++) { features[offsetNum][featureNum] = glcmCalc->GetFeature(fnameIt.Value()); } } - + // Now get the mean and deviaton of each feature across the offsets. m_FeatureMeans->clear(); m_FeatureStandardDeviations->clear(); double *tempFeatureMeans = new double [numFeatures]; double *tempFeatureDevs = new double [numFeatures]; - - /*Compute incremental mean and SD, a la Knuth, "The Art of Computer - Programming, Volume 2: Seminumerical Algorithms", section 4.2.2. + + /*Compute incremental mean and SD, a la Knuth, "The Art of Computer + Programming, Volume 2: Seminumerical Algorithms", section 4.2.2. Compute mean and standard deviation using the recurrence relation: M(1) = x(1), M(k) = M(k-1) + (x(k) - M(k-1) ) / k S(1) = 0, S(k) = S(k-1) + (x(k) - M(k-1)) * (x(k) - M(k)) @@ -132,7 +132,7 @@ FullCompute(void) sigma = vcl_sqrt(S(n) / n) (or divide by n-1 for sample SD instead of population SD). */ - + // Set up the initial conditions (k = 1) for (featureNum = 0; featureNum < numFeatures; featureNum++) { @@ -148,10 +148,10 @@ FullCompute(void) double M_k_minus_1 = tempFeatureMeans[featureNum]; double S_k_minus_1 = tempFeatureDevs[featureNum]; double x_k = features[offsetNum][featureNum]; - + double M_k = M_k_minus_1 + (x_k - M_k_minus_1) / k; double S_k = S_k_minus_1 + (x_k - M_k_minus_1) * (x_k - M_k); - + tempFeatureMeans[featureNum] = M_k; tempFeatureDevs[featureNum] = S_k; } @@ -159,7 +159,7 @@ FullCompute(void) for (featureNum = 0; featureNum < numFeatures; featureNum++) { tempFeatureDevs[featureNum] = vcl_sqrt(tempFeatureDevs[featureNum] / numOffsets); - + m_FeatureMeans->push_back(tempFeatureMeans[featureNum]); m_FeatureStandardDeviations->push_back(tempFeatureDevs[featureNum]); } @@ -171,28 +171,28 @@ FullCompute(void) } delete[] features; } - + template< class TImage, class THistogramFrequencyContainer > void -ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: +ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: FastCompute(void) -{ +{ // For each offset, calculate each feature - typename OffsetVector::ConstIterator offsetIt; + typename OffsetVector::ConstIterator offsetIt; for(offsetIt = m_Offsets->Begin(); offsetIt != m_Offsets->End(); offsetIt++) { m_GLCMGenerator->SetOffset(offsetIt.Value()); } - + m_GLCMGenerator->Compute(); typename GLCMCalculatorType::Pointer glcmCalc = GLCMCalculatorType::New(); glcmCalc->SetHistogram(m_GLCMGenerator->GetOutput()); glcmCalc->Compute(); - + m_FeatureMeans->clear(); m_FeatureStandardDeviations->clear(); typename FeatureNameVector::ConstIterator fnameIt; - for(fnameIt = m_RequestedFeatures->Begin(); + for(fnameIt = m_RequestedFeatures->Begin(); fnameIt != m_RequestedFeatures->End(); fnameIt++) { m_FeatureMeans->push_back(glcmCalc->GetFeature(fnameIt.Value())); @@ -203,44 +203,44 @@ FastCompute(void) template< class TImage, class THistogramFrequencyContainer > void -ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: +ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: SetInput( const ImageType * inputImage ) { itkDebugMacro("setting Input to " << inputImage); m_GLCMGenerator->SetInput(inputImage); this->Modified(); } - + template< class TImage, class THistogramFrequencyContainer > void -ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: +ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: SetNumberOfBinsPerAxis( unsigned int numberOfBins ) { itkDebugMacro("setting NumberOfBinsPerAxis to " << numberOfBins); m_GLCMGenerator->SetNumberOfBinsPerAxis(numberOfBins); this->Modified(); } - + template< class TImage, class THistogramFrequencyContainer > void -ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: +ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: SetPixelValueMinMax( PixelType min, PixelType max ) { itkDebugMacro("setting Min to " << min << "and Max to " << max); m_GLCMGenerator->SetPixelValueMinMax(min, max); this->Modified(); } - + template< class TImage, class THistogramFrequencyContainer > void -ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: +ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: SetImageMask( const ImageType* imageMask) { itkDebugMacro("setting ImageMask to " << imageMask); m_GLCMGenerator->SetImageMask(imageMask); this->Modified(); } - + template< class TImage, class THistogramFrequencyContainer > void ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: @@ -250,18 +250,18 @@ SetInsidePixelValue(PixelType insidePixelValue) m_GLCMGenerator->SetInsidePixelValue(insidePixelValue); this->Modified(); } - + template< class TImage, class THistogramFrequencyContainer > void -ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: +ScalarImageTextureCalculator< TImage, THistogramFrequencyContainer >:: PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); } - -} // end of namespace Statistics -} // end of namespace itk +} // end of namespace Statistics + +} // end of namespace itk #endif diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.h index d3553beea2..368518ea48 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.h,v $ Language: C++ - Date: $Date: 2005-08-24 15:16:54 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-05-20 16:21:47 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,166 +26,170 @@ #include "itkMacro.h" namespace itk { - namespace Statistics { +namespace Statistics { /** \class ScalarImageToGreyLevelCooccurrenceMatrixGenerator -* \brief This class computes a grey-level co-occurence matrix (histogram) from -* a given image. GLCM's are used for image texture description. -* -* This generator creates a grey-level co-occurence matrix from a N-D scalar -* image. This is the first step in texture description a la Haralick. (See -* Haralick, R.M., K. Shanmugam and I. Dinstein. 1973. Textural Features for -* Image Classification. IEEE Transactions on Systems, Man and Cybernetics. -* SMC-3(6):610-620. See also Haralick, R.M. 1979. Statistical and Structural -* Approaches to Texture. Proceedings of the IEEE, 67:786-804.) -* -* The basic idea is as follows: -* Given an image and an offset (e.g. (1, -1) for a 2-d image), grey-level -* co-occurences are pairs of intensity values for a specific pixel and the -* pixel at that offset from the specified pixel. These co-occurences can provide -* information about the visual texture of an image region -- for example, an -* eight-bit image of alternating pixel-wide white and black vertical lines -* would have a large number of (0, 255) and (255, 0) co-occurences for offset -* (1, 0). -* -* The offset (or offsets) along which the co-occurences are calculated can be -* set by the user. Traditionally, only one offset is used per histogram, and -* offset components in the range [-1, 1] are used. For rotation-invariant features, -* averages of features computed over several histograms with different offsets -* are generally used, instead of computing features from one histogram created -* with several offsets. Additionally, instead of using offsets of two or more -* pixels in any direction, multy-resulution techniques (e.g. image pyramids) -* are generally used to deal with texture at different spatial resolutions. -* -* This class calculates a 2-d histogram of all the co-occurence pairs in the -* given image's requested region, for a given set of offsets. That is, if a given -* offset falls outside of the requested region at a particular point, that -* co-occurrence pair will not be added to the matrix. -* -* The number of histogram bins on each axis can be set (defaults to 256). Also, -* by default the histogram min and max corresponds to the largest and smallest -* possible pixel value of that pixel type. To customize the histogram bounds -* for a given image, the max and min pixel values that will be placed in the -* histogram can be set manually. NB: The min and max are INCLUSIVE. -* -* Further, the type of histogram frequency container used is an optional template -* parameter. By default, a dense container is used, but for images with little -* texture or in cases where the user wants more histogram bins, a sparse container -* can be used for the histogram instead. -* -* WARNING: This probably won't work for pixels of double or long-double type -* unless you set the histogram min and max manually. This is because the largest -* histogram bin by default has max value of the largest possible pixel value -* plus 1. For double and long-double types, whose "RealType" as defined by the -* NumericTraits class is the same, and thus cannot hold any larger values, -* this would cause a float overflow. -* -* \sa MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator -* \sa GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator -* \sa ScalarImageTextureCalculator -* -* Authors: Zachary Pincus and Glenn Pierce -*/ + * \brief This class computes a grey-level co-occurence matrix (histogram) from + * a given image. GLCM's are used for image texture description. + * + * This generator creates a grey-level co-occurence matrix from a N-D scalar + * image. This is the first step in texture description a la Haralick. (See + * Haralick, R.M., K. Shanmugam and I. Dinstein. 1973. Textural Features for + * Image Classification. IEEE Transactions on Systems, Man and Cybernetics. + * SMC-3(6):610-620. See also Haralick, R.M. 1979. Statistical and Structural + * Approaches to Texture. Proceedings of the IEEE, 67:786-804.) + * + * The basic idea is as follows: + * Given an image and an offset (e.g. (1, -1) for a 2-d image), grey-level + * co-occurences are pairs of intensity values for a specific pixel and the + * pixel at that offset from the specified pixel. These co-occurences can provide + * information about the visual texture of an image region -- for example, an + * eight-bit image of alternating pixel-wide white and black vertical lines + * would have a large number of (0, 255) and (255, 0) co-occurences for offset + * (1, 0). + * + * The offset (or offsets) along which the co-occurences are calculated can be + * set by the user. Traditionally, only one offset is used per histogram, and + * offset components in the range [-1, 1] are used. For rotation-invariant features, + * averages of features computed over several histograms with different offsets + * are generally used, instead of computing features from one histogram created + * with several offsets. Additionally, instead of using offsets of two or more + * pixels in any direction, multy-resulution techniques (e.g. image pyramids) + * are generally used to deal with texture at different spatial resolutions. + * + * This class calculates a 2-d histogram of all the co-occurence pairs in the + * given image's requested region, for a given set of offsets. That is, if a given + * offset falls outside of the requested region at a particular point, that + * co-occurrence pair will not be added to the matrix. + * + * The number of histogram bins on each axis can be set (defaults to 256). Also, + * by default the histogram min and max corresponds to the largest and smallest + * possible pixel value of that pixel type. To customize the histogram bounds + * for a given image, the max and min pixel values that will be placed in the + * histogram can be set manually. NB: The min and max are INCLUSIVE. + * + * Further, the type of histogram frequency container used is an optional template + * parameter. By default, a dense container is used, but for images with little + * texture or in cases where the user wants more histogram bins, a sparse container + * can be used for the histogram instead. + * + * WARNING: This probably won't work for pixels of double or long-double type + * unless you set the histogram min and max manually. This is because the largest + * histogram bin by default has max value of the largest possible pixel value + * plus 1. For double and long-double types, whose "RealType" as defined by the + * NumericTraits class is the same, and thus cannot hold any larger values, + * this would cause a float overflow. + * + * \sa MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator + * \sa GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator + * \sa ScalarImageTextureCalculator + * + * Authors: Zachary Pincus and Glenn Pierce + */ template< class TImageType, class THistogramFrequencyContainer = DenseFrequencyContainer > class ScalarImageToGreyLevelCooccurrenceMatrixGenerator : public Object - { - public: - /** Standard typedefs */ - typedef ScalarImageToGreyLevelCooccurrenceMatrixGenerator Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; +{ +public: + /** Standard typedefs */ + typedef ScalarImageToGreyLevelCooccurrenceMatrixGenerator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; - /** Run-time type information (and related methods). */ - itkTypeMacro(ScalarImageToGreyLevelCooccurrenceMatrixGenerator, Object); + /** Run-time type information (and related methods). */ + itkTypeMacro(ScalarImageToGreyLevelCooccurrenceMatrixGenerator, Object); - /** standard New() method support */ - itkNewMacro(Self) ; + /** standard New() method support */ + itkNewMacro(Self); - typedef TImageType ImageType; - typedef typename ImageType::Pointer ImagePointer; - typedef typename ImageType::ConstPointer ImageConstPointer; - typedef typename ImageType::PixelType PixelType; - typedef typename ImageType::RegionType RegionType; - typedef typename ImageType::SizeType RadiusType; - typedef typename ImageType::OffsetType OffsetType; - typedef VectorContainer<unsigned char, OffsetType> OffsetVector; - typedef typename OffsetVector::Pointer OffsetVectorPointer; - typedef typename OffsetVector::ConstPointer OffsetVectorConstPointer; + typedef TImageType ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::RegionType RegionType; + typedef typename ImageType::SizeType RadiusType; + typedef typename ImageType::OffsetType OffsetType; + typedef VectorContainer<unsigned char, OffsetType> OffsetVector; + typedef typename OffsetVector::Pointer OffsetVectorPointer; + typedef typename OffsetVector::ConstPointer OffsetVectorConstPointer; - typedef typename NumericTraits<PixelType>::RealType MeasurementType; + typedef typename NumericTraits<PixelType>::RealType MeasurementType; - typedef Histogram< MeasurementType, 2, THistogramFrequencyContainer > - HistogramType; - typedef typename HistogramType::Pointer HistogramPointer; - typedef typename HistogramType::ConstPointer HistogramConstPointer; - typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; + typedef Histogram< MeasurementType, 2, THistogramFrequencyContainer > + HistogramType; + typedef typename HistogramType::Pointer HistogramPointer; + typedef typename HistogramType::ConstPointer HistogramConstPointer; + typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; - itkStaticConstMacro(DefaultBinsPerAxis, unsigned int, 256); + itkStaticConstMacro(DefaultBinsPerAxis, unsigned int, 256); - /** Triggers the Computation of the histogram */ - void Compute( void ); + /** Triggers the Computation of the histogram */ + void Compute( void ); - /** Connects the input image for which the histogram is going to be computed */ - itkSetConstObjectMacro( Input, ImageType ); - itkGetConstObjectMacro( Input, ImageType ); + /** Connects the input image for which the histogram is going to be computed */ + itkSetConstObjectMacro( Input, ImageType ); + itkGetConstObjectMacro( Input, ImageType ); - /** Set the offset or offsets over which the co-occurrence pairs will be computed. - Calling either of these methods clears the previous offsets.*/ - itkSetConstObjectMacro( Offsets, OffsetVector ); - itkGetConstObjectMacro( Offsets, OffsetVector ); - void SetOffset( const OffsetType offset ) - { - OffsetVectorPointer offsetVector = OffsetVector::New(); - offsetVector->push_back(offset); - this->SetOffsets(offsetVector); - } + /** Set the offset or offsets over which the co-occurrence pairs + * will be computed. Calling either of these methods clears the + * previous offsets. */ + itkSetConstObjectMacro( Offsets, OffsetVector ); + itkGetConstObjectMacro( Offsets, OffsetVector ); + void SetOffset( const OffsetType offset ) + { + OffsetVectorPointer offsetVector = OffsetVector::New(); + offsetVector->push_back(offset); + this->SetOffsets(offsetVector); + } - /** Return the histogram. + /** Return the histogram. \warning This output is only valid after the Compute() method has been invoked \sa Compute */ - itkGetObjectMacro( Output, HistogramType ); + itkGetObjectMacro( Output, HistogramType ); - /** Set number of histogram bins along each axis */ - itkSetMacro( NumberOfBinsPerAxis, unsigned int ); - itkGetMacro( NumberOfBinsPerAxis, unsigned int ); + /** Set number of histogram bins along each axis */ + itkSetMacro( NumberOfBinsPerAxis, unsigned int ); + itkGetMacro( NumberOfBinsPerAxis, unsigned int ); - /** Set the min and max (inclusive) pixel value that will be placed in the histogram */ - void SetPixelValueMinMax( PixelType min, PixelType max ); - itkGetMacro(Min, PixelType); - itkGetMacro(Max, PixelType); + /** Set the min and max (inclusive) pixel value that will be placed in the histogram */ + void SetPixelValueMinMax( PixelType min, PixelType max ); + itkGetMacro(Min, PixelType); + itkGetMacro(Max, PixelType); - /** Set the calculator to normalize the histogram (divide all bins by the + /** Set the calculator to normalize the histogram (divide all bins by the total frequency). Normalization is off by default.*/ - itkSetMacro(Normalize, bool); - itkGetMacro(Normalize, bool); - itkBooleanMacro(Normalize); + itkSetMacro(Normalize, bool); + itkGetMacro(Normalize, bool); + itkBooleanMacro(Normalize); - protected: - ScalarImageToGreyLevelCooccurrenceMatrixGenerator(); - virtual ~ScalarImageToGreyLevelCooccurrenceMatrixGenerator() {}; - void PrintSelf(std::ostream& os, Indent indent) const; - virtual void FillHistogram( RadiusType radius, RegionType region ); - - private: - void NormalizeHistogram( void ); +protected: + ScalarImageToGreyLevelCooccurrenceMatrixGenerator(); + virtual ~ScalarImageToGreyLevelCooccurrenceMatrixGenerator() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + virtual void FillHistogram( RadiusType radius, RegionType region ); + +private: + ScalarImageToGreyLevelCooccurrenceMatrixGenerator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + void NormalizeHistogram( void ); - ImageConstPointer m_Input; - HistogramPointer m_Output; - OffsetVectorConstPointer m_Offsets; - PixelType m_Min, m_Max; + ImageConstPointer m_Input; + HistogramPointer m_Output; + OffsetVectorConstPointer m_Offsets; + PixelType m_Min; + PixelType m_Max; - unsigned int m_NumberOfBinsPerAxis; - MeasurementVectorType m_LowerBound, m_UpperBound; - bool m_Normalize; + unsigned int m_NumberOfBinsPerAxis; + MeasurementVectorType m_LowerBound; + MeasurementVectorType m_UpperBound; + bool m_Normalize; - }; - - - } // end of namespace Statistics +}; + +} // end of namespace Statistics } // end of namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx index 43c2a05f5d..c210a6c22d 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.txx,v $ Language: C++ - Date: $Date: 2005-04-20 20:31:22 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkScalarImageToGreyLevelCooccurrenceMatrixGenerator_txx -#define _itkScalarImageToGreyLevelCooccurrenceMatrixGenerator_txx +#ifndef __itkScalarImageToGreyLevelCooccurrenceMatrixGenerator_txx +#define __itkScalarImageToGreyLevelCooccurrenceMatrixGenerator_txx #include "itkScalarImageToGreyLevelCooccurrenceMatrixGenerator.h" @@ -24,158 +24,158 @@ namespace itk { - namespace Statistics { +namespace Statistics { - template< class TImageType, class THistogramFrequencyContainer > - ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer >:: - ScalarImageToGreyLevelCooccurrenceMatrixGenerator() : - m_NumberOfBinsPerAxis(itkGetStaticConstMacro(DefaultBinsPerAxis)), m_Normalize(false) - { - m_LowerBound.Fill(NumericTraits<PixelType>::min()); - m_UpperBound.Fill(NumericTraits<PixelType>::max() + 1); - m_Min = NumericTraits<PixelType>::min(); - m_Max = NumericTraits<PixelType>::max(); - } +template< class TImageType, class THistogramFrequencyContainer > +ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer >:: +ScalarImageToGreyLevelCooccurrenceMatrixGenerator() : + m_NumberOfBinsPerAxis(itkGetStaticConstMacro(DefaultBinsPerAxis)), m_Normalize(false) +{ + m_LowerBound.Fill(NumericTraits<PixelType>::min()); + m_UpperBound.Fill(NumericTraits<PixelType>::max() + 1); + m_Min = NumericTraits<PixelType>::min(); + m_Max = NumericTraits<PixelType>::max(); +} - template< class TImageType, class THistogramFrequencyContainer > - void - ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer >:: - Compute( void ) - { - // First, create an appropriate histogram with the right number of bins - // and mins and maxes correct for the image type. - m_Output = HistogramType::New(); - typename HistogramType::SizeType size; - size.Fill(m_NumberOfBinsPerAxis); - m_Output->Initialize(size, m_LowerBound, m_UpperBound); +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer >:: +Compute( void ) +{ + // First, create an appropriate histogram with the right number of bins + // and mins and maxes correct for the image type. + m_Output = HistogramType::New(); + typename HistogramType::SizeType size; + size.Fill(m_NumberOfBinsPerAxis); + m_Output->Initialize(size, m_LowerBound, m_UpperBound); - // Next, find the minimum radius that encloses all the offsets. - unsigned int minRadius = 0; - typename OffsetVector::ConstIterator offsets; - for(offsets = m_Offsets->Begin(); offsets != m_Offsets->End(); offsets++) + // Next, find the minimum radius that encloses all the offsets. + unsigned int minRadius = 0; + typename OffsetVector::ConstIterator offsets; + for(offsets = m_Offsets->Begin(); offsets != m_Offsets->End(); offsets++) + { + for(unsigned int i = 0; i < offsets.Value().GetOffsetDimension(); i++) + { + unsigned int distance = vnl_math_abs(offsets.Value()[i]); + if(distance > minRadius) { - for(unsigned int i = 0; i < offsets.Value().GetOffsetDimension(); i++) - { - unsigned int distance = vnl_math_abs(offsets.Value()[i]); - if(distance > minRadius) - { - minRadius = distance; - } - } + minRadius = distance; } + } + } - RadiusType radius; - radius.Fill(minRadius); + RadiusType radius; + radius.Fill(minRadius); - // Now fill in the histogram - this->FillHistogram(radius, m_Input->GetRequestedRegion()); + // Now fill in the histogram + this->FillHistogram(radius, m_Input->GetRequestedRegion()); - // Normalizse the histogram if requested - if(m_Normalize) - { - this->NormalizeHistogram(); - } + // Normalizse the histogram if requested + if(m_Normalize) + { + this->NormalizeHistogram(); + } - } +} - template< class TImageType, class THistogramFrequencyContainer > - void - ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer >:: - FillHistogram(RadiusType radius, RegionType region) - { - // Iterate over all of those pixels and offsets, adding each - // co-occurrence pair to the histogram +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer >:: +FillHistogram(RadiusType radius, RegionType region) +{ + // Iterate over all of those pixels and offsets, adding each + // co-occurrence pair to the histogram - typedef ConstNeighborhoodIterator<ImageType> NeighborhoodIteratorType; - NeighborhoodIteratorType neighborIt; - neighborIt = NeighborhoodIteratorType(radius, m_Input, region); + typedef ConstNeighborhoodIterator<ImageType> NeighborhoodIteratorType; + NeighborhoodIteratorType neighborIt; + neighborIt = NeighborhoodIteratorType(radius, m_Input, region); - for (neighborIt.GoToBegin(); !neighborIt.IsAtEnd(); ++neighborIt) - { - const PixelType centerPixelIntensity = neighborIt.GetCenterPixel(); - if (centerPixelIntensity < m_Min || - centerPixelIntensity > m_Max) - { - continue; // don't put a pixel in the histogram if the value - // is out-of-bounds. - } + for (neighborIt.GoToBegin(); !neighborIt.IsAtEnd(); ++neighborIt) + { + const PixelType centerPixelIntensity = neighborIt.GetCenterPixel(); + if (centerPixelIntensity < m_Min || + centerPixelIntensity > m_Max) + { + continue; // don't put a pixel in the histogram if the value + // is out-of-bounds. + } - typename OffsetVector::ConstIterator offsets; - for(offsets = m_Offsets->Begin(); offsets != m_Offsets->End(); offsets++) - { - bool pixelInBounds; - const PixelType pixelIntensity = - neighborIt.GetPixel(offsets.Value(), pixelInBounds); - - if (!pixelInBounds) - { - continue; // don't put a pixel in the histogram if it's out-of-bounds. - } + typename OffsetVector::ConstIterator offsets; + for(offsets = m_Offsets->Begin(); offsets != m_Offsets->End(); offsets++) + { + bool pixelInBounds; + const PixelType pixelIntensity = + neighborIt.GetPixel(offsets.Value(), pixelInBounds); - if (pixelIntensity < m_Min || - pixelIntensity > m_Max) - { - continue; // don't put a pixel in the histogram if the value - // is out-of-bounds. - } + if (!pixelInBounds) + { + continue; // don't put a pixel in the histogram if it's out-of-bounds. + } - // Now make both possible co-occurrence combinations and increment the - // histogram with them. - MeasurementVectorType cooccur; - cooccur[0] = centerPixelIntensity; - cooccur[1] = pixelIntensity; - m_Output->IncreaseFrequency(cooccur, 1); - cooccur[1] = centerPixelIntensity; - cooccur[0] = pixelIntensity; - m_Output->IncreaseFrequency(cooccur, 1); - } + if (pixelIntensity < m_Min || + pixelIntensity > m_Max) + { + continue; // don't put a pixel in the histogram if the value + // is out-of-bounds. } + + // Now make both possible co-occurrence combinations and increment the + // histogram with them. + MeasurementVectorType cooccur; + cooccur[0] = centerPixelIntensity; + cooccur[1] = pixelIntensity; + m_Output->IncreaseFrequency(cooccur, 1); + cooccur[1] = centerPixelIntensity; + cooccur[0] = pixelIntensity; + m_Output->IncreaseFrequency(cooccur, 1); } + } +} - template< class TImageType, class THistogramFrequencyContainer > - void - ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer >:: - NormalizeHistogram( void ) - { - typename HistogramType::Iterator hit; - typename HistogramType::FrequencyType totalFrequency = - m_Output->GetTotalFrequency(); +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer >:: +NormalizeHistogram( void ) +{ + typename HistogramType::Iterator hit; + typename HistogramType::FrequencyType totalFrequency = + m_Output->GetTotalFrequency(); - for (hit = m_Output->Begin(); hit != m_Output->End(); ++hit) - { - hit.SetFrequency(hit.GetFrequency() / totalFrequency); - } - } + for (hit = m_Output->Begin(); hit != m_Output->End(); ++hit) + { + hit.SetFrequency(hit.GetFrequency() / totalFrequency); + } +} - template< class TImageType, class THistogramFrequencyContainer > - void - ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer >:: - SetPixelValueMinMax( PixelType min, PixelType max ) - { - itkDebugMacro("setting Min to " << min << "and Max to " << max); - m_Min = min; - m_Max = max; - m_LowerBound.Fill(min); - m_UpperBound.Fill(max + 1); - this->Modified(); - } +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer >:: +SetPixelValueMinMax( PixelType min, PixelType max ) +{ + itkDebugMacro("setting Min to " << min << "and Max to " << max); + m_Min = min; + m_Max = max; + m_LowerBound.Fill(min); + m_UpperBound.Fill(max + 1); + this->Modified(); +} - template< class TImageType, class THistogramFrequencyContainer > - void - ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, - THistogramFrequencyContainer >:: - PrintSelf(std::ostream& os, Indent indent) const - { - Superclass::PrintSelf(os,indent); - } +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToGreyLevelCooccurrenceMatrixGenerator< TImageType, + THistogramFrequencyContainer >:: +PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} - } // end of namespace Statistics +} // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToHistogramGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToHistogramGenerator.h index 4c51c8ef3c..415907570a 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToHistogramGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToHistogramGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageToHistogramGenerator.h,v $ Language: C++ - Date: $Date: 2009-01-16 11:37:58 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,16 +35,16 @@ class ScalarImageToHistogramGenerator : public Object { public: /** Standard typedefs */ - typedef ScalarImageToHistogramGenerator Self ; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef ScalarImageToHistogramGenerator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(ScalarImageToHistogramGenerator, Object) ; + itkTypeMacro(ScalarImageToHistogramGenerator, Object); /** standard New() method support */ - itkNewMacro(Self) ; + itkNewMacro(Self); typedef TImageType ImageType; typedef itk::Statistics::ScalarImageToListAdaptor< diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToHistogramGenerator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToHistogramGenerator.txx index c5f6403fca..f5addd1cc6 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToHistogramGenerator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToHistogramGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageToHistogramGenerator.txx,v $ Language: C++ - Date: $Date: 2006-03-14 22:01:52 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,8 +14,8 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkScalarImageToHistogramGenerator_txx -#define _itkScalarImageToHistogramGenerator_txx +#ifndef __itkScalarImageToHistogramGenerator_txx +#define __itkScalarImageToHistogramGenerator_txx #include "itkScalarImageToHistogramGenerator.h" @@ -33,8 +33,6 @@ ScalarImageToHistogramGenerator< TImage > m_HistogramGenerator->SetListSample( m_ImageToListAdaptor ); } - - template < class TImage > void ScalarImageToHistogramGenerator< TImage > @@ -52,8 +50,6 @@ ScalarImageToHistogramGenerator< TImage > return m_HistogramGenerator->GetOutput(); } - - template < class TImage > void ScalarImageToHistogramGenerator< TImage > @@ -62,8 +58,6 @@ ScalarImageToHistogramGenerator< TImage > m_HistogramGenerator->Update(); } - - template < class TImage > void ScalarImageToHistogramGenerator< TImage > @@ -98,8 +92,6 @@ ScalarImageToHistogramGenerator< TImage > m_HistogramGenerator->SetHistogramMax( maxVector ); } - - template < class TImage > void ScalarImageToHistogramGenerator< TImage > @@ -108,9 +100,6 @@ ScalarImageToHistogramGenerator< TImage > m_HistogramGenerator->SetMarginalScale( marginalScale ); } - - - template < class TImage > void ScalarImageToHistogramGenerator< TImage > @@ -121,11 +110,7 @@ ScalarImageToHistogramGenerator< TImage > os << "HistogramGenerator = " << m_HistogramGenerator << std::endl; } - - } // end of namespace Statistics } // end of namespace itk #endif - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToListAdaptor.h b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToListAdaptor.h index 6dd20d3b51..187dff6cc4 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToListAdaptor.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToListAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageToListAdaptor.h,v $ Language: C++ - Date: $Date: 2008-08-19 22:27:57 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,8 +27,8 @@ #include "itkFixedArray.h" #include "itkMacro.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class ScalarImageToListAdaptor * \brief This class provides ListSampleBase interfaces to ITK Image @@ -69,10 +69,10 @@ public: typedef FixedArray< typename TImage::PixelType, 1 > MeasurementVectorType; /** Standard class typedefs */ - typedef ScalarImageToListAdaptor Self; + typedef ScalarImageToListAdaptor Self; typedef ImageToListAdaptor< TImage, MeasurementVectorType > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(ScalarImageToListAdaptor, ListSampleBase); @@ -86,11 +86,11 @@ public: /** Superclass typedefs for Measurement vector, measurement, * Instance Identifier, frequency, size, size element value */ - typedef typename Superclass::FrequencyType FrequencyType; - typedef typename Superclass::MeasurementType MeasurementType; - typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + typedef typename Superclass::FrequencyType FrequencyType; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; - typedef MeasurementVectorType ValueType; + typedef MeasurementVectorType ValueType; virtual void SetMeasurementVectorSize( const MeasurementVectorSizeType s ) { diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToListAdaptor.txx b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToListAdaptor.txx index 5deb897c68..5c393c12a7 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToListAdaptor.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkScalarImageToListAdaptor.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageToListAdaptor.txx,v $ Language: C++ - Date: $Date: 2008-08-19 22:27:57 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,11 +14,11 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkScalarImageToListAdaptor_txx -#define _itkScalarImageToListAdaptor_txx +#ifndef __itkScalarImageToListAdaptor_txx +#define __itkScalarImageToListAdaptor_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template < class TImage > void @@ -48,6 +48,3 @@ ScalarImageToListAdaptor< TImage > } // end of namespace itk #endif - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSelectiveSubsampleGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkSelectiveSubsampleGenerator.h index 6668e16dc2..f35bcaef7c 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSelectiveSubsampleGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSelectiveSubsampleGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSelectiveSubsampleGenerator.h,v $ Language: C++ - Date: $Date: 2003-12-15 01:00:46 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include "itkObject.h" #include "itkMembershipSample.h" -namespace itk{ - namespace Statistics{ +namespace itk { +namespace Statistics { /** \class SelectiveSubsampleGenerator * \brief SelectiveSubsampleGenerator generates a Subsample object @@ -52,59 +52,59 @@ class ITK_EXPORT SelectiveSubsampleGenerator : public: /** Standard class typedefs. */ typedef SelectiveSubsampleGenerator Self; - typedef Object Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(SelectiveSubsampleGenerator, Object); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Input sample types alias */ - typedef typename TInputSample::MeasurementVectorType MeasurementVectorType ; + typedef typename TInputSample::MeasurementVectorType MeasurementVectorType; - typedef typename TClassMaskSample::MeasurementType ClassLabelType ; - typedef std::vector< ClassLabelType > ClassLabelVectorType ; + typedef typename TClassMaskSample::MeasurementType ClassLabelType; + typedef std::vector< ClassLabelType > ClassLabelVectorType; /** Output: MembershipSample types */ - typedef Subsample< TInputSample > OutputType ; - typedef typename OutputType::Pointer OutputPointer ; + typedef Subsample< TInputSample > OutputType; + typedef typename OutputType::Pointer OutputPointer; /** Stores the input sample */ - void SetInput(TInputSample* sample) ; + void SetInput(TInputSample* sample); /** Returns the input sample pointer */ - TInputSample* GetInput() ; + TInputSample* GetInput(); /** Stores the class mask sample */ - void SetClassMask(const TClassMaskSample* classMask) ; + void SetClassMask(const TClassMaskSample* classMask); - /** Returns the class mask sample pointer*/ + /** Returns the class mask sample pointer */ const TClassMaskSample* GetClassMask() const; void SetSelectedClassLabels( const ClassLabelVectorType& classLabels ) - { m_SelectedClassLabels = classLabels ; } + { m_SelectedClassLabels = classLabels; } /** Returns the pointer to the MembershipSample object * that has been generated by this */ const OutputType * GetOutput() const; /** The actual output generation procedure. */ - void GenerateData() ; + void GenerateData(); protected: - SelectiveSubsampleGenerator() ; + SelectiveSubsampleGenerator(); virtual ~SelectiveSubsampleGenerator() {} void PrintSelf(std::ostream& os, Indent indent) const; private: - TInputSample* m_Input ; - const TClassMaskSample* m_ClassMask ; - ClassLabelVectorType m_SelectedClassLabels ; - OutputPointer m_Output ; -} ; // end of class + TInputSample* m_Input; + const TClassMaskSample* m_ClassMask; + ClassLabelVectorType m_SelectedClassLabels; + OutputPointer m_Output; +}; // end of class - } // end namespace Statistics +} // end namespace Statistics } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSelectiveSubsampleGenerator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkSelectiveSubsampleGenerator.txx index 15bef55c45..e5cdd87905 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSelectiveSubsampleGenerator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSelectiveSubsampleGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSelectiveSubsampleGenerator.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:05 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,16 +19,16 @@ #include "itkSelectiveSubsampleGenerator.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TInputSample, class TClassMaskSample > SelectiveSubsampleGenerator< TInputSample, TClassMaskSample > ::SelectiveSubsampleGenerator() { - m_Input = 0 ; - m_ClassMask = 0 ; - m_Output = OutputType::New() ; + m_Input = 0; + m_ClassMask = 0; + m_Output = OutputType::New(); } template< class TInputSample, class TClassMaskSample > @@ -38,33 +38,33 @@ SelectiveSubsampleGenerator< TInputSample, TClassMaskSample > { Superclass::PrintSelf(os,indent); - os << indent << "Input: " ; + os << indent << "Input: "; if ( m_Input != 0 ) { os << m_Input << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "ClassMask: " ; + os << indent << "ClassMask: "; if ( m_ClassMask != 0 ) { - os << m_ClassMask << std::endl ; + os << m_ClassMask << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } os << indent << "Output: " << m_Output << std::endl; - os << indent << "SelectedClassLabels: " ; - for ( unsigned int i = 0 ; i < m_SelectedClassLabels.size() ; ++i ) + os << indent << "SelectedClassLabels: "; + for ( unsigned int i = 0; i < m_SelectedClassLabels.size(); ++i ) { - os << " " << m_SelectedClassLabels[i] ; + os << " " << m_SelectedClassLabels[i]; } - os << std::endl ; + os << std::endl; } template< class TInputSample, class TClassMaskSample > @@ -78,7 +78,7 @@ SelectiveSubsampleGenerator< TInputSample, TClassMaskSample > itkExceptionMacro( << "Measurement vector length of input sample must be non-zero."); } - m_Input = sample ; + m_Input = sample; } template< class TInputSample, class TClassMaskSample > @@ -86,7 +86,7 @@ TInputSample* SelectiveSubsampleGenerator< TInputSample, TClassMaskSample > ::GetInput() { - return m_Input ; + return m_Input; } template< class TInputSample, class TClassMaskSample > @@ -100,7 +100,7 @@ SelectiveSubsampleGenerator< TInputSample, TClassMaskSample > itkExceptionMacro( << "Class mask measurement vector length of input sample must be 1."); } - m_ClassMask = classMask ; + m_ClassMask = classMask; } template< class TInputSample, class TClassMaskSample > @@ -108,7 +108,7 @@ const TClassMaskSample* SelectiveSubsampleGenerator< TInputSample, TClassMaskSample > ::GetClassMask() const { - return m_ClassMask ; + return m_ClassMask; } template< class TInputSample, class TClassMaskSample > @@ -116,7 +116,7 @@ const typename SelectiveSubsampleGenerator< TInputSample, TClassMaskSample >::Ou SelectiveSubsampleGenerator< TInputSample, TClassMaskSample > ::GetOutput() const { - return m_Output.GetPointer() ; + return m_Output.GetPointer(); } template< class TInputSample, class TClassMaskSample > @@ -124,8 +124,8 @@ void SelectiveSubsampleGenerator< TInputSample, TClassMaskSample > ::GenerateData() { - m_Output->SetSample(m_Input) ; - typename TClassMaskSample::ConstIterator iter = m_ClassMask->Begin() ; + m_Output->SetSample(m_Input); + typename TClassMaskSample::ConstIterator iter = m_ClassMask->Begin(); while (iter != m_ClassMask->End()) { if ( std::find(m_SelectedClassLabels.begin(), @@ -133,9 +133,9 @@ SelectiveSubsampleGenerator< TInputSample, TClassMaskSample > iter.GetMeasurementVector()[0]) != m_SelectedClassLabels.end() ) { - m_Output->AddInstance(iter.GetInstanceIdentifier()) ; + m_Output->AddInstance(iter.GetInstanceIdentifier()); } - ++iter ; + ++iter; } } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.cxx b/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.cxx index fe52617828..80185d68f4 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.cxx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSparseFrequencyContainer.cxx,v $ Language: C++ - Date: $Date: 2007-05-08 14:20:29 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,7 @@ namespace Statistics{ SparseFrequencyContainer ::SparseFrequencyContainer() { - m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero ; + m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero; } void @@ -44,7 +44,7 @@ SparseFrequencyContainer iter->second = NumericTraits< FrequencyType >::Zero; ++iter; } - m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero ; + m_TotalFrequency = NumericTraits< TotalFrequencyType >::Zero; } bool @@ -53,9 +53,9 @@ SparseFrequencyContainer { // No need to test for bounds because in a map container the // element is allocated if the key doesn't exist yet - FrequencyType frequency = this->GetFrequency(id) ; - m_FrequencyContainer[id] = value ; - m_TotalFrequency += (value - frequency) ; + FrequencyType frequency = this->GetFrequency(id); + m_FrequencyContainer[id] = value; + m_TotalFrequency += (value - frequency); return true; } @@ -63,10 +63,10 @@ SparseFrequencyContainer::FrequencyType SparseFrequencyContainer ::GetFrequency(const InstanceIdentifier id) const { - FrequencyContainerType::const_iterator iter = m_FrequencyContainer.find(id) ; + FrequencyContainerType::const_iterator iter = m_FrequencyContainer.find(id); if ( iter != m_FrequencyContainer.end() ) { - return iter->second ; + return iter->second; } else { @@ -80,9 +80,9 @@ SparseFrequencyContainer { // No need to test for bounds because in a map container the // element is allocated if the key doesn't exist yet - FrequencyType frequency = this->GetFrequency(id) ; - m_FrequencyContainer[id] = frequency + value ; - m_TotalFrequency += value ; + FrequencyType frequency = this->GetFrequency(id); + m_FrequencyContainer[id] = frequency + value; + m_TotalFrequency += value; return true; } @@ -95,4 +95,3 @@ SparseFrequencyContainer } // end of namespace Statistics } // end of namespace itk - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.h b/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.h index d708ab663d..3699a71914 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSparseFrequencyContainer.h,v $ Language: C++ - Date: $Date: 2005-09-30 14:14:19 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,8 +22,8 @@ #include "itkObject.h" #include "itkNumericTraits.h" -namespace itk{ - namespace Statistics{ +namespace itk { +namespace Statistics { /** \class SparseFrequencyContainer * \brief his class is a container for an histogram. @@ -38,38 +38,38 @@ class ITK_EXPORT SparseFrequencyContainer : public Object public: /** Standard class typedefs. */ typedef SparseFrequencyContainer Self; - typedef Object Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard macros */ itkTypeMacro(SparseFrequencyContainer, Object); itkNewMacro(Self); /** instance idenfitifer alias */ - typedef unsigned long InstanceIdentifier ; + typedef unsigned long InstanceIdentifier; /** frequency type alias */ - typedef float FrequencyType ; + typedef float FrequencyType; - /** Total frequency type*/ - typedef NumericTraits<FrequencyType>::AccumulateType TotalFrequencyType ; + /** Total frequency type */ + typedef NumericTraits<FrequencyType>::AccumulateType TotalFrequencyType; /** Histogram typedef support */ - typedef std::map< InstanceIdentifier, FrequencyType > FrequencyContainerType ; + typedef std::map< InstanceIdentifier, FrequencyType > FrequencyContainerType; typedef FrequencyContainerType::const_iterator - FrequencyContainerConstIterator ; + FrequencyContainerConstIterator; /** prepares the frequency container */ - void Initialize(unsigned long length) ; + void Initialize(unsigned long length); /** Calls the SetToZero method of superclass to initialize all the bins to Zero. * This should be done before starting to call the IncreaseFrequency method. */ - void SetToZero() ; + void SetToZero(); /** Method to set the frequency of histogram using instance identifier. It * returns false when the Id is out of bounds */ - bool SetFrequency(const InstanceIdentifier id, const FrequencyType value) ; + bool SetFrequency(const InstanceIdentifier id, const FrequencyType value); /** Method to increase the frequency by one. This function is convinent * to create a histogram. It returns false when the id is out of bounds. */ @@ -78,26 +78,26 @@ public: /** Method to get the frequency of a bin from the histogram. It will return * zero when the Id is out of bounds. */ - FrequencyType GetFrequency(const InstanceIdentifier id) const ; + FrequencyType GetFrequency(const InstanceIdentifier id) const; TotalFrequencyType GetTotalFrequency() - { return m_TotalFrequency ; } + { return m_TotalFrequency; } protected: - SparseFrequencyContainer() ; + SparseFrequencyContainer(); virtual ~SparseFrequencyContainer() {} void PrintSelf(std::ostream& os, Indent indent) const; private: - SparseFrequencyContainer(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + SparseFrequencyContainer(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented // Container of histogram - FrequencyContainerType m_FrequencyContainer ; - TotalFrequencyType m_TotalFrequency ; -} ; // end of class + FrequencyContainerType m_FrequencyContainer; + TotalFrequencyType m_TotalFrequency; +}; // end of class - } // end of namespace Statistics +} // end of namespace Statistics } // end of namespace itk #endif diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkStatisticsAlgorithm.h b/Utilities/ITK/Code/Numerics/Statistics/itkStatisticsAlgorithm.h index 13d26954b1..a768d7a6cf 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkStatisticsAlgorithm.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkStatisticsAlgorithm.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkStatisticsAlgorithm.h,v $ Language: C++ - Date: $Date: 2008-04-29 18:33:57 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,23 +20,23 @@ #include "itkSample.h" #include "itkSubsample.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { #if !defined(_MSC_VER) template< class TSize > -TSize FloorLog(TSize size) ; +TSize FloorLog(TSize size); template< class TValue > -TValue MedianOfThree(const TValue a, const TValue b, const TValue c) ; +TValue MedianOfThree(const TValue a, const TValue b, const TValue c); template< class TSample > void FindSampleBound(const TSample* sample, typename TSample::ConstIterator begin, typename TSample::ConstIterator end, typename TSample::MeasurementVectorType &min, - typename TSample::MeasurementVectorType &max) ; + typename TSample::MeasurementVectorType &max); template< class TSubsample > void FindSampleBoundAndMean(const TSubsample* sample, @@ -44,7 +44,7 @@ void FindSampleBoundAndMean(const TSubsample* sample, int endIndex, typename TSubsample::MeasurementVectorType &min, typename TSubsample::MeasurementVectorType &max, - typename TSubsample::MeasurementVectorType &mean) ; + typename TSubsample::MeasurementVectorType &mean); /** The Partition algorithm performs partial sorting in a sample. Given a * partitionValue, the algorithm moves to the beginning of the sample all @@ -62,7 +62,7 @@ template< class TSubsample > int Partition(TSubsample* sample, unsigned int activeDimension, int beginIndex, int endIndex, - const typename TSubsample::MeasurementType partitionValue) ; + const typename TSubsample::MeasurementType partitionValue); /** QuickSelect is an algorithm for finding the k-th largest element of a list. * In this case, only of the components of the measurement vectors is @@ -78,7 +78,7 @@ QuickSelect(TSubsample* sample, unsigned int activeDimension, int beginIndex, int endIndex, int kth, - typename TSubsample::MeasurementType medianGuess) ; + typename TSubsample::MeasurementType medianGuess); /** QuickSelect is an algorithm for finding the k-th largest element of a list. * In this case, only of the components of the measurement vectors is @@ -91,7 +91,7 @@ typename TSubsample::MeasurementType QuickSelect(TSubsample* sample, unsigned int activeDimension, int beginIndex, int endIndex, - int kth) ; + int kth); /** NthElement is an algorithm for finding the n-th largest element of a list. * In this case, only of the components of the measurement vectors is @@ -109,17 +109,17 @@ NthElement(TSubsample* sample, template< class TSubsample > void InsertSort(TSubsample* sample, unsigned int activeDimension, - int beginIndex, int endIndex) ; + int beginIndex, int endIndex); template< class TSubsample > void DownHeap(TSubsample* sample, unsigned int activeDimension, - int beginIndex, int endIndex, int node) ; + int beginIndex, int endIndex, int node); template< class TSubsample > void HeapSort(TSubsample* sample, unsigned int activeDimension, - int beginIndex, int endIndex) ; + int beginIndex, int endIndex); template< class TSubsample > @@ -128,13 +128,13 @@ void IntrospectiveSortLoop(TSubsample* sample, int beginIndex, int endIndex, int depthLimit, - int sizeThreshold) ; + int sizeThreshold); template< class TSubsample > void IntrospectiveSort(TSubsample* sample, unsigned int activeDimension, int beginIndex, int endIndex, - int sizeThreshold) ; + int sizeThreshold); #endif // #if defined(_MSC_VER) @@ -146,6 +146,3 @@ void IntrospectiveSort(TSubsample* sample, #endif #endif // #ifndef __itkStatisticsAlgorithm_h - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkStatisticsAlgorithm.txx b/Utilities/ITK/Code/Numerics/Statistics/itkStatisticsAlgorithm.txx index 0e9efed62a..54a8ed7e1e 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkStatisticsAlgorithm.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkStatisticsAlgorithm.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkStatisticsAlgorithm.txx,v $ Language: C++ - Date: $Date: 2008-04-29 23:00:07 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,13 +20,13 @@ #include "itkStatisticsAlgorithm.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSize > inline TSize FloorLog(TSize size) { - TSize k ; + TSize k; for (k = 0; size != 1; size >>= 1) { @@ -194,7 +194,7 @@ inline int Partition(TSubsample* sample, MeasurementType boundaryValue = sample->GetMeasurementVectorByIndex( storeIndex )[activeDimension]; if( nodeValue > boundaryValue ) { - sample->Swap(kk, storeIndex) ; + sample->Swap(kk, storeIndex); } } @@ -221,7 +221,7 @@ inline TValue MedianOfThree(const TValue a, } } else if (a < c) { - return a ; + return a; } else if (b < c) { return c; @@ -237,7 +237,7 @@ inline void FindSampleBound(const TSample* sample, typename TSample::ConstIterator end, typename TSample::MeasurementVectorType &min, typename TSample::MeasurementVectorType &max) -{ +{ typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; const MeasurementVectorSizeType Dimension = sample->GetMeasurementVectorSize(); @@ -253,28 +253,28 @@ inline void FindSampleBound(const TSample* sample, "Length mismatch StatisticsAlgorithm::FindSampleBound"); unsigned int dimension; - typename TSample::MeasurementVectorType temp ; + typename TSample::MeasurementVectorType temp; - min = max = temp = begin.GetMeasurementVector() ; + min = max = temp = begin.GetMeasurementVector(); while (true) { - for (dimension= 0 ; dimension < Dimension ; dimension++) + for (dimension= 0; dimension < Dimension; dimension++) { if ( temp[dimension] < min[dimension]) { - min[dimension] = temp[dimension] ; + min[dimension] = temp[dimension]; } else if (temp[dimension] > max[dimension]) { - max[dimension] = temp[dimension] ; + max[dimension] = temp[dimension]; } } - ++begin ; + ++begin; if (begin == end) { - break ; + break; } - temp = begin.GetMeasurementVector() ; + temp = begin.GetMeasurementVector(); } // end of while } @@ -287,9 +287,9 @@ FindSampleBoundAndMean(const TSubsample* sample, typename TSubsample::MeasurementVectorType &min, typename TSubsample::MeasurementVectorType &max, typename TSubsample::MeasurementVectorType &mean) -{ - typedef typename TSubsample::MeasurementType MeasurementType ; - typedef typename TSubsample::MeasurementVectorType MeasurementVectorType ; +{ + typedef typename TSubsample::MeasurementType MeasurementType; + typedef typename TSubsample::MeasurementVectorType MeasurementVectorType; typedef typename TSubsample::MeasurementVectorSizeType MeasurementVectorSizeType; const MeasurementVectorSizeType Dimension = sample->GetMeasurementVectorSize(); @@ -299,43 +299,43 @@ FindSampleBoundAndMean(const TSubsample* sample, << "Length of a sample's measurement vector hasn't been set."); } - Array< double > sum( Dimension ) ; + Array< double > sum( Dimension ); - MeasurementVectorSizeType dimension ; + MeasurementVectorSizeType dimension; MeasurementVectorType temp; MeasurementVectorTraits::SetLength( temp, Dimension ); MeasurementVectorTraits::SetLength( mean, Dimension ); - min = max = temp = sample->GetMeasurementVectorByIndex(beginIndex) ; - double frequencySum = sample->GetFrequencyByIndex(beginIndex) ; - sum.Fill(0.0) ; + min = max = temp = sample->GetMeasurementVectorByIndex(beginIndex); + double frequencySum = sample->GetFrequencyByIndex(beginIndex); + sum.Fill(0.0); while (true) { - for (dimension= 0 ; dimension < Dimension ; dimension++) + for (dimension= 0; dimension < Dimension; dimension++) { if ( temp[dimension] < min[dimension]) { - min[dimension] = temp[dimension] ; + min[dimension] = temp[dimension]; } else if (temp[dimension] > max[dimension]) { - max[dimension] = temp[dimension] ; + max[dimension] = temp[dimension]; } - sum[dimension] += temp[dimension] ; + sum[dimension] += temp[dimension]; } - ++beginIndex ; + ++beginIndex; if (beginIndex == endIndex) { - break ; + break; } - temp = sample->GetMeasurementVectorByIndex(beginIndex) ; - frequencySum += sample->GetFrequencyByIndex(beginIndex) ; + temp = sample->GetMeasurementVectorByIndex(beginIndex); + frequencySum += sample->GetFrequencyByIndex(beginIndex); } // end of while - for (unsigned int i = 0 ; i < Dimension ; i++) + for (unsigned int i = 0; i < Dimension; i++) { - mean[i] = (MeasurementType)(sum[i] / frequencySum) ; + mean[i] = (MeasurementType)(sum[i] / frequencySum); } } @@ -353,10 +353,10 @@ QuickSelect(TSubsample* sample, int kth, typename TSubsample::MeasurementType medianGuess) { - typedef typename TSubsample::MeasurementType MeasurementType ; + typedef typename TSubsample::MeasurementType MeasurementType; - int begin = beginIndex ; - int end = endIndex - 1 ; + int begin = beginIndex; + int end = endIndex - 1; int kthIndex = kth + beginIndex; MeasurementType tempMedian; @@ -366,11 +366,11 @@ QuickSelect(TSubsample* sample, // if (medianGuess != NumericTraits< MeasurementType >::NonpositiveMin()) { - tempMedian = medianGuess ; + tempMedian = medianGuess; } else { - const int length = end - begin ; + const int length = end - begin; const int middle = begin + length / 2; const MeasurementType v1 = sample->GetMeasurementVectorByIndex(begin)[activeDimension]; const MeasurementType v2 = sample->GetMeasurementVectorByIndex(end)[activeDimension]; @@ -383,7 +383,7 @@ QuickSelect(TSubsample* sample, // Partition expects the end argument to be one past-the-end of the array. // The index pivotNewIndex returned by Partition is in the range [begin,end]. int pivotNewIndex = - Partition< TSubsample >(sample, activeDimension, begin, end+1, tempMedian) ; + Partition< TSubsample >(sample, activeDimension, begin, end+1, tempMedian); if( kthIndex == pivotNewIndex ) { @@ -404,7 +404,7 @@ QuickSelect(TSubsample* sample, break; } - const int length = end - begin ; + const int length = end - begin; const MeasurementType v1 = sample->GetMeasurementVectorByIndex(begin)[activeDimension]; const MeasurementType v2 = sample->GetMeasurementVectorByIndex(end)[activeDimension]; @@ -413,7 +413,7 @@ QuickSelect(TSubsample* sample, { if( v2 < v1 ) { - sample->Swap(begin, end) ; + sample->Swap(begin, end); } break; } @@ -462,7 +462,7 @@ NthElement(TSubsample* sample, { const int begin = beginElement; const int end = endElement-1; - const int length = endElement - beginElement ; + const int length = endElement - beginElement; const int middle = beginElement + length / 2; const MeasurementType v1 = sample->GetMeasurementVectorByIndex(begin)[activeDimension]; @@ -538,26 +538,26 @@ inline void InsertSort(TSubsample* sample, int beginIndex, int endIndex) { - int backwardSearchBegin ; - int backwardIndex ; + int backwardSearchBegin; + int backwardIndex; - for (backwardSearchBegin = beginIndex + 1 ; - backwardSearchBegin < endIndex ; + for (backwardSearchBegin = beginIndex + 1; + backwardSearchBegin < endIndex; backwardSearchBegin++) { - backwardIndex = backwardSearchBegin ; + backwardIndex = backwardSearchBegin; while (backwardIndex > beginIndex) { if (sample->GetMeasurementVectorByIndex(backwardIndex)[activeDimension] < sample->GetMeasurementVectorByIndex(backwardIndex - 1)[activeDimension]) { - sample->Swap(backwardIndex, backwardIndex - 1) ; + sample->Swap(backwardIndex, backwardIndex - 1); } else { - break ; + break; } - --backwardIndex ; + --backwardIndex; } } } @@ -568,51 +568,51 @@ inline void DownHeap(TSubsample* sample, int beginIndex, int endIndex, int node) { int currentNode = node; - int leftChild ; - int rightChild ; - int largerChild ; - typedef typename TSubsample::MeasurementType MeasurementType ; + int leftChild; + int rightChild; + int largerChild; + typedef typename TSubsample::MeasurementType MeasurementType; MeasurementType currentNodeValue = - sample->GetMeasurementVectorByIndex(currentNode)[activeDimension] ; - MeasurementType leftChildValue ; - MeasurementType rightChildValue ; - MeasurementType largerChildValue ; + sample->GetMeasurementVectorByIndex(currentNode)[activeDimension]; + MeasurementType leftChildValue; + MeasurementType rightChildValue; + MeasurementType largerChildValue; while (true) { // location of first child largerChild = leftChild = - beginIndex + 2*(currentNode - beginIndex) + 1 ; - rightChild = leftChild + 1 ; + beginIndex + 2*(currentNode - beginIndex) + 1; + rightChild = leftChild + 1; if (leftChild > endIndex - 1) { // leaf node - return ; + return; } largerChildValue = rightChildValue = leftChildValue = - sample->GetMeasurementVectorByIndex(leftChild)[activeDimension] ; + sample->GetMeasurementVectorByIndex(leftChild)[activeDimension]; if (rightChild < endIndex) { rightChildValue = - sample->GetMeasurementVectorByIndex(rightChild)[activeDimension] ; + sample->GetMeasurementVectorByIndex(rightChild)[activeDimension]; } if (leftChildValue < rightChildValue) { - largerChild = rightChild ; - largerChildValue = rightChildValue ; + largerChild = rightChild; + largerChildValue = rightChildValue; } if (largerChildValue <= currentNodeValue) { // the node satisfies heap property - return ; + return; } // move down current node value to the larger child - sample->Swap(currentNode, largerChild) ; - currentNode = largerChild ; + sample->Swap(currentNode, largerChild); + currentNode = largerChild; } } @@ -623,18 +623,18 @@ inline void HeapSort(TSubsample* sample, int endIndex) { // construct a heap - int node ; + int node; - for (node = beginIndex + (endIndex - beginIndex) / 2 - 1 ; - node >= beginIndex ; node--) + for (node = beginIndex + (endIndex - beginIndex) / 2 - 1; + node >= beginIndex; node--) { DownHeap< TSubsample >(sample, activeDimension, - beginIndex, endIndex, node) ; + beginIndex, endIndex, node); } // sort - int newEndIndex ; - for (newEndIndex = endIndex - 1 ; newEndIndex >= beginIndex ; + int newEndIndex; + for (newEndIndex = endIndex - 1; newEndIndex >= beginIndex; --newEndIndex) { sample->Swap(beginIndex, newEndIndex); @@ -652,31 +652,31 @@ inline void IntrospectiveSortLoop(TSubsample* sample, int depthLimit, int sizeThreshold) { - typedef typename TSubsample::MeasurementType MeasurementType ; + typedef typename TSubsample::MeasurementType MeasurementType; - int length = endIndex - beginIndex ; - int cut ; + int length = endIndex - beginIndex; + int cut; while(length > sizeThreshold) { if (depthLimit == 0) { HeapSort< TSubsample >(sample, activeDimension, - beginIndex, endIndex) ; - return ; + beginIndex, endIndex); + return; } - --depthLimit ; + --depthLimit; cut = Partition< TSubsample >(sample, activeDimension, beginIndex, endIndex, MedianOfThree< MeasurementType > (sample->GetMeasurementVectorByIndex(beginIndex)[activeDimension], sample->GetMeasurementVectorByIndex(beginIndex + length/2)[activeDimension], - sample->GetMeasurementVectorByIndex(endIndex - 1)[activeDimension])) ; + sample->GetMeasurementVectorByIndex(endIndex - 1)[activeDimension])); IntrospectiveSortLoop< TSubsample >(sample, activeDimension, cut, endIndex, - depthLimit, sizeThreshold) ; - endIndex = cut ; - length = endIndex - beginIndex ; + depthLimit, sizeThreshold); + endIndex = cut; + length = endIndex - beginIndex; } } @@ -687,23 +687,13 @@ inline void IntrospectiveSort(TSubsample* sample, int endIndex, int sizeThreshold) { - typedef typename TSubsample::MeasurementType MeasurementType ; + typedef typename TSubsample::MeasurementType MeasurementType; IntrospectiveSortLoop< TSubsample >(sample, activeDimension, beginIndex, endIndex, - 2 * FloorLog(endIndex - beginIndex), sizeThreshold) ; - InsertSort< TSubsample >(sample, activeDimension, beginIndex, endIndex) ; + 2 * FloorLog(endIndex - beginIndex), sizeThreshold); + InsertSort< TSubsample >(sample, activeDimension, beginIndex, endIndex); } } // end of namespace Statistics } // end of namespace itk #endif // #ifndef __itkStatisticsAlgorithm_txx - - - - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSubsample.h b/Utilities/ITK/Code/Numerics/Statistics/itkSubsample.h index df9834747e..3c2556c7f2 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSubsample.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSubsample.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSubsample.h,v $ Language: C++ - Date: $Date: 2006-08-17 17:57:22 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include "itkMacro.h" #include "itkObjectFactory.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class Subsample * \brief This class stores a subset of instance identifiers from another sample @@ -40,96 +40,97 @@ class ITK_EXPORT Subsample : { public: /** Standard class typedefs */ - typedef Subsample Self; - typedef Sample< typename TSample::MeasurementVectorType > Superclass ; - typedef SmartPointer< Self > Pointer ; - typedef SmartPointer<const Self> ConstPointer; + typedef Subsample Self; + typedef Sample< typename TSample::MeasurementVectorType > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; - /** Run-time type information (and related methods).*/ + /** Run-time type information (and related methods). */ itkTypeMacro(Subsample, Sample); /** standard New() method support */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** Smart pointer to the actual sample data holder */ - typedef typename TSample::Pointer SamplePointer ; + typedef typename TSample::Pointer SamplePointer; /** Typedefs for Measurement vector, measurement, Instance Identifier, - * frequency, size, size element value from the template argument TSample*/ + * frequency, size, size element value from the template argument + * TSample */ typedef typename TSample::MeasurementVectorType MeasurementVectorType; - typedef typename TSample::MeasurementType MeasurementType; - typedef typename TSample::InstanceIdentifier InstanceIdentifier; - typedef typename TSample::FrequencyType FrequencyType ; - typedef typename TSample::TotalFrequencyType TotalFrequencyType ; - typedef MeasurementVectorType ValueType ; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::InstanceIdentifier InstanceIdentifier; + typedef typename TSample::FrequencyType FrequencyType; + typedef typename TSample::TotalFrequencyType TotalFrequencyType; + typedef MeasurementVectorType ValueType; /** Type of the storage for instances that belong to the class * represented by a Subsample object. A Subsample object stores * only the InstanceIdentifiers. The actual data is still in the Sample * object */ - typedef std::vector< InstanceIdentifier > InstanceIdentifierHolder ; + typedef std::vector< InstanceIdentifier > InstanceIdentifierHolder; /** Plug in the actual sample data */ void SetSample(const TSample* sample) { - m_Sample = sample ; + m_Sample = sample; this->SetMeasurementVectorSize( m_Sample->GetMeasurementVectorSize() ); } const TSample* GetSample() const - { return m_Sample ; } + { return m_Sample; } void InitializeWithAllInstances() - { - m_IdHolder.resize(m_Sample->Size()) ; - typename InstanceIdentifierHolder::iterator idIter = m_IdHolder.begin() ; - typename TSample::ConstIterator iter = m_Sample->Begin() ; - typename TSample::ConstIterator last = m_Sample->End() ; - m_TotalFrequency = NumericTraits< FrequencyType >::Zero ; + { + m_IdHolder.resize(m_Sample->Size()); + typename InstanceIdentifierHolder::iterator idIter = m_IdHolder.begin(); + typename TSample::ConstIterator iter = m_Sample->Begin(); + typename TSample::ConstIterator last = m_Sample->End(); + m_TotalFrequency = NumericTraits< FrequencyType >::Zero; while (iter != last) { - *idIter++ = iter.GetInstanceIdentifier() ; - m_TotalFrequency += iter.GetFrequency() ; - ++iter ; + *idIter++ = iter.GetInstanceIdentifier(); + m_TotalFrequency += iter.GetFrequency(); + ++iter; } - } + } void AddInstance(InstanceIdentifier id) - { - m_IdHolder.push_back(id) ; - m_TotalFrequency += m_Sample->GetFrequency(id) ; - } + { + m_IdHolder.push_back(id); + m_TotalFrequency += m_Sample->GetFrequency(id); + } /** returns SizeType object whose each element is the number of * elements in each dimension */ unsigned int Size() const - { + { return static_cast<unsigned int>( m_IdHolder.size() ); - } + } void Clear() - { - m_IdHolder.clear() ; - m_TotalFrequency = NumericTraits< FrequencyType >::Zero ; - } + { + m_IdHolder.clear(); + m_TotalFrequency = NumericTraits< FrequencyType >::Zero; + } /** retunrs the measurement of the instance which is identified * by the 'id' */ const MeasurementVectorType & GetMeasurementVector(const InstanceIdentifier &id) const - { return m_Sample->GetMeasurementVector(id) ; } + { return m_Sample->GetMeasurementVector(id); } /** returns the frequency of the instance which is identified by the 'id' */ FrequencyType GetFrequency(const InstanceIdentifier &id) const - { return m_Sample->GetFrequency(id) ; } + { return m_Sample->GetFrequency(id); } /** returns the total frequency for the 'd' dimension */ TotalFrequencyType GetTotalFrequency() const - { return m_TotalFrequency ; } + { return m_TotalFrequency; } - void Swap(int index1, int index2) ; + void Swap(int index1, int index2); - MeasurementVectorType GetMeasurementVectorByIndex(int index) const ; + MeasurementVectorType GetMeasurementVectorByIndex(int index) const; FrequencyType GetFrequencyByIndex(int index) const; @@ -138,188 +139,178 @@ public: class ConstIterator; class Iterator - { + { friend class ConstIterator; - public: + public: Iterator(typename InstanceIdentifierHolder::iterator iter, Self* classSample) :m_Iter(iter), m_Subsample(classSample), - m_Sample(classSample->GetSample()) - {} + m_Sample(classSample->GetSample()) {} FrequencyType GetFrequency() const - { return m_Sample->GetFrequency(*m_Iter) ; } + { return m_Sample->GetFrequency(*m_Iter); } const MeasurementVectorType & GetMeasurementVector() const - { return m_Sample->GetMeasurementVector(*m_Iter) ; } + { return m_Sample->GetMeasurementVector(*m_Iter); } InstanceIdentifier GetInstanceIdentifier() const - { return *m_Iter ; } + { return *m_Iter; } Iterator& operator++() - { - ++m_Iter ; - return *this ; - } + { + ++m_Iter; + return *this; + } - //Iterator& operator+() - //{ m_Iter += n; return *this ;} - Iterator& operator+(int n) - { m_Iter += n; return *this ;} + { m_Iter += n; return *this;} Iterator& operator-(int n) - { m_Iter -= n; return *this ;} + { m_Iter -= n; return *this;} bool operator!=(const Iterator& it) - { return (m_Iter != it.m_Iter) ; } + { return (m_Iter != it.m_Iter); } bool operator==(const Iterator& it) - { return (m_Iter == it.m_Iter) ; } + { return (m_Iter == it.m_Iter); } Iterator& operator=(const Iterator& iter) - { + { m_Iter = iter.m_Iter; - m_Subsample = iter.m_Subsample ; - m_Sample = iter.m_Sample ; - return *this ; - } + m_Subsample = iter.m_Subsample; + m_Sample = iter.m_Sample; + return *this; + } Iterator(const Iterator& iter) - { + { m_Iter = iter.m_Iter; - m_Subsample = iter.m_Subsample ; - m_Sample = iter.m_Sample ; - } + m_Subsample = iter.m_Subsample; + m_Sample = iter.m_Sample; + } - private: - // Iterator pointing to ImageToListAdaptor - typename InstanceIdentifierHolder::iterator m_Iter ; - // Pointer to Subsample object - Self* m_Subsample ; - const TSample* m_Sample ; - } ; + private: + // Iterator pointing to ImageToListAdaptor + typename InstanceIdentifierHolder::iterator m_Iter; + // Pointer to Subsample object + Self* m_Subsample; + const TSample* m_Sample; + }; class ConstIterator - { - public: + { + public: ConstIterator(typename InstanceIdentifierHolder::const_iterator iter, - const Self* classSample) + const Self* classSample) :m_Iter(iter), m_Subsample(classSample), - m_Sample(classSample->GetSample()) - {} + m_Sample(classSample->GetSample()) {} FrequencyType GetFrequency() const - { return m_Sample->GetFrequency(*m_Iter) ; } + { return m_Sample->GetFrequency(*m_Iter); } const MeasurementVectorType & GetMeasurementVector() const - { return m_Sample->GetMeasurementVector(*m_Iter) ; } + { return m_Sample->GetMeasurementVector(*m_Iter); } InstanceIdentifier GetInstanceIdentifier() const - { return *m_Iter ; } + { return *m_Iter; } ConstIterator& operator++() - { - ++m_Iter ; - return *this ; - } + { + ++m_Iter; + return *this; + } - //ConstIterator& operator+() - //{ m_Iter += n; return *this ;} - ConstIterator& operator+(int n) - { m_Iter += n; return *this ;} + { m_Iter += n; return *this;} ConstIterator& operator-(int n) - { m_Iter -= n; return *this ;} + { m_Iter -= n; return *this;} bool operator!=(const ConstIterator& it) - { return (m_Iter != it.m_Iter) ; } + { return (m_Iter != it.m_Iter); } bool operator==(const ConstIterator& it) - { return (m_Iter == it.m_Iter) ; } + { return (m_Iter == it.m_Iter); } ConstIterator& operator=(const ConstIterator& iter) - { + { m_Iter = iter.m_Iter; - m_Subsample = iter.m_Subsample ; - m_Sample = iter.m_Sample ; - return *this ; - } + m_Subsample = iter.m_Subsample; + m_Sample = iter.m_Sample; + return *this; + } ConstIterator& operator=(const Iterator& iter) - { + { m_Iter = iter.m_Iter; - m_Subsample = iter.m_Subsample ; - m_Sample = iter.m_Sample ; - return *this ; - } + m_Subsample = iter.m_Subsample; + m_Sample = iter.m_Sample; + return *this; + } ConstIterator(const ConstIterator& iter) - { + { m_Iter = iter.m_Iter; - m_Subsample = iter.m_Subsample ; - m_Sample = iter.m_Sample ; - } + m_Subsample = iter.m_Subsample; + m_Sample = iter.m_Sample; + } ConstIterator(const Iterator& iter) - { + { m_Iter = iter.m_Iter; - m_Subsample = iter.m_Subsample ; - m_Sample = iter.m_Sample ; - } + m_Subsample = iter.m_Subsample; + m_Sample = iter.m_Sample; + } - private: + private: // ConstIterator pointing to ImageToListAdaptor - typename InstanceIdentifierHolder::const_iterator m_Iter ; + typename InstanceIdentifierHolder::const_iterator m_Iter; // Pointer to Subsample object - const Self* m_Subsample ; - const TSample* m_Sample ; - } ; - - + const Self* m_Subsample; + const TSample* m_Sample; + }; Iterator Begin() - { - Iterator iter(m_IdHolder.begin(), this) ; + { + Iterator iter(m_IdHolder.begin(), this); return iter; - } - - Iterator End() - { - Iterator iter(m_IdHolder.end(), this) ; + } + + Iterator End() + { + Iterator iter(m_IdHolder.end(), this); return iter; - } + } ConstIterator Begin() const - { - ConstIterator iter(m_IdHolder.begin(), this) ; + { + ConstIterator iter(m_IdHolder.begin(), this); return iter; - } + } ConstIterator End() const - { - ConstIterator iter(m_IdHolder.end(), this) ; + { + ConstIterator iter(m_IdHolder.end(), this); return iter; - } + } protected: - Subsample() ; + Subsample(); virtual ~Subsample() {} void PrintSelf(std::ostream& os, Indent indent) const; private: - Subsample(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + Subsample(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - const TSample* m_Sample ; - InstanceIdentifierHolder m_IdHolder ; - unsigned int m_ActiveDimension ; - FrequencyType m_TotalFrequency ; -} ; // end of class + const TSample* m_Sample; + InstanceIdentifierHolder m_IdHolder; + unsigned int m_ActiveDimension; + FrequencyType m_TotalFrequency; +}; // end of class } // end of namespace Statistics @@ -331,10 +322,3 @@ private: #endif #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSubsample.txx b/Utilities/ITK/Code/Numerics/Statistics/itkSubsample.txx index 072dc49d2b..5e503499c8 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSubsample.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSubsample.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSubsample.txx,v $ Language: C++ - Date: $Date: 2003-12-15 01:00:46 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,16 +19,16 @@ #include "itkObject.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > Subsample< TSample > ::Subsample() { - m_Sample = 0 ; - m_TotalFrequency = NumericTraits< FrequencyType >::Zero ; - m_ActiveDimension = 0 ; + m_Sample = 0; + m_TotalFrequency = NumericTraits< FrequencyType >::Zero; + m_ActiveDimension = 0; } template< class TSample > @@ -38,19 +38,19 @@ Subsample< TSample > { Superclass::PrintSelf(os,indent); - os << indent << "Sample: " ; + os << indent << "Sample: "; if ( m_Sample != 0 ) { - os << m_Sample << std::endl ; + os << m_Sample << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "TotalFrequency: " << m_TotalFrequency << std::endl ; - os << indent << "ActiveDimension: " << m_ActiveDimension << std::endl ; - os << indent << "InstanceIdentifierHolder : " << &m_IdHolder << std::endl ; + os << indent << "TotalFrequency: " << m_TotalFrequency << std::endl; + os << indent << "ActiveDimension: " << m_ActiveDimension << std::endl; + os << indent << "InstanceIdentifierHolder : " << &m_IdHolder << std::endl; } template< class TSample > @@ -58,7 +58,7 @@ inline typename Subsample< TSample >::MeasurementVectorType Subsample< TSample > ::GetMeasurementVectorByIndex(int index) const { - return m_Sample->GetMeasurementVector(m_IdHolder[index]) ; + return m_Sample->GetMeasurementVector(m_IdHolder[index]); } template< class TSample > @@ -66,7 +66,7 @@ inline typename Subsample< TSample >::FrequencyType Subsample< TSample > ::GetFrequencyByIndex(int index) const { - return m_Sample->GetFrequency(m_IdHolder[index]) ; + return m_Sample->GetFrequency(m_IdHolder[index]); } template< class TSample > @@ -74,7 +74,7 @@ inline typename Subsample< TSample >::InstanceIdentifier Subsample< TSample > ::GetInstanceIdentifier(int index) const { - return m_IdHolder[index] ; + return m_IdHolder[index]; } template< class TSample > @@ -82,19 +82,12 @@ inline void Subsample< TSample > ::Swap(int index1, int index2) { - InstanceIdentifier temp = m_IdHolder[index1] ; - m_IdHolder[index1] = m_IdHolder[index2] ; - m_IdHolder[index2] = temp ; + InstanceIdentifier temp = m_IdHolder[index1]; + m_IdHolder[index1] = m_IdHolder[index2]; + m_IdHolder[index2] = temp; } } // end of namespace Statistics } // end of namespace itk #endif - - - - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkTDistribution.cxx b/Utilities/ITK/Code/Numerics/Statistics/itkTDistribution.cxx index 1d2dd40892..1168d4750c 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkTDistribution.cxx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkTDistribution.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTDistribution.cxx,v $ Language: C++ - Date: $Date: 2007-02-24 13:47:32 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-06 11:15:09 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -71,14 +71,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 1; @@ -94,7 +94,7 @@ TDistribution double pdf; pdf = (dgamma_(&dofplusoneon2) / dgamma_(&dofon2)) - / (sqrt(dof*vnl_math::pi) * pow(1.0 + ((x*x)/dof), dofplusoneon2)); + / (vcl_sqrt(dof*vnl_math::pi) * vcl_pow(1.0 + ((x*x)/dof), dofplusoneon2)); return pdf; } @@ -109,14 +109,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << "TDistribution: " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; @@ -180,14 +180,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << "TDistribution: " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; @@ -218,10 +218,10 @@ TDistribution dof4 = dof*dof3; gaussX = GaussianDistribution::InverseCDF(p); - gaussX3 = pow(gaussX, 3.0); - gaussX5 = pow(gaussX, 5.0); - gaussX7 = pow(gaussX, 7.0); - gaussX9 = pow(gaussX, 9.0); + gaussX3 = vcl_pow(gaussX, 3.0); + gaussX5 = vcl_pow(gaussX, 5.0); + gaussX7 = vcl_pow(gaussX, 7.0); + gaussX9 = vcl_pow(gaussX, 9.0); x = gaussX + (gaussX3 + gaussX) / (4.0 * dof) @@ -279,14 +279,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << "TDistribution: " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; @@ -303,14 +303,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -325,14 +325,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -355,14 +355,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -377,14 +377,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -407,14 +407,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -429,14 +429,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return 0.0; } @@ -461,14 +461,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } return false; @@ -500,14 +500,14 @@ TDistribution } else { - InvalidArgumentError exp(__FILE__, __LINE__); + InvalidArgumentError excp(__FILE__, __LINE__); ::itk::OStringStream message; message << "itk::ERROR: " << this->GetNameOfClass() << "(" << this << "): " << "Invalid number of parameters to describe distribution."; - exp.SetDescription(message.str()); - exp.SetLocation(ITK_LOCATION); - throw exp; + excp.SetDescription(message.str()); + excp.SetLocation(ITK_LOCATION); + throw excp; } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkVariableDimensionHistogram.h b/Utilities/ITK/Code/Numerics/Statistics/itkVariableDimensionHistogram.h index 598327852c..f6feccb6f6 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkVariableDimensionHistogram.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkVariableDimensionHistogram.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVariableDimensionHistogram.h,v $ Language: C++ - Date: $Date: 2005-09-30 17:40:35 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 20:26:56 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,8 +26,8 @@ #include "itkDenseFrequencyContainer.h" #include "itkSparseFrequencyContainer.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class VariableDimensionHistogram * \brief This class is similar to the Histogram class. It @@ -62,9 +62,6 @@ namespace Statistics{ * * \sa Histogram, Sample, DenseFrequencyContainer, SparseFrequencyContainer */ - - - template < class TMeasurement = float, class TFrequencyContainer = DenseFrequencyContainer > @@ -74,62 +71,62 @@ class ITK_EXPORT VariableDimensionHistogram public: /** Standard typedefs */ - typedef VariableDimensionHistogram Self ; - typedef Sample< Array< TMeasurement > > Superclass ; - typedef SmartPointer<Self> Pointer ; - typedef SmartPointer<const Self> ConstPointer ; + typedef VariableDimensionHistogram Self; + typedef Sample< Array< TMeasurement > > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(VariableDimensionHistogram, Sample) ; + itkTypeMacro(VariableDimensionHistogram, Sample); /** standard New() method support */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** type of an element of a measurement vector */ - typedef TMeasurement MeasurementType ; + typedef TMeasurement MeasurementType; /** Common sample class typedefs */ - typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; - typedef typename Superclass::InstanceIdentifier InstanceIdentifier ; - typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType ; - typedef MeasurementVectorType ValueType ; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + typedef MeasurementVectorType ValueType; /** frequency container typedef */ - typedef TFrequencyContainer FrequencyContainerType ; - typedef typename FrequencyContainerType::Pointer FrequencyContainerPointer ; + typedef TFrequencyContainer FrequencyContainerType; + typedef typename FrequencyContainerType::Pointer FrequencyContainerPointer; /** Frequency value and TotalFrequency type from superclass */ - typedef typename FrequencyContainerType::FrequencyType FrequencyType ; - typedef typename FrequencyContainerType::TotalFrequencyType TotalFrequencyType ; + typedef typename FrequencyContainerType::FrequencyType FrequencyType; + typedef typename FrequencyContainerType::TotalFrequencyType TotalFrequencyType; /** Index typedef support. An index is used to access pixel values. */ - typedef itk::Array< long > IndexType; + typedef itk::Array< long > IndexType; typedef typename IndexType::ValueType IndexValueType; /** size array type */ - typedef itk::Array< long > SizeType ; - typedef typename SizeType::ValueType SizeValueType ; + typedef itk::Array< long > SizeType; + typedef typename SizeType::ValueType SizeValueType; /** bin min max value storage types */ - typedef std::vector< MeasurementType > BinMinVectorType ; - typedef std::vector< MeasurementType > BinMaxVectorType ; - typedef std::vector< BinMinVectorType > BinMinContainerType ; - typedef std::vector< BinMaxVectorType > BinMaxContainerType ; + typedef std::vector< MeasurementType > BinMinVectorType; + typedef std::vector< MeasurementType > BinMaxVectorType; + typedef std::vector< BinMinVectorType > BinMinContainerType; + typedef std::vector< BinMaxVectorType > BinMaxContainerType; /** Initialize the histogram, generating the offset table and * preparing the frequency container. Subclasses should call this * method in their Initialize() method. */ - void Initialize(const SizeType &size) ; + void Initialize(const SizeType &size); /** Initialize the histogram using equal size bins. To assign bin's * min and max values along each dimension use SetBinMin() and * SetBinMax() functions. */ void Initialize(const SizeType &size, MeasurementVectorType& lowerBound, - MeasurementVectorType& upperBound) ; + MeasurementVectorType& upperBound); /** Initialize the values of the histogram bins to zero */ - void SetToZero() ; + void SetToZero(); /** Get the index of histogram corresponding to the specified * measurement value. Returns true if index is valid and false if @@ -140,7 +137,7 @@ public: /** Get the index that is uniquely labelled by an instance identifier * The corresponding id is the offset of the index * This method uses ImageBase::ComputeIndex() method */ - const IndexType & GetIndex(const InstanceIdentifier &id) const; + const IndexType & GetIndex(const InstanceIdentifier &ident) const; /** Is set to false if the bins at edges of the histogram extend to * +/- infinity. */ @@ -157,130 +154,129 @@ public: /** Get the instance identifier of the bin that is indexed by the * index. The corresponding instance identifier is the offset of the index * This method uses ImageBase::ComputeIndex() method */ - InstanceIdentifier GetInstanceIdentifier(const IndexType &index) const ; + InstanceIdentifier GetInstanceIdentifier(const IndexType &index) const; /** Returns the number of instances (bins or cells) in this container */ - unsigned int Size() const ; + unsigned int Size() const; /** Get the size (N-dimensional) of the histogram */ SizeType GetSize() const - { return m_Size ; } + { return m_Size; } /** Get the size of histogram along a specified dimension */ SizeValueType GetSize(const unsigned int dimension) const - { - return m_Size[dimension] ; - } + { + return m_Size[dimension]; + } /** Get the minimum value of nth bin of dimension d */ const MeasurementType& GetBinMin(const unsigned int dimension, const unsigned long nbin) const - { return m_Min[dimension][nbin] ; } + { return m_Min[dimension][nbin]; } /** Get the maximum value of nth bin of dimension d */ const MeasurementType& GetBinMax(const unsigned int dimension, const unsigned long nbin) const - { return m_Max[dimension][nbin] ; } + { return m_Max[dimension][nbin]; } /** Set the minimum value of nth bin of dimension d */ void SetBinMin(const unsigned int dimension, const unsigned long nbin, const MeasurementType min) - { m_Min[dimension][nbin] = min ; } + { m_Min[dimension][nbin] = min; } /** Set the maximum value of nth bin of dimension d */ void SetBinMax(const unsigned int dimension, unsigned long nbin, const MeasurementType max) - { m_Max[dimension][nbin] = max ; } + { m_Max[dimension][nbin] = max; } /** Get the minimum of the bin along dimension d corresponding to a * particular measurement. */ const MeasurementType& GetBinMinFromValue(const unsigned int dimension, - const float value ) const ; + const float value ) const; /** Get the maximum of the bin along dimension d corresponding to a * particular measurement. */ const MeasurementType& GetBinMaxFromValue(const unsigned int dimension, - const float value ) const ; + const float value ) const; /** Get the vector of bin minimums along a dimension */ const BinMinVectorType& GetDimensionMins(const unsigned int dimension) const - { return m_Min[dimension] ; } + { return m_Min[dimension]; } /** Get the vector of maximums along a dimension */ const BinMaxVectorType& GetDimensionMaxs(const unsigned int dimension) const - { return m_Max[dimension] ; } + { return m_Max[dimension]; } /** Get the minimums of the bins */ const BinMinContainerType& GetMins() const - { return m_Min ; } - + { return m_Min; } /** Method the maximums of the bins */ const BinMaxContainerType& GetMaxs() const - { return m_Max ; } + { return m_Max; } /** Get the minimums of the bin corresponding to a particular measurement */ MeasurementVectorType& GetHistogramMinFromValue(const MeasurementVectorType - &measurement) ; + &measurement); /** Get the maximums of the bin corresponding to a particular measurement */ MeasurementVectorType& GetHistogramMaxFromValue(const MeasurementVectorType - &measurement) ; + &measurement); /** Get the minimums of the bin corresponding to a particular index */ - MeasurementVectorType& GetHistogramMinFromIndex(const IndexType &index) ; + MeasurementVectorType& GetHistogramMinFromIndex(const IndexType &index); /** Get the maximums of the bin corresponding to a particular index */ - MeasurementVectorType& GetHistogramMaxFromIndex(const IndexType &index) ; + MeasurementVectorType& GetHistogramMaxFromIndex(const IndexType &index); /** Get the frequency of an instance indentifier */ - FrequencyType GetFrequency(const InstanceIdentifier &id) const - { return m_FrequencyContainer->GetFrequency(id) ; } + FrequencyType GetFrequency(const InstanceIdentifier &ident) const + { return m_FrequencyContainer->GetFrequency(ident); } /** Get the frequency of an index */ - FrequencyType GetFrequency(const IndexType &index) const ; + FrequencyType GetFrequency(const IndexType &index) const; /** Set all the bins in the histogram to a specified frequency */ - void SetFrequency(const FrequencyType value) ; + void SetFrequency(const FrequencyType value); /** Set the frequency of an instance identifier. Returns false if the bin is * out of bounds. */ - bool SetFrequency(const InstanceIdentifier &id, const FrequencyType value) - { return m_FrequencyContainer->SetFrequency(id, value) ; } + bool SetFrequency(const InstanceIdentifier &ident, const FrequencyType value) + { return m_FrequencyContainer->SetFrequency(ident, value); } /** Set the frequency of an index. Returns false if the bin is * out of bounds. */ bool SetFrequency(const IndexType &index, - const FrequencyType value) ; + const FrequencyType value); /** Set the frequency of a measurement. Returns false if the bin is * out of bounds. */ bool SetFrequency(const MeasurementVectorType &measurement, - const FrequencyType value) ; + const FrequencyType value); /** Increase the frequency of an instance identifier. * Frequency is increased by the specified value. Returns false if * the bin is out of bounds. */ - bool IncreaseFrequency(const InstanceIdentifier &id, + bool IncreaseFrequency(const InstanceIdentifier &ident, const FrequencyType value) - { return m_FrequencyContainer->IncreaseFrequency(id, value) ; } + { return m_FrequencyContainer->IncreaseFrequency(ident, value); } /** Increase the frequency of an index. Frequency is * increased by the specified value. Returns false if the bin is out * of bounds. */ bool IncreaseFrequency(const IndexType &index, - const FrequencyType value) ; + const FrequencyType value); /** Increase the frequency of a measurement. Frequency is * increased by the specified value. Returns false if the * measurement is outside the bounds of the histogram. */ bool IncreaseFrequency(const MeasurementVectorType &measurement, - const FrequencyType value) ; + const FrequencyType value); /** Get the measurement of an instance identifier. This is the * centroid of the bin. */ - const MeasurementVectorType & GetMeasurementVector(const InstanceIdentifier &id) const; + const MeasurementVectorType & GetMeasurementVector(const InstanceIdentifier &ident) const; /** Get the measurement of an index. This is the centroid of the bin. */ const MeasurementVectorType & GetMeasurementVector(const IndexType &index) const; @@ -288,14 +284,14 @@ public: /** Get the measurement a bin along a specified dimension. This is * the midpoint of the bin along that dimension. */ MeasurementType GetMeasurement(const unsigned long n, - const unsigned int dimension) const ; + const unsigned int dimension) const; - /** Get the total frequency in the histogram*/ - TotalFrequencyType GetTotalFrequency() const ; + /** Get the total frequency in the histogram */ + TotalFrequencyType GetTotalFrequency() const; /** Get the frequency of a dimension's nth element. */ FrequencyType GetFrequency(const unsigned long n, - const unsigned int dimension) const ; + const unsigned int dimension) const; /** Get the pth percentile value for a dimension. * @@ -303,7 +299,7 @@ public: * min = min value of the dimension of the bin, * max = max value of the dimension of the bin, * interval = max - min , - * pp = cumlated proportion until n-1 bin ; + * pp = cumlated proportion until n-1 bin; * and pb = frequency of the bin / total frequency of the dimension. * * If p is less than 0.5, @@ -314,170 +310,167 @@ public: * max - ((pp - p) / pb) * interval */ double Quantile(const unsigned int dimension, const double &p) const; - protected: +protected: void PrintSelf(std::ostream& os, Indent indent) const; public: /** iterator support */ class Iterator - { - public: + { + public: Iterator(){}; Iterator(Self * histogram) - { - m_Id = 0 ; + { + m_Id = 0; m_Histogram = histogram; - } + } - Iterator(InstanceIdentifier id, Self * histogram) - : m_Id(id), m_Histogram(histogram) - {} + Iterator(InstanceIdentifier ident, Self * histogram) + : m_Id(ident), m_Histogram(histogram) {} FrequencyType GetFrequency() const - { - return m_Histogram->GetFrequency(m_Id) ; - } + { + return m_Histogram->GetFrequency(m_Id); + } bool SetFrequency(const FrequencyType value) - { + { return m_Histogram->SetFrequency(m_Id, value); - } + } InstanceIdentifier GetInstanceIdentifier() const - { return m_Id ; } + { return m_Id; } const MeasurementVectorType & GetMeasurementVector() const - { - return m_Histogram->GetMeasurementVector(m_Id) ; - } + { + return m_Histogram->GetMeasurementVector(m_Id); + } Iterator& operator++() - { + { ++m_Id; return *this; - } + } bool operator!=(const Iterator& it) - { return (m_Id != it.m_Id); } + { return (m_Id != it.m_Id); } bool operator==(const Iterator& it) - { return (m_Id == it.m_Id); } + { return (m_Id == it.m_Id); } Iterator& operator=(const Iterator& it) - { + { m_Id = it.m_Id; - m_Histogram = it.m_Histogram ; - return *this ; - } + m_Histogram = it.m_Histogram; + return *this; + } Iterator(const Iterator& it) - { + { m_Id = it.m_Id; - m_Histogram = it.m_Histogram ; - } + m_Histogram = it.m_Histogram; + } - private: - // Iterator pointing DenseFrequencyContainer - InstanceIdentifier m_Id; - - // Pointer of DenseFrequencyContainer - Self* m_Histogram ; - } ; // end of iterator class + private: + // Iterator pointing DenseFrequencyContainer + InstanceIdentifier m_Id; + + // Pointer of DenseFrequencyContainer + Self* m_Histogram; + }; // end of iterator class // Const Iterator class ConstIterator - { - public: + { + public: ConstIterator(){}; ConstIterator(const Self * histogram) - { - m_Id = 0 ; + { + m_Id = 0; m_Histogram = histogram; - } + } - ConstIterator(InstanceIdentifier id, const Self * histogram) - : m_Id(id), m_Histogram(histogram) - {} + ConstIterator(InstanceIdentifier ident, const Self * histogram) + : m_Id(ident), m_Histogram(histogram) {} FrequencyType GetFrequency() const - { - return m_Histogram->GetFrequency(m_Id) ; - } + { + return m_Histogram->GetFrequency(m_Id); + } bool SetFrequency(const FrequencyType value) - { + { return m_Histogram->SetFrequency(m_Id, value); - } + } InstanceIdentifier GetInstanceIdentifier() const - { return m_Id ; } + { return m_Id; } const MeasurementVectorType & GetMeasurementVector() const - { - return m_Histogram->GetMeasurementVector(m_Id) ; - } + { + return m_Histogram->GetMeasurementVector(m_Id); + } ConstIterator& operator++() - { + { ++m_Id; return *this; - } + } bool operator!=(const ConstIterator& it) - { return (m_Id != it.m_Id); } + { return (m_Id != it.m_Id); } bool operator==(const ConstIterator& it) - { return (m_Id == it.m_Id); } + { return (m_Id == it.m_Id); } ConstIterator& operator=(const ConstIterator& it) - { + { m_Id = it.m_Id; - m_Histogram = it.m_Histogram ; - return *this ; - } + m_Histogram = it.m_Histogram; + return *this; + } ConstIterator(const ConstIterator & it) - { + { m_Id = it.m_Id; - m_Histogram = it.m_Histogram ; - } + m_Histogram = it.m_Histogram; + } - private: + private: // ConstIterator pointing DenseFrequencyContainer InstanceIdentifier m_Id; // Pointer of DenseFrequencyContainer - const Self* m_Histogram ; - } ; // end of iterator class + const Self* m_Histogram; + }; // end of iterator class Iterator Begin() - { - Iterator iter(0, this) ; - return iter ; - } + { + Iterator iter(0, this); + return iter; + } - Iterator End() - { - return Iterator(m_OffsetTable[this->GetMeasurementVectorSize()], this) ; - } + Iterator End() + { + return Iterator(m_OffsetTable[this->GetMeasurementVectorSize()], this); + } ConstIterator Begin() const - { - ConstIterator iter(0, this) ; - return iter ; - } + { + ConstIterator iter(0, this); + return iter; + } ConstIterator End() const - { - return ConstIterator(m_OffsetTable[this->GetMeasurementVectorSize()], this) ; - } - + { + return ConstIterator(m_OffsetTable[this->GetMeasurementVectorSize()], this); + } protected: - VariableDimensionHistogram() ; + VariableDimensionHistogram(); virtual ~VariableDimensionHistogram() {} /** Set the length of each measurement vector = dimension of the histogram. @@ -486,28 +479,28 @@ protected: void SetMeasurementVectorSize( const MeasurementVectorSizeType ); // The number of bins for each dimension - SizeType m_Size ; + SizeType m_Size; private: VariableDimensionHistogram(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented Array< InstanceIdentifier > m_OffsetTable; - FrequencyContainerPointer m_FrequencyContainer ; - unsigned int m_NumberOfInstances ; + FrequencyContainerPointer m_FrequencyContainer; + unsigned int m_NumberOfInstances; // lower bound of each bin - std::vector< std::vector<MeasurementType> > m_Min ; + std::vector< std::vector<MeasurementType> > m_Min; // upper bound of each bin - std::vector< std::vector<MeasurementType> > m_Max ; + std::vector< std::vector<MeasurementType> > m_Max; - mutable MeasurementVectorType m_TempMeasurementVector ; - mutable IndexType m_TempIndex ; + mutable MeasurementVectorType m_TempMeasurementVector; + mutable IndexType m_TempIndex; bool m_ClipBinsAtEnds; -} ; // end of class +}; // end of class } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkVariableDimensionHistogram.txx b/Utilities/ITK/Code/Numerics/Statistics/itkVariableDimensionHistogram.txx index 884ded6e94..96f9601213 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkVariableDimensionHistogram.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkVariableDimensionHistogram.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVariableDimensionHistogram.txx,v $ Language: C++ - Date: $Date: 2008-01-16 19:31:11 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-04 20:26:56 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,14 +14,14 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#ifndef _itkHistogram_txx -#define _itkHistogram_txx +#ifndef __itkVariableDimensionHistogram_txx +#define __itkVariableDimensionHistogram_txx #include "itkVariableDimensionHistogram.h" #include "itkNumericTraits.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TMeasurement, class TFrequencyContainer> @@ -29,7 +29,7 @@ VariableDimensionHistogram<TMeasurement, TFrequencyContainer> ::VariableDimensionHistogram() { m_ClipBinsAtEnds = true; - m_FrequencyContainer = FrequencyContainerType::New() ; + m_FrequencyContainer = FrequencyContainerType::New(); } template< class TMeasurement, @@ -42,9 +42,9 @@ void VariableDimensionHistogram<TMeasurement, TFrequencyContainer> return; } - if( (m_OffsetTable.Size() != 0) || - (m_Size.Size() != 0) || - (m_TempIndex.Size() != 0) || + if( (m_OffsetTable.Size() != 0) || + (m_Size.Size() != 0) || + (m_TempIndex.Size() != 0) || (m_TempMeasurementVector.Size() != 0)) { itkWarningMacro( << "Destructively resizing paramters of the histogram" ); @@ -70,12 +70,12 @@ VariableDimensionHistogram<TMeasurement, TFrequencyContainer> return 0; } - unsigned int size = 1 ; - for (unsigned int i = 0 ; i < this->GetMeasurementVectorSize() ; i++) + unsigned int size = 1; + for (unsigned int i = 0; i < this->GetMeasurementVectorSize(); i++) { - size *= m_Size[i] ; + size *= m_Size[i]; } - return size ; + return size; } template< class TMeasurement, @@ -92,20 +92,20 @@ VariableDimensionHistogram<TMeasurement, TFrequencyContainer> this->SetMeasurementVectorSize( size.Size() ); } - m_Size = size ; + m_Size = size; // creates offset table which will be used for generation of // instance identifiers. - InstanceIdentifier num = 1 ; + InstanceIdentifier num = 1; - m_OffsetTable[0] = num ; - for (unsigned int i = 0 ; i < this->GetMeasurementVectorSize() ; i++) + m_OffsetTable[0] = num; + for (unsigned int i = 0; i < this->GetMeasurementVectorSize(); i++) { - num *= m_Size[i] ; + num *= m_Size[i]; m_OffsetTable[i + 1] = num; } - m_NumberOfInstances = num ; + m_NumberOfInstances = num; // adjust the sizes of min max value containers unsigned int dim; @@ -122,7 +122,7 @@ VariableDimensionHistogram<TMeasurement, TFrequencyContainer> } // initialize the frequency container - m_FrequencyContainer->Initialize(m_OffsetTable[ this->GetMeasurementVectorSize() ]) ; + m_FrequencyContainer->Initialize(m_OffsetTable[ this->GetMeasurementVectorSize() ]); this->SetToZero(); } @@ -142,7 +142,7 @@ VariableDimensionHistogram<TMeasurement, TFrequencyContainer> ::Initialize(const SizeType &size, MeasurementVectorType& lowerBound, MeasurementVectorType& upperBound) { - this->Initialize(size) ; + this->Initialize(size); // Sanity check to see if size, lowerBound and upperBound are of the // same length. @@ -154,24 +154,24 @@ VariableDimensionHistogram<TMeasurement, TFrequencyContainer> "Length mismatch: VariableDimensionHistogram::Initialize( , )"); float interval; - for ( unsigned int i = 0 ; i < measurementVectorSize; i++) + for ( unsigned int i = 0; i < measurementVectorSize; i++) { interval = (float) (upperBound[i] - lowerBound[i]) - / static_cast< MeasurementType >(size[i]) ; + / static_cast< MeasurementType >(size[i]); // Set the min vector and max vector - for (unsigned int j = 0; j < static_cast< unsigned int >(size[i] - 1) ; j++) + for (unsigned int j = 0; j < static_cast< unsigned int >(size[i] - 1); j++) { this->SetBinMin(i, j, (MeasurementType)(lowerBound[i] + - ((float)j * interval))) ; + ((float)j * interval))); this->SetBinMax(i, j, (MeasurementType)(lowerBound[i] + (((float)j + 1) * interval))); } this->SetBinMin(i, size[i] - 1, (MeasurementType)(lowerBound[i] + - (((float) size[i] - 1) * interval))) ; + (((float) size[i] - 1) * interval))); this->SetBinMax(i, size[i] - 1, - (MeasurementType)(upperBound[i])) ; + (MeasurementType)(upperBound[i])); } } @@ -193,79 +193,77 @@ bool VariableDimensionHistogram<TMeasurement, TFrequencyContainer> // now using something similar to binary search to find // index. - unsigned int dim ; + unsigned int dim; - int begin, mid, end ; - MeasurementType median ; - MeasurementType tempMeasurement ; + int begin, mid, end; + MeasurementType median; + MeasurementType tempMeasurement; - for (dim = 0 ; dim < measurementVectorSize ; dim++) + for (dim = 0; dim < measurementVectorSize; dim++) { - tempMeasurement = measurement[dim] ; - begin = 0 ; + tempMeasurement = measurement[dim]; + begin = 0; if (tempMeasurement < m_Min[dim][begin]) { // one of measurement is below the minimum - index[dim] = (long) m_Size[dim] ; + index[dim] = (long) m_Size[dim]; return false; } - end = m_Min[dim].size() - 1 ; + end = m_Min[dim].size() - 1; if (tempMeasurement >= m_Max[dim][end]) { // one of measurement is above the maximum - index[dim] = (long) m_Size[dim] ; + index[dim] = (long) m_Size[dim]; return false; } - mid = (end + 1) / 2 ; + mid = (end + 1) / 2; median = m_Min[dim][mid]; while(true) { if (tempMeasurement < median ) { - end = mid - 1 ; + end = mid - 1; } else if (tempMeasurement > median) { if (tempMeasurement < m_Max[dim][mid]) { - index[dim] = mid ; - break ; + index[dim] = mid; + break; } - begin = mid + 1 ; + begin = mid + 1; } else { // measurement[dim] = m_Min[dim][med] - index[dim] = mid ; - break ; + index[dim] = mid; + break; } - mid = begin + (end - begin) / 2 ; - median = m_Min[dim][mid] ; + mid = begin + (end - begin) / 2; + median = m_Min[dim][mid]; } // end of while } // end of for() return true; } - - template< class TMeasurement, class TFrequencyContainer> inline const typename VariableDimensionHistogram<TMeasurement, TFrequencyContainer>::IndexType& VariableDimensionHistogram<TMeasurement, TFrequencyContainer> -::GetIndex(const InstanceIdentifier &id) const +::GetIndex(const InstanceIdentifier &ident) const { - InstanceIdentifier id2 = id ; + InstanceIdentifier ident2 = ident; - for (int i = this->GetMeasurementVectorSize() - 1 ; i > 0 ; i--) + for (int i = this->GetMeasurementVectorSize() - 1; i > 0; i--) { - m_TempIndex[i] = static_cast<IndexValueType>(id2 / m_OffsetTable[i]); - id2 -= (m_TempIndex[i] * m_OffsetTable[i]); + m_TempIndex[i] = static_cast<IndexValueType>(ident2 / m_OffsetTable[i]); + ident2 -= (m_TempIndex[i] * m_OffsetTable[i]); } - m_TempIndex[0] = static_cast<IndexValueType>(id2); + m_TempIndex[0] = static_cast<IndexValueType>(ident2); return m_TempIndex; } @@ -281,14 +279,14 @@ VariableDimensionHistogram<TMeasurement, TFrequencyContainer> MeasurementVectorTraits::Assert( index, this->GetMeasurementVectorSize(), "Length mismatch: VariableDimensionHistogram::GetIndex(MeasurementVectorType, IndexType)"); - for (unsigned int dim = 0 ; dim < this->GetMeasurementVectorSize() ; dim++) + for (unsigned int dim = 0; dim < this->GetMeasurementVectorSize(); dim++) { if (index[dim] < 0 || index[dim] >= static_cast<IndexValueType>(m_Size[dim])) { - return true ; + return true; } } - return false ; + return false; } template< class TMeasurement, @@ -302,15 +300,15 @@ VariableDimensionHistogram<TMeasurement, TFrequencyContainer> MeasurementVectorTraits::Assert( index, this->GetMeasurementVectorSize(), "Length mismatch: VariableDimensionHistogram::GetIndex(MeasurementVectorType, IndexType)"); - InstanceIdentifier id = 0 ; - for (int i= this->GetMeasurementVectorSize() - 1 ; i > 0 ; i-- ) + InstanceIdentifier ident = 0; + for (int i= this->GetMeasurementVectorSize() - 1; i > 0; i-- ) { - id += index[i] * m_OffsetTable[i]; + ident += index[i] * m_OffsetTable[i]; } - id += index[0] ; + ident += index[0]; - return id ; + return ident; } @@ -366,7 +364,7 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > return m_Max[dimension][this->m_Size[dimension]-1]; } - for ( int i = 0 ; i < this->m_Size[dimension]; i++ ) + for ( int i = 0; i < this->m_Size[dimension]; i++ ) { if ( (value >= this->m_Min[dimension][i]) && (value < this->m_Max[dimension][i]) ) @@ -393,7 +391,7 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > { m_TempMeasurementVector[i] = this->GetDimensionMinByValue(i,measurement[i]); } - return m_TempMeasurementVector ; + return m_TempMeasurementVector; } template< class TMeasurement, @@ -413,7 +411,7 @@ VariableDimensionHistogram<TMeasurement, TFrequencyContainer> { m_TempMeasurementVector[i] = this->GetDimensionMaxByValue(i,measurement[i]); } - return m_TempMeasurementVector ; + return m_TempMeasurementVector; } @@ -430,9 +428,9 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > for ( int i=0; i < this->GetMeasurementVectorSize(); i++ ) { - m_TempMeasurementVector[i] = this->GetBinMin(i, index[i]) ; + m_TempMeasurementVector[i] = this->GetBinMin(i, index[i]); } - return m_TempMeasurementVector ; + return m_TempMeasurementVector; } template< class TMeasurement, @@ -448,9 +446,9 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > for ( int i=0; i < this->GetMeasurementVectorSize(); i++ ) { - m_TempMeasurementVector[i] = this->GetBinMax(i, index[i]) ; + m_TempMeasurementVector[i] = this->GetBinMax(i, index[i]); } - return m_TempMeasurementVector ; + return m_TempMeasurementVector; } template< class TMeasurement, @@ -469,7 +467,7 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > MeasurementType value = (m_Min[i][index[i]] + m_Max[i][index[i]]); m_TempMeasurementVector[i] = static_cast< MeasurementType >( value / 2.0 ); } - return m_TempMeasurementVector ; + return m_TempMeasurementVector; } template< class TMeasurement, @@ -477,9 +475,9 @@ template< class TMeasurement, inline const typename VariableDimensionHistogram< TMeasurement, TFrequencyContainer >::MeasurementVectorType & VariableDimensionHistogram< TMeasurement, TFrequencyContainer > -::GetMeasurementVector(const InstanceIdentifier &id) const +::GetMeasurementVector(const InstanceIdentifier &ident) const { - return this->GetMeasurementVector( this->GetIndex(id) ) ; + return this->GetMeasurementVector( this->GetIndex(ident) ); } template< class TMeasurement, @@ -488,13 +486,13 @@ inline void VariableDimensionHistogram< TMeasurement, TFrequencyContainer > ::SetFrequency(const FrequencyType value) { - typename Self::Iterator iter = this->Begin() ; - typename Self::Iterator end = this->End() ; + typename Self::Iterator iter = this->Begin(); + typename Self::Iterator end = this->End(); while ( iter != end ) { - iter.SetFrequency(value) ; - ++iter ; + iter.SetFrequency(value); + ++iter; } } @@ -508,7 +506,7 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > MeasurementVectorTraits::Assert( index, this->GetMeasurementVectorSize(), "Length mismatch: VariableDimensionHistogram::GetIndex(MeasurementVectorType, IndexType)"); - return this->SetFrequency( this->GetInstanceIdentifier(index), value) ; + return this->SetFrequency( this->GetInstanceIdentifier(index), value); } template< class TMeasurement, @@ -523,7 +521,7 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > MeasurementVectorTraits::Assert( measurement, this->GetMeasurementVectorSize(), "Length mismatch: VariableDimensionHistogram::SetFrequency"); - return this->SetFrequency( this->GetInstanceIdentifier(GetIndex(measurement)), value) ; + return this->SetFrequency( this->GetInstanceIdentifier(GetIndex(measurement)), value); } template< class TMeasurement, @@ -537,7 +535,7 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > "Length mismatch: VariableDimensionHistogram::GetIndex(MeasurementVectorType, IndexType)"); const bool result = - this->IncreaseFrequency( this->GetInstanceIdentifier(index), value) ; + this->IncreaseFrequency( this->GetInstanceIdentifier(index), value); return result; } @@ -558,8 +556,6 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > return this->IncreaseFrequency( this->GetInstanceIdentifier( index ), value ); } - - template< class TMeasurement, class TFrequencyContainer > inline typename VariableDimensionHistogram< TMeasurement, @@ -570,7 +566,7 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > MeasurementVectorTraits::Assert( index, this->GetMeasurementVectorSize(), "Length mismatch: VariableDimensionHistogram::GetFrequency"); - return ( this->GetFrequency( this->GetInstanceIdentifier(index)) ) ; + return ( this->GetFrequency( this->GetInstanceIdentifier(index)) ); } template< class TMeasurement, @@ -581,7 +577,7 @@ VariableDimensionHistogram< TMeasurement, TFrequencyContainer > ::GetMeasurement(const unsigned long n, const unsigned int dimension) const { return static_cast< MeasurementType >((m_Min[dimension][n] + - m_Max[dimension][n]) / 2) ; + m_Max[dimension][n]) / 2); } template< class TMeasurement, @@ -591,26 +587,26 @@ inline typename VariableDimensionHistogram< TMeasurement, VariableDimensionHistogram< TMeasurement, TFrequencyContainer > ::GetFrequency(const unsigned long n, const unsigned int dimension) const { - InstanceIdentifier nextOffset = m_OffsetTable[dimension + 1] ; - InstanceIdentifier current = m_OffsetTable[dimension] * n ; - InstanceIdentifier includeLength = m_OffsetTable[dimension] ; - InstanceIdentifier include ; - InstanceIdentifier includeEnd ; - InstanceIdentifier last = m_OffsetTable[this->GetMeasurementVectorSize()] ; - - FrequencyType frequency = 0 ; + InstanceIdentifier nextOffset = m_OffsetTable[dimension + 1]; + InstanceIdentifier current = m_OffsetTable[dimension] * n; + InstanceIdentifier includeLength = m_OffsetTable[dimension]; + InstanceIdentifier include; + InstanceIdentifier includeEnd; + InstanceIdentifier last = m_OffsetTable[this->GetMeasurementVectorSize()]; + + FrequencyType frequency = 0; while (current < last) { - include = current ; - includeEnd = include + includeLength ; + include = current; + includeEnd = include + includeLength; while(include < includeEnd) { - frequency += GetFrequency(include) ; - include++ ; + frequency += GetFrequency(include); + include++; } - current += nextOffset ; + current += nextOffset; } - return frequency ; + return frequency; } template< class TMeasurement, @@ -620,7 +616,7 @@ inline typename VariableDimensionHistogram< TMeasurement, VariableDimensionHistogram< TMeasurement, TFrequencyContainer > ::GetTotalFrequency() const { - return m_FrequencyContainer->GetTotalFrequency() ; + return m_FrequencyContainer->GetTotalFrequency(); } template< class TMeasurement, @@ -629,58 +625,58 @@ double VariableDimensionHistogram< TMeasurement, TFrequencyContainer > ::Quantile(const unsigned int dimension, const double &p) const { - InstanceIdentifier n ; - const unsigned int size = this->GetSize(dimension) ; - double p_n_prev ; - double p_n ; - double f_n ; - double cumulated = 0 ; - double totalFrequency = double( this->GetTotalFrequency() ) ; - double binProportion ; - double min, max, interval ; + InstanceIdentifier n; + const unsigned int size = this->GetSize(dimension); + double p_n_prev; + double p_n; + double f_n; + double cumulated = 0; + double totalFrequency = double( this->GetTotalFrequency() ); + double binProportion; + double min, max, interval; if ( p < 0.5 ) { - n = 0 ; - p_n = NumericTraits< double >::Zero ; + n = 0; + p_n = NumericTraits< double >::Zero; do { - f_n = this->GetFrequency(n, dimension) ; - cumulated += f_n ; - p_n_prev = p_n ; - p_n = cumulated / totalFrequency ; - n++ ; + f_n = this->GetFrequency(n, dimension); + cumulated += f_n; + p_n_prev = p_n; + p_n = cumulated / totalFrequency; + n++; } - while( n < size && p_n < p) ; + while( n < size && p_n < p); - binProportion = f_n / totalFrequency ; + binProportion = f_n / totalFrequency; - min = double( this->GetBinMin(dimension, n - 1) ) ; - max = double( this->GetBinMax(dimension, n - 1) ) ; - interval = max - min ; - return min + ((p - p_n_prev) / binProportion) * interval ; + min = double( this->GetBinMin(dimension, n - 1) ); + max = double( this->GetBinMax(dimension, n - 1) ); + interval = max - min; + return min + ((p - p_n_prev) / binProportion) * interval; } else { - n = size - 1 ; + n = size - 1; InstanceIdentifier m = NumericTraits< InstanceIdentifier >::Zero; - p_n = NumericTraits< double >::One ; + p_n = NumericTraits< double >::One; do { - f_n = this->GetFrequency(n, dimension) ; - cumulated += f_n ; - p_n_prev = p_n ; - p_n = NumericTraits< double >::One - cumulated / totalFrequency ; + f_n = this->GetFrequency(n, dimension); + cumulated += f_n; + p_n_prev = p_n; + p_n = NumericTraits< double >::One - cumulated / totalFrequency; n--; m++; } while( m < size && p_n > p); - binProportion = f_n / totalFrequency ; - min = double( this->GetBinMin(dimension, n + 1) ) ; - max = double( this->GetBinMax(dimension, n + 1) ) ; - interval = max - min ; - return max - ((p_n_prev - p) / binProportion) * interval ; + binProportion = f_n / totalFrequency; + min = double( this->GetBinMin(dimension, n + 1) ); + max = double( this->GetBinMax(dimension, n + 1) ); + interval = max - min; + return max - ((p_n_prev - p) / binProportion) * interval; } } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCentroidKdTreeGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCentroidKdTreeGenerator.h index fc1aff45fe..abeba8e889 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCentroidKdTreeGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCentroidKdTreeGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWeightedCentroidKdTreeGenerator.h,v $ Language: C++ - Date: $Date: 2008-04-25 22:36:09 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,8 +25,8 @@ #include "itkKdTreeGenerator.h" #include "itkStatisticsAlgorithm.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class WeightedCentroidKdTreeGenerator * \brief This class generates a KdTree object with centroid information. @@ -68,34 +68,34 @@ class ITK_EXPORT WeightedCentroidKdTreeGenerator : { public: /** Standard class typedefs */ - typedef WeightedCentroidKdTreeGenerator Self ; - typedef KdTreeGenerator< TSample > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef WeightedCentroidKdTreeGenerator Self; + typedef KdTreeGenerator< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods) */ itkTypeMacro(WeightedCentroidKdTreeGenerator, KdTreeGenerator); /** Method for creation through the object factory. */ - itkNewMacro(Self) ; + itkNewMacro(Self); /** typedef alias for the source data container */ - typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; - typedef typename Superclass::MeasurementType MeasurementType ; - typedef typename Superclass::SubsampleType SubsampleType ; - typedef typename Superclass::SubsamplePointer SubsamplePointer ; - typedef typename Superclass::KdTreeType KdTreeType ; - typedef typename Superclass::KdTreeNodeType KdTreeNodeType ; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::SubsampleType SubsampleType; + typedef typename Superclass::SubsamplePointer SubsamplePointer; + typedef typename Superclass::KdTreeType KdTreeType; + typedef typename Superclass::KdTreeNodeType KdTreeNodeType; protected: /** Constructor */ - WeightedCentroidKdTreeGenerator() ; + WeightedCentroidKdTreeGenerator(); /** Destructor */ virtual ~WeightedCentroidKdTreeGenerator() {} - void PrintSelf(std::ostream& os, Indent indent) const ; + void PrintSelf(std::ostream& os, Indent indent) const; /** Nonterminal node generation routine */ virtual KdTreeNodeType* GenerateNonterminalNode(unsigned int beginIndex, @@ -104,16 +104,16 @@ protected: &lowerBound, MeasurementVectorType &upperBound, - unsigned int level) ; + unsigned int level); private: - WeightedCentroidKdTreeGenerator(const Self&) ; //purposely not implemented - void operator=(const Self&) ; //purposely not implemented + WeightedCentroidKdTreeGenerator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented - MeasurementVectorType m_TempLowerBound ; - MeasurementVectorType m_TempUpperBound ; - MeasurementVectorType m_TempMean ; -} ; // end of class + MeasurementVectorType m_TempLowerBound; + MeasurementVectorType m_TempUpperBound; + MeasurementVectorType m_TempMean; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -123,7 +123,3 @@ private: #endif #endif - - - - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCentroidKdTreeGenerator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCentroidKdTreeGenerator.txx index 708d18dfc6..7a976786f1 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCentroidKdTreeGenerator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCentroidKdTreeGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWeightedCentroidKdTreeGenerator.txx,v $ Language: C++ - Date: $Date: 2008-08-22 23:42:31 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,8 +17,8 @@ #ifndef __itkWeightedCentroidKdTreeGenerator_txx #define __itkWeightedCentroidKdTreeGenerator_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > WeightedCentroidKdTreeGenerator< TSample > diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCovarianceCalculator.h b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCovarianceCalculator.h index fe2d4403d8..cd99df3109 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCovarianceCalculator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCovarianceCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWeightedCovarianceCalculator.h,v $ Language: C++ - Date: $Date: 2008-06-30 15:34:58 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-03-04 19:29:54 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,8 +21,8 @@ #include "itkVariableSizeMatrix.h" #include "itkSampleAlgorithmBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class WeightedCovarianceCalculator * \brief Calculates the covariance matrix of the target sample data @@ -44,10 +44,10 @@ class WeightedCovarianceCalculator : { public: /** Standard class typedefs. */ - typedef WeightedCovarianceCalculator Self; + typedef WeightedCovarianceCalculator Self; typedef SampleAlgorithmBase< TSample > Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Standard Macros */ itkTypeMacro(WeightedCovarianceCalculator, SampleAlgorithmBase); @@ -106,14 +106,14 @@ protected: void ComputeCovarianceWithoutGivenMean( void ); private: - OutputType* m_Output; - MeanType* m_Mean; - MeanType* m_InternalMean; - WeightArrayType* m_Weights; + OutputType* m_Output; + MeanType* m_Mean; + MeanType* m_InternalMean; + WeightArrayType* m_Weights; WeightFunctionType* m_WeightFunction; }; // end of class - } // end of namespace Statistics +} // end of namespace Statistics } // end of namespace itk #ifndef ITK_MANUAL_INSTANTIATION @@ -121,4 +121,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCovarianceCalculator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCovarianceCalculator.txx index 09c0a26251..e7cdb7231d 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCovarianceCalculator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedCovarianceCalculator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWeightedCovarianceCalculator.txx,v $ Language: C++ - Date: $Date: 2008-06-30 15:34:59 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-03-04 19:29:55 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,8 +19,8 @@ #include "itkWeightedCovarianceCalculator.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > WeightedCovarianceCalculator< TSample > @@ -169,8 +169,7 @@ WeightedCovarianceCalculator< TSample > { for ( col = 0; col < row + 1; col++) { - (*m_Output)(row,col) += - weight * diff[row] * diff[col]; + (*m_Output)(row,col) += weight * diff[row] * diff[col]; } } ++iter; @@ -193,8 +192,7 @@ WeightedCovarianceCalculator< TSample > { for ( col = 0; col < row + 1; col++) { - (*m_Output)(row,col) += - weight * diff[row] * diff[col]; + (*m_Output)(row,col) += weight * diff[row] * diff[col]; } } ++measurementVectorIndex; @@ -261,10 +259,10 @@ WeightedCovarianceCalculator< TSample > iter.GetFrequency() * m_WeightFunction->Evaluate(measurements); if ( weight == 0 ) - { + { ++iter; continue; - } + } sumWeight += weight; sumSquaredWeight += weight * weight; @@ -345,13 +343,13 @@ WeightedCovarianceCalculator< TSample > double denom = sumWeight - ( sumSquaredWeight / sumWeight ); if ( denom > 1e-6 || denom < -1e-6 ) - { + { (*m_Output) /= denom; - } + } else - { + { m_Output->Fill( 0.0 ); - } + } } @@ -418,4 +416,3 @@ WeightedCovarianceCalculator< TSample > } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedMeanCalculator.h b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedMeanCalculator.h index d55c5e8564..9176536f0a 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedMeanCalculator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedMeanCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWeightedMeanCalculator.h,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:07 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-03-04 19:29:55 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,8 +25,8 @@ #include "itkFunctionBase.h" #include "itkSampleAlgorithmBase.h" -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { /** \class WeightedMeanCalculator * \brief calculates sample mean where each measurement vector has @@ -52,59 +52,59 @@ class WeightedMeanCalculator : { public: /**Standard class typedefs. */ - typedef WeightedMeanCalculator Self; - typedef SampleAlgorithmBase< TSample > Superclass ; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef WeightedMeanCalculator Self; + typedef SampleAlgorithmBase< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /**Standard Macros */ itkTypeMacro(WeightedMeanCalculator, SampleAlgorithmBase); - itkNewMacro(Self) ; + itkNewMacro(Self); /** Length of a measurement vector */ typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; - typedef typename TSample::MeasurementVectorType MeasurementVectorType ; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; /** Typedef for the mean output */ typedef Array< double > OutputType; /** Array typedef for weights */ - typedef Array< double > WeightArrayType ; + typedef Array< double > WeightArrayType; /** Sets the weights using an array */ - void SetWeights(WeightArrayType* array) ; + void SetWeights(WeightArrayType* array); /** Gets the weights array */ - WeightArrayType* GetWeights() ; + WeightArrayType* GetWeights(); /** Weight calculation function typedef */ - typedef FunctionBase< MeasurementVectorType, double > WeightFunctionType ; + typedef FunctionBase< MeasurementVectorType, double > WeightFunctionType; /** Sets the wiehts using an function * the function should have a method, * Evaluate(MeasurementVectorType&) */ - void SetWeightFunction(WeightFunctionType* func) ; + void SetWeightFunction(WeightFunctionType* func); /** Gets the weight function */ - WeightFunctionType* GetWeightFunction() ; + WeightFunctionType* GetWeightFunction(); /** Returns the mean vector as the result */ - OutputType* GetOutput() ; + OutputType* GetOutput(); protected: - WeightedMeanCalculator() ; + WeightedMeanCalculator(); virtual ~WeightedMeanCalculator() {} void PrintSelf(std::ostream& os, Indent indent) const; /** Calculates the mean and save it */ - void GenerateData() ; + void GenerateData(); private: - WeightArrayType* m_Weights ; - WeightFunctionType* m_WeightFunction ; - OutputType m_Output ; -} ; // end of class + WeightArrayType* m_Weights; + WeightFunctionType* m_WeightFunction; + OutputType m_Output; +}; // end of class } // end of namespace Statistics } // end of namespace itk @@ -114,4 +114,3 @@ private: #endif #endif - diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedMeanCalculator.txx b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedMeanCalculator.txx index d3719322a0..0baa231e9b 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkWeightedMeanCalculator.txx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkWeightedMeanCalculator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWeightedMeanCalculator.txx,v $ Language: C++ - Date: $Date: 2005-07-26 15:55:07 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-03-04 19:29:55 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,16 +17,16 @@ #ifndef __itkWeightedMeanCalculator_txx #define __itkWeightedMeanCalculator_txx -namespace itk{ -namespace Statistics{ +namespace itk { +namespace Statistics { template< class TSample > WeightedMeanCalculator< TSample > ::WeightedMeanCalculator() { - m_WeightFunction = 0 ; - m_Weights = 0 ; - m_Output.Fill(0.0) ; + m_WeightFunction = 0; + m_Weights = 0; + m_Output.Fill(0.0); } template< class TSample > @@ -36,26 +36,26 @@ WeightedMeanCalculator< TSample > { Superclass::PrintSelf(os,indent); - os << indent << "Output: " << m_Output << std::endl ; + os << indent << "Output: " << m_Output << std::endl; - os << indent << "WeightFunction: " ; + os << indent << "WeightFunction: "; if ( m_WeightFunction != 0 ) { - os << m_WeightFunction << std::endl ; + os << m_WeightFunction << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } - os << indent << "Weights: " ; + os << indent << "Weights: "; if ( m_Weights != 0 ) { - os << m_Weights << std::endl ; + os << m_Weights << std::endl; } else { - os << "not set." << std::endl ; + os << "not set." << std::endl; } } @@ -64,7 +64,7 @@ void WeightedMeanCalculator< TSample > ::SetWeights(WeightArrayType* array) { - m_Weights = array ; + m_Weights = array; this->Modified(); } @@ -73,7 +73,7 @@ typename WeightedMeanCalculator< TSample >::WeightArrayType* WeightedMeanCalculator< TSample > ::GetWeights() { - return m_Weights ; + return m_Weights; } template< class TSample > @@ -81,7 +81,7 @@ void WeightedMeanCalculator< TSample > ::SetWeightFunction(WeightFunctionType* func) { - m_WeightFunction = func ; + m_WeightFunction = func; } template< class TSample > @@ -89,7 +89,7 @@ typename WeightedMeanCalculator< TSample >::WeightFunctionType* WeightedMeanCalculator< TSample > ::GetWeightFunction() { - return m_WeightFunction ; + return m_WeightFunction; } @@ -107,46 +107,46 @@ WeightedMeanCalculator< TSample > MeasurementVectorTraits::SetLength( m_Output, measurementVectorSize ); - typename TSample::ConstIterator iter = this->GetInputSample()->Begin() ; - typename TSample::ConstIterator end = this->GetInputSample()->End() ; - double totalWeight = 0.0 ; - double weight ; - unsigned int dim ; - int measurementVectorIndex = 0 ; - typename TSample::MeasurementVectorType measurements ; + typename TSample::ConstIterator iter = this->GetInputSample()->Begin(); + typename TSample::ConstIterator end = this->GetInputSample()->End(); + double totalWeight = 0.0; + double weight; + unsigned int dim; + int measurementVectorIndex = 0; + typename TSample::MeasurementVectorType measurements; if (m_WeightFunction != 0) { while (iter != end) { - measurements = iter.GetMeasurementVector() ; + measurements = iter.GetMeasurementVector(); weight = - iter.GetFrequency() * m_WeightFunction->Evaluate(measurements) ; - totalWeight += weight ; - for (dim = 0 ; dim < measurementVectorSize ; dim++) + iter.GetFrequency() * m_WeightFunction->Evaluate(measurements); + totalWeight += weight; + for (dim = 0; dim < measurementVectorSize; dim++) { - m_Output[dim] += measurements[dim] * weight ; + m_Output[dim] += measurements[dim] * weight; } - ++iter ; + ++iter; } - m_Output /= totalWeight ; + m_Output /= totalWeight; } else { while (iter != end) { - measurements = iter.GetMeasurementVector() ; - weight = iter.GetFrequency() * (*m_Weights)[measurementVectorIndex] ; - totalWeight += weight ; - for (dim = 0 ; dim < measurementVectorSize ; dim++) + measurements = iter.GetMeasurementVector(); + weight = iter.GetFrequency() * (*m_Weights)[measurementVectorIndex]; + totalWeight += weight; + for (dim = 0; dim < measurementVectorSize; dim++) { - m_Output[dim] += measurements[dim] * weight ; + m_Output[dim] += measurements[dim] * weight; } - ++measurementVectorIndex ; - ++iter ; + ++measurementVectorIndex; + ++iter; } - m_Output /= totalWeight ; + m_Output /= totalWeight; } } @@ -155,11 +155,10 @@ typename WeightedMeanCalculator< TSample >::OutputType* WeightedMeanCalculator< TSample > ::GetOutput() { - return &m_Output ; + return &m_Output; } } // end of namespace Statistics } // end of namespace itk #endif - diff --git a/Utilities/ITK/Code/Numerics/itkCacheableScalarFunction.h b/Utilities/ITK/Code/Numerics/itkCacheableScalarFunction.h index b7ac3fc9bf..c0038fc28d 100644 --- a/Utilities/ITK/Code/Numerics/itkCacheableScalarFunction.h +++ b/Utilities/ITK/Code/Numerics/itkCacheableScalarFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCacheableScalarFunction.h,v $ Language: C++ - Date: $Date: 2007-03-29 19:37:00 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-05-12 17:19:41 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,7 +52,7 @@ namespace itk { * as an energy function. The bias field estimation requires calculation of * energy values again and again for each iteration. */ -class CacheableScalarFunction +class ITK_EXPORT CacheableScalarFunction { public: /** Constructor. */ diff --git a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianCostFunction.cxx b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianCostFunction.cxx index d13fb3e056..39967ffecf 100644 --- a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianCostFunction.cxx +++ b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianCostFunction.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCumulativeGaussianCostFunction.cxx,v $ Language: C++ - Date: $Date: 2007-03-29 19:37:00 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-05 10:56:48 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -68,7 +68,7 @@ CumulativeGaussianCostFunction { fitError += vcl_pow((setTestArray->get(i) - m_OriginalDataArray->get(i)), 2); } - return(sqrt((1/numberOfElements) * fitError)); + return(vcl_sqrt((1/numberOfElements) * fitError)); } double diff --git a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianCostFunction.h b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianCostFunction.h index a1b9263ee4..72749cb0e7 100644 --- a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianCostFunction.h +++ b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianCostFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCumulativeGaussianCostFunction.h,v $ Language: C++ - Date: $Date: 2007-10-27 19:51:42 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-12 17:19:44 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,7 +47,7 @@ namespace itk * \ingroup Numerics Cost Functions */ -class CumulativeGaussianCostFunction : public MultipleValuedCostFunction +class ITK_EXPORT CumulativeGaussianCostFunction : public MultipleValuedCostFunction { public: diff --git a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.cxx index b284446750..07e7a51aeb 100644 --- a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCumulativeGaussianOptimizer.cxx,v $ Language: C++ - Date: $Date: 2007-03-22 21:39:37 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-04-05 10:56:48 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -129,7 +129,7 @@ CumulativeGaussianOptimizer averageSumOfSquaredDifferences = FindAverageSumOfSquaredDifferences(extendedArray, extendedArrayCopy); // Stop if there is a very very very small change between iterations. - if(fabs(temp - averageSumOfSquaredDifferences) <= m_DifferenceTolerance) + if(vcl_fabs(temp - averageSumOfSquaredDifferences) <= m_DifferenceTolerance) break; } // Update the mean calculation. @@ -209,7 +209,7 @@ CumulativeGaussianOptimizer if( i < startingPointForInsertion || i >= startingPointForInsertion + (int)(originalArray->GetNumberOfElements()) ) { - extendedArray->put(i, amplitude * vcl_exp(-(pow((i - mean),2) / (2 * vcl_pow(sd,2))))); + extendedArray->put(i, amplitude * vcl_exp(-(vcl_pow((i - mean),2) / (2 * vcl_pow(sd,2))))); } } return extendedArray; diff --git a/Utilities/ITK/Code/Numerics/itkFRPROptimizer.cxx b/Utilities/ITK/Code/Numerics/itkFRPROptimizer.cxx index 5389e2407a..ba1b2c07b5 100755 --- a/Utilities/ITK/Code/Numerics/itkFRPROptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkFRPROptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFRPROptimizer.cxx,v $ Language: C++ - Date: $Date: 2008-04-23 15:01:26 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-05 10:56:49 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,7 +58,7 @@ FRPROptimizer { len += (*xi)[i]*(*xi)[i]; } - len = sqrt(len/this->GetSpaceDimension()); + len = vcl_sqrt(len/this->GetSpaceDimension()); for(unsigned int i=0; i<this->GetSpaceDimension(); i++) { (*xi)[i] /= len; diff --git a/Utilities/ITK/Code/Numerics/itkMultipleValuedVnlCostFunctionAdaptor.h b/Utilities/ITK/Code/Numerics/itkMultipleValuedVnlCostFunctionAdaptor.h index 8d27e1fd75..b3aa8a981d 100644 --- a/Utilities/ITK/Code/Numerics/itkMultipleValuedVnlCostFunctionAdaptor.h +++ b/Utilities/ITK/Code/Numerics/itkMultipleValuedVnlCostFunctionAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultipleValuedVnlCostFunctionAdaptor.h,v $ Language: C++ - Date: $Date: 2007-03-22 21:39:37 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-05-12 17:19:46 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -33,7 +33,7 @@ namespace itk * * \ingroup Numerics Optimizers */ -class MultipleValuedVnlCostFunctionAdaptor : +class ITK_EXPORT MultipleValuedVnlCostFunctionAdaptor : public vnl_least_squares_function { public: diff --git a/Utilities/ITK/Code/Numerics/itkMultivariateLegendrePolynomial.h b/Utilities/ITK/Code/Numerics/itkMultivariateLegendrePolynomial.h index 89a9e4663c..8235dcd76d 100644 --- a/Utilities/ITK/Code/Numerics/itkMultivariateLegendrePolynomial.h +++ b/Utilities/ITK/Code/Numerics/itkMultivariateLegendrePolynomial.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultivariateLegendrePolynomial.h,v $ Language: C++ -Date: $Date: 2009-01-25 12:45:06 $ -Version: $Revision: 1.26 $ +Date: $Date: 2009-05-12 17:19:47 $ +Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -68,7 +68,7 @@ namespace itk { * (http://www.ia.unc.edu/~styner/docs/StynerTR97.pdf) */ -class MultivariateLegendrePolynomial +class ITK_EXPORT MultivariateLegendrePolynomial { public: typedef MultivariateLegendrePolynomial Self; diff --git a/Utilities/ITK/Code/Numerics/itkPowellOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkPowellOptimizer.cxx index 29cc70924d..342042429e 100755 --- a/Utilities/ITK/Code/Numerics/itkPowellOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkPowellOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPowellOptimizer.cxx,v $ Language: C++ - Date: $Date: 2009-01-24 21:04:35 $ - Version: $Revision: 1.20 $ + Date: $Date: 2009-04-05 10:56:50 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -250,7 +250,7 @@ PowellOptimizer x = bx; w = bx; - const double goldenSectionRatio = (3.0-sqrt(5.0))/2; /* Gold section ratio */ + const double goldenSectionRatio = (3.0-vcl_sqrt(5.0))/2; /* Gold section ratio */ const double POWELL_TINY = 1.0e-20; double functionValueOfX; /* f(x) */ @@ -293,7 +293,7 @@ PowellOptimizer /* Decide if the interpolation can be tried */ - if( fabs(x-w) >= tolerance1 ) /* If x and w are distinct */ + if( vcl_fabs(x-w) >= tolerance1 ) /* If x and w are distinct */ { double t; t = (x-w) * (functionValueOfX-functionValueOfV); @@ -317,7 +317,7 @@ PowellOptimizer /* Chec if x+p/q falls in [a,b] and not too close to a and b and isn't too large */ - if( fabs(p) < fabs(new_step*q) && + if( vcl_fabs(p) < vcl_fabs(new_step*q) && p > q*(a-x+2*tolerance1) && p < q*(b-x-2*tolerance1) ) { @@ -329,7 +329,7 @@ PowellOptimizer } /* Adjust the step to be not less than tolerance*/ - if( fabs(new_step) < tolerance1 ) + if( vcl_fabs(new_step) < tolerance1 ) { if ( new_step > 0.0 ) { diff --git a/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.cxx index f5b63ccc1a..808c58d90f 100644 --- a/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSPSAOptimizer.cxx,v $ Language: C++ - Date: $Date: 2009-01-24 21:04:35 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-05-26 23:45:04 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -70,6 +70,11 @@ SPSAOptimizer os << indent << "Alpha: " << m_Alpha << std::endl; os << indent << "c: " << m_Sc << std::endl; os << indent << "Gamma: " << m_Gamma << std::endl; + os << indent << "Tolerance: " << m_Tolerance << std::endl; + os << indent << "GradientMagnitude: " << m_GradientMagnitude << std::endl; + os << indent << "StateOfConvergenceDecayRate: " << m_StateOfConvergenceDecayRate << std::endl; + os << indent << "Gradient: " << m_Gradient << std::endl; + os << indent << "StateOfConvergence: " << m_StateOfConvergence << std::endl; os << indent << "NumberOfPerturbations: " << m_NumberOfPerturbations << std::endl; @@ -344,9 +349,11 @@ void SPSAOptimizer for ( unsigned int j = 0; j < spaceDimension; j++ ) { /** Generate randomly -1 or 1. */ - // m_Delta[ j ] = 2 * vnl_math_rnd( vnl_sample_uniform(0.0f,1.0f) ) - 1; - +#ifdef ITK_USE_PORTABLE_ROUND + m_Delta[ j ] = 2 * Math::Round( this->m_Generator->GetUniformVariate (0.0f, 1.0f) ) - 1; +#else m_Delta[ j ] = 2 * vnl_math_rnd ( this->m_Generator->GetUniformVariate (0.0f, 1.0f) ) - 1; +#endif /** * Take scales into account. The perturbation of a parameter that has a diff --git a/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.h b/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.h index d065855828..ba9eef7f3e 100644 --- a/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSPSAOptimizer.h,v $ Language: C++ - Date: $Date: 2009-01-26 12:19:14 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-05-12 17:19:52 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,7 +40,7 @@ namespace itk * \ingroup Optimizers */ -class SPSAOptimizer +class ITK_EXPORT SPSAOptimizer : public SingleValuedNonLinearOptimizer { public: diff --git a/Utilities/ITK/Code/Numerics/itkSingleValuedVnlCostFunctionAdaptor.h b/Utilities/ITK/Code/Numerics/itkSingleValuedVnlCostFunctionAdaptor.h index e34552885a..33411788a2 100644 --- a/Utilities/ITK/Code/Numerics/itkSingleValuedVnlCostFunctionAdaptor.h +++ b/Utilities/ITK/Code/Numerics/itkSingleValuedVnlCostFunctionAdaptor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSingleValuedVnlCostFunctionAdaptor.h,v $ Language: C++ - Date: $Date: 2007-03-22 21:39:38 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-05-12 17:19:54 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -33,7 +33,7 @@ namespace itk * * \ingroup Numerics Optimizers */ -class SingleValuedVnlCostFunctionAdaptor : +class ITK_EXPORT SingleValuedVnlCostFunctionAdaptor : public vnl_cost_function { public: diff --git a/Utilities/ITK/Code/Patented/itkActiveShapeModelGradientSearchMethod.txx b/Utilities/ITK/Code/Patented/itkActiveShapeModelGradientSearchMethod.txx index b2ee9f8c9c..b4876e213a 100644 --- a/Utilities/ITK/Code/Patented/itkActiveShapeModelGradientSearchMethod.txx +++ b/Utilities/ITK/Code/Patented/itkActiveShapeModelGradientSearchMethod.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkActiveShapeModelGradientSearchMethod.txx,v $ Language: C++ - Date: $Date: 2009-02-01 13:08:40 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-05 23:09:19 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -269,7 +269,7 @@ ActiveShapeModelGradientSearchMethod<TImage> for(unsigned int j = 0; j < numberOfEigenValues; j++) { - if(fabs(m_Db[j]) > m_Blimit[j]) + if(vcl_fabs(m_Db[j]) > m_Blimit[j]) { m_Db[j] = ( m_Db[j] / vcl_fabs(m_Db[j]) ) * m_Blimit[j]; } diff --git a/Utilities/ITK/Code/Patented/itkSimpleFuzzyConnectednessRGBImageFilter.txx b/Utilities/ITK/Code/Patented/itkSimpleFuzzyConnectednessRGBImageFilter.txx index 47a0e3a4b7..b5a7aa6f7c 100644 --- a/Utilities/ITK/Code/Patented/itkSimpleFuzzyConnectednessRGBImageFilter.txx +++ b/Utilities/ITK/Code/Patented/itkSimpleFuzzyConnectednessRGBImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimpleFuzzyConnectednessRGBImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-01 13:08:41 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-06 11:15:09 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -63,7 +63,7 @@ SimpleFuzzyConnectednessRGBImageFilter<TInputImage,TOutputImage> if(this->GetWeight() == 1) { - return( (NumericTraits<unsigned short>::max())*(exp(-0.5*tmp1)) ); + return( (NumericTraits<unsigned short>::max())*(vcl_exp(-0.5*tmp1)) ); } else { diff --git a/Utilities/ITK/Code/Patented/itkSimpleFuzzyConnectednessScalarImageFilter.txx b/Utilities/ITK/Code/Patented/itkSimpleFuzzyConnectednessScalarImageFilter.txx index 2a274de807..2f9c15796b 100644 --- a/Utilities/ITK/Code/Patented/itkSimpleFuzzyConnectednessScalarImageFilter.txx +++ b/Utilities/ITK/Code/Patented/itkSimpleFuzzyConnectednessScalarImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimpleFuzzyConnectednessScalarImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-01 13:08:41 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-06 11:15:09 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -76,7 +76,7 @@ SimpleFuzzyConnectednessScalarImageFilter<TInputImage,TOutputImage> if(this->GetWeight() == 1) { return( (NumericTraits<unsigned short>::max())* - (exp(-0.5 * tmp1 * tmp1 / m_Variance))); + (vcl_exp(-0.5 * tmp1 * tmp1 / m_Variance))); } else { diff --git a/Utilities/ITK/Code/Patented/itkVectorFuzzyConnectednessImageFilter.txx b/Utilities/ITK/Code/Patented/itkVectorFuzzyConnectednessImageFilter.txx index 590005ac51..2643e6ffcf 100644 --- a/Utilities/ITK/Code/Patented/itkVectorFuzzyConnectednessImageFilter.txx +++ b/Utilities/ITK/Code/Patented/itkVectorFuzzyConnectednessImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorFuzzyConnectednessImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-01-31 17:23:45 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-06 16:49:30 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -176,7 +176,7 @@ VectorFuzzyConnectednessImageFilter<TInputImage,TOutputImage> { if (ppptti1[tti1 + i][tti1 + j] == 0) { - tt1 = vcl_sqrt(pow(((double) i) * anisotropy_row,2.0) + vcl_pow(((double) j) * anisotropy_col, 2.0)); + tt1 = vcl_sqrt(vcl_pow(((double) i) * anisotropy_row,2.0) + vcl_pow(((double) j) * anisotropy_col, 2.0)); if (tt1 <= ((double) k) + 0.5) { m_CirclePointsNum[k] = m_CirclePointsNum[k] + 1; diff --git a/Utilities/ITK/Code/Review/CMakeLists.txt b/Utilities/ITK/Code/Review/CMakeLists.txt index e57a28749b..6803085012 100644 --- a/Utilities/ITK/Code/Review/CMakeLists.txt +++ b/Utilities/ITK/Code/Review/CMakeLists.txt @@ -23,6 +23,10 @@ IF(NOT ITK_INSTALL_NO_LIBRARIES) ARCHIVE DESTINATION ${ITK_INSTALL_LIB_DIR_CM24} COMPONENT Development) ENDIF(NOT ITK_INSTALL_NO_LIBRARIES) +# Use the new statistics framework.. +IF (ITK_USE_REVIEW_STATISTICS) + SUBDIRS( Statistics ) +ENDIF (ITK_USE_REVIEW_STATISTICS) IF(ITK_USE_TRANSFORM_IO_FACTORIES) diff --git a/Utilities/ITK/Code/Review/Statistics/CMakeLists.txt b/Utilities/ITK/Code/Review/Statistics/CMakeLists.txt new file mode 100644 index 0000000000..be32d4cdc6 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/CMakeLists.txt @@ -0,0 +1,42 @@ +# Sources for ITKStatisticsNew library + +ADD_LIBRARY(ITKStatistics + itkDenseFrequencyContainer2.cxx + itkSparseFrequencyContainer2.cxx + itkDecisionRule.cxx + itkMaximumDecisionRule2.cxx + itkMaximumRatioDecisionRule2.cxx + itkMinimumDecisionRule2.cxx + itkNormalVariateGenerator.cxx + + # Distributions + itkGaussianDistribution.cxx + itkTDistribution.cxx + itkChiSquareDistribution.cxx + ) + +TARGET_LINK_LIBRARIES(ITKStatistics ITKCommon itkNetlibSlatec ) + +IF(ITK_LIBRARY_PROPERTIES) + SET_TARGET_PROPERTIES(ITKStatistics PROPERTIES ${ITK_LIBRARY_PROPERTIES}) +ENDIF(ITK_LIBRARY_PROPERTIES) + +IF(NOT ITK_INSTALL_NO_LIBRARIES) + INSTALL(TARGETS ITKStatistics + RUNTIME DESTINATION ${ITK_INSTALL_BIN_DIR_CM24} COMPONENT RuntimeLibraries + LIBRARY DESTINATION ${ITK_INSTALL_LIB_DIR_CM24} COMPONENT RuntimeLibraries + ARCHIVE DESTINATION ${ITK_INSTALL_LIB_DIR_CM24} COMPONENT Development) +ENDIF(NOT ITK_INSTALL_NO_LIBRARIES) + +IF(NOT ITK_INSTALL_NO_DEVELOPMENT) + FILE(GLOB __files1 "${CMAKE_CURRENT_SOURCE_DIR}/*.h") + FILE(GLOB __files2 "${CMAKE_CURRENT_SOURCE_DIR}/*.txx") + INSTALL(FILES ${__files1} ${__files2} + DESTINATION ${ITK_INSTALL_INCLUDE_DIR_CM24}/Numerics/Statistics + COMPONENT Development) +ENDIF(NOT ITK_INSTALL_NO_DEVELOPMENT) + +IF(BORLAND) + SET (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w-8057 -w-8004") +ENDIF(BORLAND) + diff --git a/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.cxx b/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.cxx new file mode 100644 index 0000000000..641ac6cf7d --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.cxx @@ -0,0 +1,379 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkChiSquareDistribution.cxx,v $ + Language: C++ + Date: $Date: 2009-05-10 18:27:08 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "itkChiSquareDistribution.h" +#include "itkGaussianDistribution.h" +#include "itkNumericTraits.h" +#include "vnl/vnl_math.h" +#include "vnl/vnl_erf.h" + +extern "C" double dgami_(double *a, double *x); +extern "C" double dgamma_(double *x); + +namespace itk { +namespace Statistics { + +ChiSquareDistribution +::ChiSquareDistribution() +{ + m_Parameters = ParametersType(1); + m_Parameters[0] = 1.0; +} + +void +ChiSquareDistribution +::SetDegreesOfFreedom(long dof) +{ + bool modified = false; + + if (m_Parameters.GetSize() > 0) + { + if (m_Parameters[0] != static_cast<double>(dof) ) + { + modified = true; + } + } + + if (m_Parameters.GetSize() != 1) + { + m_Parameters = ParametersType(1); + } + + m_Parameters[0] = static_cast<double>(dof); + + if (modified) + { + this->Modified(); + } +} + +long +ChiSquareDistribution +::GetDegreesOfFreedom() const +{ + if (m_Parameters.GetSize() != 1) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return static_cast<long>(m_Parameters[0]); +} + +double +ChiSquareDistribution +::PDF(double x, long degreesOfFreedom) +{ + double dof = static_cast<double>(degreesOfFreedom); + double dofon2 = 0.5*dof; + double pdf = 0.0; + + if (x >= 0.0) + { + pdf = exp(-0.5*x) * pow(x, dofon2 - 1.0) + / (pow(2.0, dofon2) * dgamma_(&dofon2)); + } + + return pdf; +} + + +double +ChiSquareDistribution +::PDF(double x, const ParametersType& p) +{ + if (p.GetSize() != 1) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << p.size() + << " parameters."); + } + return ChiSquareDistribution::PDF(x, static_cast<long>(p[0])); +} + +double +ChiSquareDistribution +::CDF(double x, long degreesOfFreedom) +{ + // Based on Abramowitz and Stegun 26.4.19 which relates the + // cumulative of the chi-square to incomplete (and complete) gamma + // function. + if (x < 0) + { + return 0.0; + } + + double dofon2 = 0.5*degreesOfFreedom; + double xon2 = 0.5*x; + + return dgami_(&dofon2, &xon2) / dgamma_(&dofon2); +} + + +double +ChiSquareDistribution +::CDF(double x, const ParametersType& p) +{ + if (p.GetSize() != 1) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << p.size() + << " parameters."); + } + return ChiSquareDistribution::CDF(x, (long) p[0]); +} + +double +ChiSquareDistribution +::InverseCDF(double p, long degreesOfFreedom) +{ + if (p <= 0.0) + { + return itk::NumericTraits<double>::Zero; + } + else if (p >= 1.0) + { + return itk::NumericTraits<double>::max(); + } + + double x; + double dof; + double nx; + + // Based on Abramowitz and Stegun 26.4.17 + dof = static_cast<double>(degreesOfFreedom); + nx = GaussianDistribution::InverseCDF(p); + + double f = 2.0 / (9.0*dof); + x = dof*pow(1.0 - f + nx*sqrt(f), 3.0); + + + // The approximation above is only accurate for large degrees of + // freedom. We'll improve the approximation by a few Newton iterations. + // + // 0 iterations, error = 10^-1 at 1 degree of freedom + // 3 iterations, error = 10^-11 at 1 degree of freedom + // 10 iterations, erorr = 10^-13 at 1 degree of freedom + // 20 iterations, erorr = 10^-13 at 1 degree of freedom + // + // 0 iterations, error = 10^-1 at 11 degrees of freedom + // 3 iterations, error = 10^-8 at 11 degrees of freedom + // 10 iterations, erorr = 10^-13 at 11 degrees of freedom + // 20 iterations, erorr = 10^-13 at 11 degrees of freedom + // + // 0 iterations, error = 10^-1 at 100 degrees of freedom + // 3 iterations, error = 10^-9 at 100 degrees of freedom + // 10 iterations, erorr = 10^-10 at 100 degrees of freedom + // 20 iterations, erorr = 10^-9 at 100 degrees of freedom + + + // We are trying to find the zero of + // + // f(x) = p - chisquarecdf(x) = 0; + // + // So, + // + // x(n+1) = x(n) - f(x(n)) / f'(x(n)) + // = x(n) + (p - chisquarecdf(x)) / chisquarepdf(x) + // + // Note that f'(x) = - chisquarepdf(x) + // + double delta; + for (unsigned int newt = 0; newt < 10; ++newt) + { + delta = (p - ChiSquareDistribution::CDF(x, degreesOfFreedom)) + / ChiSquareDistribution::PDF(x, degreesOfFreedom); + x += delta; + } + + return x; +} + + +double +ChiSquareDistribution +::InverseCDF(double p, const ParametersType& params) +{ + if( params.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << params.size() + << " parameters."); + } + return ChiSquareDistribution::InverseCDF(p, static_cast<long>(params[0])); +} + +double +ChiSquareDistribution +::EvaluatePDF(double x) const +{ + if( m_Parameters.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return ChiSquareDistribution::PDF(x, static_cast<long>(m_Parameters[0])); +} + +double +ChiSquareDistribution +::EvaluatePDF(double x, const ParametersType& p) const +{ + if( p.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << p.size() + << " parameters."); + } + return ChiSquareDistribution::PDF(x, static_cast<long>(p[0])); +} + +double +ChiSquareDistribution +::EvaluatePDF(double x, long degreesOfFreedom) const +{ + return ChiSquareDistribution::PDF(x, degreesOfFreedom); +} + + +double +ChiSquareDistribution +::EvaluateCDF(double x) const +{ + if( m_Parameters.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return ChiSquareDistribution::CDF(x, static_cast<long>(m_Parameters[0])); +} + +double +ChiSquareDistribution +::EvaluateCDF(double x, const ParametersType& p) const +{ + if( p.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << p.size() + << " parameters."); + } + return ChiSquareDistribution::CDF(x, static_cast<long>(p[0])); +} + +double +ChiSquareDistribution +::EvaluateCDF(double x, long degreesOfFreedom) const +{ + return ChiSquareDistribution::CDF(x, degreesOfFreedom); +} + + +double +ChiSquareDistribution +::EvaluateInverseCDF(double p) const +{ + if( m_Parameters.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return ChiSquareDistribution::InverseCDF(p, static_cast<long>(m_Parameters[0])); +} + +double +ChiSquareDistribution +::EvaluateInverseCDF(double p, const ParametersType& params) const +{ + if( params.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << params.size() + << " parameters."); + } + return ChiSquareDistribution::InverseCDF(p, static_cast<long>(params[0])); +} + +double +ChiSquareDistribution +::EvaluateInverseCDF(double p, long degreesOfFreedom) const +{ + return ChiSquareDistribution::InverseCDF(p, degreesOfFreedom); +} + + +double +ChiSquareDistribution +::GetMean() const +{ + if( m_Parameters.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return m_Parameters[0]; +} + +double +ChiSquareDistribution +::GetVariance() const +{ + if( m_Parameters.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return 2.0 * m_Parameters[0]; +} + +void +ChiSquareDistribution +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + if (m_Parameters.GetSize() > 0) + { + os << indent << "Degrees of freedom: " + << static_cast<long>(m_Parameters[0]) << std::endl; + } + else + { + os << indent << "Degrees of freedom: (unknown)" + << std::endl; + } +} + +} // end of namespace Statistics +} // end namespace itk diff --git a/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.h b/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.h new file mode 100644 index 0000000000..5e12baeb8f --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.h @@ -0,0 +1,210 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkChiSquareDistribution.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkChiSquareDistribution_h +#define __itkChiSquareDistribution_h + +#include "itkProbabilityDistribution.h" +#include "itkNumericTraits.h" + +namespace itk { +namespace Statistics { + +/** \class ChiSquareDistribution + * \brief ChiSquareDistribution class defines the interface for a + * univariate Chi-Square distribution (pdfs, cdfs, etc.). + * + * ChiSquareDistribution provides access to the probability density + * function (pdf), the cumulative distribution function (cdf), and the + * inverse cumulative distribution function for a Chi-Square distribution. + * + * The EvaluatePDF(), EvaluateCDF, EvaluateInverseCDF() methods are + * all virtual, allowing algorithms to be written with an abstract + * interface to a distribution (with said distribution provided to the + * algorithm at run-time). Static methods, not requiring an instance + * of the distribution, are also provided. The static methods allow + * for optimized access to distributions when the distribution is + * known a priori to the algorithm. + * + * ChiSquareDistributions are univariate. Multivariate versions may + * be provided under a separate superclass (since the parameters to the + * pdf and cdf would have to be vectors not scalars). + * + * ChiSquareDistributions can be used for Chi-Square tests. + * + * \note This work is part of the National Alliance for Medical Image + * Computing (NAMIC), funded by the National Institutes of Health + * through the NIH Roadmap for Medical Research, Grant U54 EB005149. + * Information on the National Centers for Biomedical Computing + * can be obtained from http://nihroadmap.nih.gov/bioinformatics. + */ +class ITK_EXPORT ChiSquareDistribution : + public ProbabilityDistribution +{ +public: + /** Standard class typedefs */ + typedef ChiSquareDistribution Self; + typedef ProbabilityDistribution Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Strandard macros */ + itkTypeMacro(ChiSquareDistribution, ProbabilityDistribution); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Return the number of parameters. For a Chi-Square + * distribution, the number of parameters is 1 (degrees of freedom) */ + virtual unsigned long GetNumberOfParameters() const { return 1; } + + /** Evaluate the probability density function (pdf). The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluatePDF(double x) const; + + /** Evaluate the probability density function (pdf). The parameters + * for the distribution are passed as a parameters vector. The + * ordering of the parameters is (degrees of freedom). */ + virtual double EvaluatePDF(double x, const ParametersType&) const; + + /** Evaluate the probability density function (pdf). The parameters + * of the distribution are passed as separate parameters. */ + virtual double EvaluatePDF(double x, long degreesOfFreedom) const; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluateCDF(double x) const; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * for the distribution are passed as a parameters vector. The + * ordering of the parameters is (degreesOfFreedom). */ + virtual double EvaluateCDF(double x, const ParametersType&) const; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * of the distribution are passed as separate parameters. */ + virtual double EvaluateCDF(double x, long degreesOfFreedom) const; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluateInverseCDF(double p) const; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * for the distribution are passed as a parameters vector. The + * ordering of the parameters is (degrees of freedom). */ + virtual double EvaluateInverseCDF(double p, const ParametersType&) const; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * of the distribution are passed as separate parameters. */ + virtual double EvaluateInverseCDF(double p, long degreesOfFreedom) const; + + /** Set the number of degrees of freedom in the Chi-Square distribution. + * Defaults to 1 */ + virtual void SetDegreesOfFreedom(long); + + /** Get the number of degrees of freedom in the t + * distribution. Defaults to 1 */ + virtual long GetDegreesOfFreedom() const; + + /** Does the Chi-Square distribution have a mean? */ + virtual bool HasMean() const { return true; } + + /** Get the mean of the distribution. */ + virtual double GetMean() const; + + /** Does the Chi-Square distribution have a variance? */ + virtual bool HasVariance() const { return true; } + + /** Get the variance of the distribution. */ + virtual double GetVariance() const; + + + /** Static method to evaluate the probability density function (pdf) + * of a Chi-Square with a specified number of degrees of freedom. The + * static method provides optimized access without requiring an + * instance of the class. The degrees of freedom for the + * distribution are passed in a parameters vector. */ + static double PDF(double x, const ParametersType&); + + /** Static method to evaluate the probability density function (pdf) + * of a Chi-Square with a specified number of degrees of freedom. The + * static method provides optimized access without requiring an + * instance of the class. */ + static double PDF(double x, long degreesOfFreedom); + + /** Static method to evaluate the cumulative distribution function + * (cdf) of a Chi-Square with a specified number of degrees of + * freedom. The static method provides optimized access without + * requiring an instance of the class. The degrees of freedom are + * passed as a parameters vector. + * + * This is based on Abramowitz and Stegun 26.7.1. Accuracy is + * approximately 10^-14. + */ + static double CDF(double x, const ParametersType&); + + /** Static method to evaluate the cumulative distribution function + * (cdf) of a Chi-Square with a specified number of degrees of + * freedom. The static method provides optimized access without + * requiring an instance of the class. + * + * This is based on Abramowitz and Stegun 26.7.1. Accuracy is + * approximately 10^-14. + */ + static double CDF(double x, long degreesOfFreedom); + + /** Static method to evaluate the inverse cumulative distribution + * function of a Chi-Square with a specified number of degrees of + * freedom. The static method provides optimized access without + * requiring an instance of the class. Parameter p must be between + * 0.0 and 1.0. The degrees of freedom are passed as a parameters vector. + * + * This is based on Abramowitz and Stegun 26.7.5 followed by a few + * Newton iterations to improve the precision at low degrees of + * freedom. Accuracy is approximately 10^-10. + **/ + static double InverseCDF(double p, const ParametersType&); + + /** Static method to evaluate the inverse cumulative distribution + * function of a Chi-Square with a specified number of degrees of + * freedom. The static method provides optimized access without + * requiring an instance of the class. Parameter p must be between + * 0.0 and 1.0. + * + * This is based on Abramowitz and Stegun 26.7.5 followed by a few + * Newton iterations to improve the precision at low degrees of + * freedom. Accuracy is approximately 10^-10. + **/ + static double InverseCDF(double p, long degreesOfFreedom); + +protected: + ChiSquareDistribution(void); + virtual ~ChiSquareDistribution(void) {} + + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + ChiSquareDistribution(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end of namespace Statistics +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkCovarianceSampleFilter.h b/Utilities/ITK/Code/Review/Statistics/itkCovarianceSampleFilter.h new file mode 100644 index 0000000000..e2701c53e3 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkCovarianceSampleFilter.h @@ -0,0 +1,120 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCovarianceSampleFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkCovarianceSampleFilter_h +#define __itkCovarianceSampleFilter_h + +#include "itkProcessObject.h" + +#include "itkArray.h" +#include "itkVariableSizeMatrix.h" +#include "itkSimpleDataObjectDecorator.h" + +namespace itk { +namespace Statistics { + +/** \class CovarianceSampleFilter + * \brief Calculates the covariance matrix of the target sample data. + * + * The filter calculates first the sample mean and use it in the covariance + * calculation. The covariance is computed as follows + * Let \f$\Sigma\f$ denotes covariance matrix for the sample, then: + * When \f$x_{i}\f$ is \f$i\f$th component of a measurement vector + * \f$\vec x\f$, \f$\mu_{i}\f$ is the \f$i\f$th componet of the \f$\vec\mu\f$, + * and the \f$\sigma_{ij}\f$ is the \f$ij\f$th componet \f$\Sigma\f$, + * \f$\sigma_{ij} = (x_{i} - \mu_{i})(x_{j} - \mu_{j})\f$ + * + * Without the plugged in mean vector, this calculator will perform + * the single pass mean and covariance calculation algorithm. + * + */ + +template< class TSample > +class ITK_EXPORT CovarianceSampleFilter : + public ProcessObject +{ +public: + /** Standard class typedefs. */ + typedef CovarianceSampleFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef TSample SampleType; + + /** Standard Macros */ + itkTypeMacro(CovarianceSampleFilter, ProcessObject); + itkNewMacro(Self); + + /** Length of a measurement vector */ + typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; + + /** Measurement vector type */ + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + + /** Typedef for Covariance output */ + typedef VariableSizeMatrix< double > MatrixType; + + /** Method to set/get the sample */ + void SetInput( const SampleType * sample ); + const SampleType * GetInput() const; + + /** VariableSizeMatrix is not a DataObject, we need to decorate it to push it down + * a ProcessObject's pipeline */ + typedef SimpleDataObjectDecorator< MatrixType > MatrixDecoratedType; + + /** MeasurementVector is not a DataObject, we need to decorate it to push it down + * a ProcessObject's pipeline */ + typedef SimpleDataObjectDecorator< MeasurementVectorType > MeasurementVectorDecoratedType; + + typedef MeasurementVectorDecoratedType OutputType; + + /** Return the covariance matrix */ + const MatrixType GetCovarianceMatrix() const; + const MatrixDecoratedType* GetCovarianceMatrixOutput() const; + + /** Return the mean vector */ + const MeasurementVectorType GetMean() const; + const MeasurementVectorDecoratedType* GetMeanOutput() const; + +protected: + CovarianceSampleFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + CovarianceSampleFilter(); + virtual ~CovarianceSampleFilter(); + void PrintSelf(std::ostream& os, Indent indent) const; + + /** DataObject pointer */ + typedef DataObject::Pointer DataObjectPointer; + + virtual DataObjectPointer MakeOutput(unsigned int idx); + + void GenerateData(); + + MeasurementVectorSizeType GetMeasurementVectorSize() const; + +private: +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkCovarianceSampleFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkCovarianceSampleFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkCovarianceSampleFilter.txx new file mode 100644 index 0000000000..6031fa23c6 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkCovarianceSampleFilter.txx @@ -0,0 +1,262 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCovarianceSampleFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkCovarianceSampleFilter_txx +#define __itkCovarianceSampleFilter_txx + +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +CovarianceSampleFilter< TSample > +::CovarianceSampleFilter() +{ + this->ProcessObject::SetNumberOfRequiredInputs(1); + this->ProcessObject::SetNumberOfRequiredOutputs(2); + + this->ProcessObject::SetNthOutput(0, this->MakeOutput(0) ); + this->ProcessObject::SetNthOutput(1, this->MakeOutput(1) ); +} + +template< class TSample > +CovarianceSampleFilter< TSample > +::~CovarianceSampleFilter() +{ +} + +template< class TSample > +void +CovarianceSampleFilter< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} + +template< class TSample > +void +CovarianceSampleFilter< TSample > +::SetInput( const SampleType * sample ) +{ + this->ProcessObject::SetNthInput(0, const_cast< SampleType* >( sample ) ); +} + +template< class TSample > +const TSample * +CovarianceSampleFilter< TSample > +::GetInput( ) const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const SampleType * > + (this->ProcessObject::GetInput(0) ); +} + +template< class TSample > +typename CovarianceSampleFilter< TSample>::DataObjectPointer +CovarianceSampleFilter< TSample > +::MakeOutput(unsigned int index ) +{ + MeasurementVectorSizeType measurementVectorSize = this->GetMeasurementVectorSize(); + + if ( index == 0 ) + { + MatrixType covarianceMatrix( measurementVectorSize, measurementVectorSize ); + covarianceMatrix.SetIdentity(); + MatrixDecoratedType::Pointer decoratedCovarianceMatrix = MatrixDecoratedType::New(); + decoratedCovarianceMatrix->Set( covarianceMatrix ); + return static_cast< DataObject * >(decoratedCovarianceMatrix.GetPointer()); + } + + if ( index == 1 ) + { + typedef typename MeasurementVectorTraitsTypes< MeasurementVectorType >::ValueType ValueType; + MeasurementVectorType mean; + (void)mean; // for complainty pants : valgrind + MeasurementVectorTraits::SetLength( mean, this->GetMeasurementVectorSize() ); + mean.Fill( NumericTraits< ValueType >::Zero ); + typename MeasurementVectorDecoratedType::Pointer decoratedMean = MeasurementVectorDecoratedType::New(); + decoratedMean->Set( mean ); + return static_cast< DataObject * >( decoratedMean.GetPointer() ); + } + itkExceptionMacro("Trying to create output of index " << index << " larger than the number of output"); +} + +template< class TSample > +typename CovarianceSampleFilter< TSample >::MeasurementVectorSizeType +CovarianceSampleFilter< TSample > +::GetMeasurementVectorSize() const +{ + const SampleType *input = this->GetInput(); + + if( input ) + { + return input->GetMeasurementVectorSize(); + } + + // Test if the Vector type knows its length + MeasurementVectorType vector; + MeasurementVectorSizeType measurementVectorSize = MeasurementVectorTraits::GetLength( vector ); + + if( measurementVectorSize ) + { + return measurementVectorSize; + } + + measurementVectorSize = 1; // Otherwise set it to an innocuous value + + return measurementVectorSize; +} + + +template< class TSample > +inline void +CovarianceSampleFilter< TSample > +::GenerateData() +{ + const SampleType *input = this->GetInput(); + + MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); + + MatrixDecoratedType * decoratedOutput = + static_cast< MatrixDecoratedType * >( + this->ProcessObject::GetOutput(0)); + + MatrixType output = decoratedOutput->Get(); + + MeasurementVectorDecoratedType * decoratedMeanOutput = + static_cast< MeasurementVectorDecoratedType * >( + this->ProcessObject::GetOutput(1)); + + output.SetSize( measurementVectorSize, measurementVectorSize ); + output.Fill(0.0); + + MeasurementVectorType mean; + + MeasurementVectorTraits::SetLength( mean, measurementVectorSize ); + + mean.Fill(0.0); + + double frequency; + double totalFrequency = 0.0; + + typename TSample::ConstIterator iter = input->Begin(); + typename TSample::ConstIterator end = input->End(); + + MeasurementVectorType diff; + MeasurementVectorType measurements; + + MeasurementVectorTraits::SetLength( diff, measurementVectorSize ); + MeasurementVectorTraits::SetLength( measurements, measurementVectorSize ); + + //Compute the mean first + while (iter != end) + { + frequency = iter.GetFrequency(); + totalFrequency += frequency; + measurements = iter.GetMeasurementVector(); + + for( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + mean[i] += frequency * measurements[i]; + } + ++iter; + } + + for( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + mean[i] = mean[i] / totalFrequency; + } + + decoratedMeanOutput->Set( mean ); + + //reset the total frequency and iterator + iter = input->Begin(); + // fills the lower triangle and the diagonal cells in the covariance matrix + while (iter != end) + { + frequency = iter.GetFrequency(); + measurements = iter.GetMeasurementVector(); + for ( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + diff[i] = measurements[i] - mean[i]; + } + + // updates the covariance matrix + for( unsigned int row = 0; row < measurementVectorSize; row++ ) + { + for( unsigned int col = 0; col < row + 1; col++) + { + output(row,col) += frequency * diff[row] * diff[col]; + } + } + ++iter; + } + + // fills the upper triangle using the lower triangle + for( unsigned int row = 1; row < measurementVectorSize; row++) + { + for( unsigned int col = 0; col < row; col++) + { + output(col, row) = output(row, col); + } + } + + output /= ( totalFrequency - 1.0 ); + + decoratedOutput->Set( output ); +} + +template< class TSample > +const typename CovarianceSampleFilter< TSample>::MatrixDecoratedType * +CovarianceSampleFilter< TSample > +::GetCovarianceMatrixOutput() const +{ + return static_cast<const MatrixDecoratedType *>(this->ProcessObject::GetOutput(0)); +} + +template< class TSample > +const typename CovarianceSampleFilter< TSample>::MatrixType +CovarianceSampleFilter< TSample > +::GetCovarianceMatrix() const +{ + return this->GetCovarianceMatrixOutput()->Get(); +} + +template< class TSample > +const typename CovarianceSampleFilter< TSample>::MeasurementVectorDecoratedType * +CovarianceSampleFilter< TSample > +::GetMeanOutput() const +{ + return static_cast<const MeasurementVectorDecoratedType *>(this->ProcessObject::GetOutput(1)); +} + +template< class TSample > +const typename CovarianceSampleFilter< TSample>::MeasurementVectorType +CovarianceSampleFilter< TSample > +::GetMean() const +{ + return this->GetMeanOutput()->Get(); +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkDecisionRule.cxx b/Utilities/ITK/Code/Review/Statistics/itkDecisionRule.cxx new file mode 100644 index 0000000000..5d18f108f9 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkDecisionRule.cxx @@ -0,0 +1,40 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDecisionRule.cxx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkDecisionRule.h" + +namespace itk { +namespace Statistics { + +DecisionRule +::DecisionRule() +{ +} + +DecisionRule +::~DecisionRule() +{ +} + +void +DecisionRule +::PrintSelf( std::ostream& os, Indent indent ) const +{ + Superclass::PrintSelf(os,indent); +}// end PrintSelf + +} // end of namespace Statistics +} // end of namespace itk diff --git a/Utilities/ITK/Code/Review/Statistics/itkDecisionRule.h b/Utilities/ITK/Code/Review/Statistics/itkDecisionRule.h new file mode 100644 index 0000000000..743ec784ce --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkDecisionRule.h @@ -0,0 +1,70 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDecisionRule.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkDecisionRule_h +#define __itkDecisionRule_h + +#include <vector> +#include "vnl/vnl_matrix.h" +#include "itkObject.h" +#include "itkObjectFactory.h" +#include "itkArray.h" +#include "itkVariableLengthVector.h" + +namespace itk { +namespace Statistics { + +/** \class DecisionRule + * \brief Base class that allows the setting of usage of different + * decision rules used in classification + * This class has the pure virtual function, Evaluate(). Therefore, + * any subclass should implement the function to be instantiated. + */ + +class ITK_EXPORT DecisionRule : public Object +{ +public: + /** Standard class typedefs */ + typedef DecisionRule Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro(DecisionRule, Object); + + /** Types for the arguments that are acceptable in the Evaluate() method */ + typedef std::vector< double > MembershipVectorType; + + /** The return value of this function is a class label. + * Basically, using its internal logic based on the discriminant + * scores, this function decides best class label and return it. + */ + virtual unsigned int Evaluate( const MembershipVectorType & discriminantScores ) const = 0; + +protected: + DecisionRule(); + virtual ~DecisionRule(); + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + DecisionRule(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; // end of class +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkDenseFrequencyContainer2.cxx b/Utilities/ITK/Code/Review/Statistics/itkDenseFrequencyContainer2.cxx new file mode 100644 index 0000000000..af41b55a26 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkDenseFrequencyContainer2.cxx @@ -0,0 +1,92 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDenseFrequencyContainer2.cxx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkDenseFrequencyContainer2.h" + +namespace itk{ +namespace Statistics{ + +DenseFrequencyContainer2 +::DenseFrequencyContainer2() +{ + m_FrequencyContainer = FrequencyContainerType::New(); + m_TotalFrequency = NumericTraits< TotalAbsoluteFrequencyType >::Zero; +} + +void +DenseFrequencyContainer2 +::Initialize(unsigned long length) +{ + m_FrequencyContainer->Reserve(length); + this->SetToZero(); +} + +void +DenseFrequencyContainer2 +::SetToZero() +{ + m_FrequencyContainer->Fill( NumericTraits< AbsoluteFrequencyType >::Zero ); + m_TotalFrequency = NumericTraits< TotalAbsoluteFrequencyType >::Zero; +} + +bool +DenseFrequencyContainer2 +::SetFrequency(const InstanceIdentifier id, const AbsoluteFrequencyType value) +{ + if( id >= m_FrequencyContainer->Size() ) + { + return false; + } + AbsoluteFrequencyType frequency = this->GetFrequency(id); + (*m_FrequencyContainer)[id] = value; + m_TotalFrequency += (value - frequency); + return true; +} + +DenseFrequencyContainer2::AbsoluteFrequencyType +DenseFrequencyContainer2 +::GetFrequency(const InstanceIdentifier id) const +{ + if( id >= m_FrequencyContainer->Size() ) + { + return NumericTraits< AbsoluteFrequencyType >::Zero; + } + return (*m_FrequencyContainer)[id]; +} + +bool +DenseFrequencyContainer2 +::IncreaseFrequency(const InstanceIdentifier id, const AbsoluteFrequencyType value) +{ + if( id >= m_FrequencyContainer->Size() ) + { + return false; + } + AbsoluteFrequencyType frequency = this->GetFrequency(id); + (*m_FrequencyContainer)[id] = frequency + value; + m_TotalFrequency += value; + return true; +} + +void +DenseFrequencyContainer2 +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} + +} // end of namespace Statistics +} // end of namespace itk diff --git a/Utilities/ITK/Code/Review/Statistics/itkDenseFrequencyContainer2.h b/Utilities/ITK/Code/Review/Statistics/itkDenseFrequencyContainer2.h new file mode 100644 index 0000000000..cd3b320143 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkDenseFrequencyContainer2.h @@ -0,0 +1,124 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDenseFrequencyContainer2.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkDenseFrequencyContainer2_h +#define __itkDenseFrequencyContainer2_h + +#include <map> +#include "itkObjectFactory.h" +#include "itkObject.h" +#include "itkValarrayImageContainer.h" +#include "itkNumericTraits.h" +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +/** \class DenseFrequencyContainer2 + * \brief his class is a container for frequencies of bins in an histogram. + * + * This class uses the ValarrayImageContainer class to store + * frequencies. If the histogram has many zero frequency bins. + * use SparseFrequencyContainer. You should access each bin + * by (InstanceIdentifier)index or measurement vector. + * + * \sa Histogram, SparseFrequencyContainer + */ + +class ITK_EXPORT DenseFrequencyContainer2 + : public Object +{ +public: + /** Standard class typedefs */ + typedef DenseFrequencyContainer2 Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(DenseFrequencyContainer2, Object); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** InstanceIdenfitifer type alias */ + typedef MeasurementVectorTraits::InstanceIdentifier InstanceIdentifier; + + /** Absoluate Frequency type alias */ + typedef MeasurementVectorTraits::AbsoluteFrequencyType AbsoluteFrequencyType; + + /** Absolute Total frequency type */ + typedef MeasurementVectorTraits::TotalAbsoluteFrequencyType TotalAbsoluteFrequencyType; + + /** Relative Frequency type alias */ + typedef MeasurementVectorTraits::RelativeFrequencyType RelativeFrequencyType; + + /** Relative Total frequency type */ + typedef MeasurementVectorTraits::TotalRelativeFrequencyType TotalRelativeFrequencyType; + + + /** Internal storage class typedefs */ + typedef ValarrayImageContainer< InstanceIdentifier, AbsoluteFrequencyType > + FrequencyContainerType; + + typedef FrequencyContainerType::Pointer FrequencyContainerPointer; + + /** Calls the Initialize method of superclass to generate the offset table + * and prepare the frequency container */ + void Initialize(unsigned long length); + + /** Calls the SetToZero method of superclass to initialize all the bins to Zero. + * This should be done before starting to call the IncreaseFrequency method. */ + void SetToZero(); + + /** Sets the frequency of histogram using instance identifier. It returns + * false when the Id is out of bounds. */ + bool SetFrequency(const InstanceIdentifier id, const AbsoluteFrequencyType value); + + /** Increases the frequency of a bin specified by the InstanceIdentifier by + * one. This function is convinient to create a histogram. It returns false + * when the bin id is out of bounds. */ + bool IncreaseFrequency(const InstanceIdentifier id, + const AbsoluteFrequencyType value); + + /** Method to get the frequency of a bin from the histogram. It returns zero + * when the Id is out of bounds. */ + AbsoluteFrequencyType GetFrequency(const InstanceIdentifier id) const; + + /** Gets the sum of the frequencies */ + TotalAbsoluteFrequencyType GetTotalFrequency() + { + return m_TotalFrequency; + } + +protected: + DenseFrequencyContainer2(); + virtual ~DenseFrequencyContainer2() {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + DenseFrequencyContainer2(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Internal storage */ + FrequencyContainerPointer m_FrequencyContainer; + TotalAbsoluteFrequencyType m_TotalFrequency; +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkDistanceMetric.h b/Utilities/ITK/Code/Review/Statistics/itkDistanceMetric.h new file mode 100644 index 0000000000..31902a33b2 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkDistanceMetric.h @@ -0,0 +1,144 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDistanceMetric.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkDistanceMetric_h +#define __itkDistanceMetric_h + +#include "itkArray.h" +#include "itkFunctionBase.h" +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +/** \class DistanceMetric + * \brief this class declares common interfaces + * for distance functions. + * + * As a function derived from FunctionBase, users use Evaluate method to get + * result. + * + * To use this function users should first set the origin by calling + * SetOrigin() function, then call Evaluate() method with a point to get the + * distance between the origin point and the evaluation point. + * + * \sa EuclideanSquareDistanceMetric + * \sa EuclideanDistanceMetric + * \sa ManhattanDistanceMetric + * + */ + +template< class TVector > +class ITK_EXPORT DistanceMetric : public FunctionBase< TVector, double > +{ +public: + /** Standard typedefs */ + typedef DistanceMetric Self; + typedef FunctionBase< TVector, double > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** declare the MeasurementVector type */ + typedef TVector MeasurementVectorType; + + /** declare Measurement vector component type */ + /** Type used to represent the number of components oft he MeasurementVectorType */ + typedef unsigned int MeasurementVectorSizeType; + + /** Run-time type information (and related methods). */ + itkTypeMacro(DistanceMetric, FunctionBase); + + typedef Array< double > OriginType; + + /** Sets the origin point that will be used for the single point version + * Evaluate() function. This function is necessary part of implementing the + * Evaluate() interface. The argument of SetOrigin() must be of type + * DistanceMetric::OriginType, which in most cases will be different from the + * TVector type. This is necessary because often times the origin would be a + * mean, or a vector representative of a collection of vectors. */ + void SetOrigin(const OriginType& x); + itkGetConstReferenceMacro(Origin, OriginType); + + /** Gets the distance between the origin point and x. This function + * work with SetOrigin() function. */ + virtual double Evaluate(const MeasurementVectorType &x) const = 0; + + /** Gets the distance between x1 and x2. This method is used by + * KdTreeKMeans estimators. When the estimator is refactored, + * this method should be removed. Distance between two measurement + * vectors can be computed by setting one of them as an origin of + * the distane and using the Evaluate method with a single argument */ + virtual double Evaluate(const MeasurementVectorType &x1, + const MeasurementVectorType &x2) const = 0; + + /** Set method for the length of the measurement vector */ + virtual void SetMeasurementVectorSize( MeasurementVectorSizeType s ) + { + // Test whether the vector type is resizable or not + MeasurementVectorType m; + if( MeasurementVectorTraits::IsResizable( m ) ) + { + // then this is a resizable vector type + // + // if the new size is the same as the previou size, just return + if( s == this->m_MeasurementVectorSize ) + { + return; + } + else + { + this->m_MeasurementVectorSize = s; + this->Modified(); + } + } + else + { + // If this is a non-resizable vector type + MeasurementVectorType m3; + MeasurementVectorSizeType defaultLength = MeasurementVectorTraits::GetLength( m3 ); + // and the new length is different from the default one, then throw an exception + if( defaultLength != s ) + { + itkExceptionMacro("Attempting to change the measurement \ + vector size of a non-resizable vector type"); + } + } + } + + /** Get method for the length of the measurement vector */ + itkGetConstMacro( MeasurementVectorSize, MeasurementVectorSizeType ); + +protected: + DistanceMetric(); + virtual ~DistanceMetric() {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + + OriginType m_Origin; + + /** Number of components in the MeasurementVectorType */ + MeasurementVectorSizeType m_MeasurementVectorSize; +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkDistanceMetric.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkDistanceMetric.txx b/Utilities/ITK/Code/Review/Statistics/itkDistanceMetric.txx new file mode 100644 index 0000000000..4a53265dfb --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkDistanceMetric.txx @@ -0,0 +1,81 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDistanceMetric.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkDistanceMetric_txx +#define __itkDistanceMetric_txx + +#include "itkDistanceMetric.h" + +namespace itk { +namespace Statistics { + +template< class TVector > +DistanceMetric< TVector > +::DistanceMetric() +{ + //If the measurment vector type is non-resizable type, + //initialize the vector size to it. + MeasurementVectorType vector; + if( ! MeasurementVectorTraits::IsResizable( vector ) ) + { + MeasurementVectorSizeType defaultLength = + MeasurementVectorTraits::GetLength( vector ); + + this->m_MeasurementVectorSize = defaultLength; + this->m_Origin.SetSize( this->m_MeasurementVectorSize ); + } + else + { + //otherwise initialize it to zero + this->m_MeasurementVectorSize = 0; + } + m_Origin.Fill(0.0); +} + +template< class TVector > +void +DistanceMetric< TVector > +::SetOrigin(const OriginType &x) +{ + if( this->m_MeasurementVectorSize != 0 ) + { + if( x.Size() != this->m_MeasurementVectorSize ) + { + itkExceptionMacro( << "Size of the origin must be same as the length of" + << " each measurement vector."); + } + } + + this->m_MeasurementVectorSize = x.Size(); + m_Origin.SetSize( this->m_MeasurementVectorSize ); + m_Origin = x; + this->Modified(); +} + +template< class TVector > +void +DistanceMetric< TVector > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Origin: " << this->GetOrigin() << std::endl; + os << indent << "MeasurementVectorSize: " << this->GetMeasurementVectorSize() << std::endl; +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkDistanceToCentroidMembershipFunction.h b/Utilities/ITK/Code/Review/Statistics/itkDistanceToCentroidMembershipFunction.h new file mode 100644 index 0000000000..c09d2d6147 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkDistanceToCentroidMembershipFunction.h @@ -0,0 +1,103 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDistanceToCentroidMembershipFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkDistanceToCentroidMembershipFunction_h +#define __itkDistanceToCentroidMembershipFunction_h + +#include "itkMembershipFunctionBase.h" +#include "itkDistanceMetric.h" + +namespace itk { +namespace Statistics { + +/** \class DistanceToCentroidMembershipFunction + * \brief class represents DistanceToCentroid Density Function. + * + * This class keeps parameter to define DistanceToCentroid Density Function and has + * method to return the probability density + * of an instance. MeasurementVectorSize is the dimension of measurement + * space. + * double is type of measurement. + */ +template< class TVector > +class ITK_EXPORT DistanceToCentroidMembershipFunction : + public MembershipFunctionBase< TVector > +{ +public: + /** Standard class typedefs */ + typedef DistanceToCentroidMembershipFunction Self; + typedef MembershipFunctionBase< TVector > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Strandard macros */ + itkTypeMacro(DistanceToCentroidMembershipFunction, + MembershipFunctionBase); + itkNewMacro(Self); + + /** Typedef alias for the measurement vectors */ + typedef TVector MeasurementVectorType; + + /** Typedef to represent the length of measurement vectors */ + typedef typename Superclass::MeasurementVectorSizeType + MeasurementVectorSizeType; + + /** Set the length of each measurement vector. */ + virtual void SetMeasurementVectorSize( MeasurementVectorSizeType ); + + /** Type of the DistanceMetric to use */ + typedef DistanceMetric< MeasurementVectorType > DistanceMetricType; + typedef typename DistanceMetricType::Pointer DistanceMetricPointer; + + /** Set the DistanceMetric to be used when calling the Evaluate() method */ + itkSetObjectMacro( DistanceMetric, DistanceMetricType ); + itkGetConstObjectMacro( DistanceMetric, DistanceMetricType ); + + typedef typename DistanceMetricType::OriginType CentroidType; + + /** Method to set mean */ + void SetCentroid(const CentroidType & centroid); + + /** Method to get mean */ + const CentroidType & GetCentroid() const; + + /** + * Method to get probability of an instance. The return value is the + * value of the density function, not probability. */ + double Evaluate(const MeasurementVectorType &measurement) const; + + /** Return a copy of the current membership function */ + Pointer Clone(); + +protected: + DistanceToCentroidMembershipFunction(void); + virtual ~DistanceToCentroidMembershipFunction(void) {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + + DistanceMetricPointer m_DistanceMetric; + +}; + +} // end of namespace Statistics +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkDistanceToCentroidMembershipFunction.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkDistanceToCentroidMembershipFunction.txx b/Utilities/ITK/Code/Review/Statistics/itkDistanceToCentroidMembershipFunction.txx new file mode 100644 index 0000000000..326c16f6b9 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkDistanceToCentroidMembershipFunction.txx @@ -0,0 +1,97 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDistanceToCentroidMembershipFunction.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkDistanceToCentroidMembershipFunction_txx +#define __itkDistanceToCentroidMembershipFunction_txx + +#include "itkDistanceToCentroidMembershipFunction.h" +#include "itkEuclideanDistanceMetric.h" + +namespace itk { +namespace Statistics { + +template < class TVector > +DistanceToCentroidMembershipFunction< TVector > +::DistanceToCentroidMembershipFunction() +{ + // Initialize by default to an Euclidean distance. This default can be + // changed by calling SetDistanceMetric(). + this->m_DistanceMetric = EuclideanDistanceMetric<TVector>::New(); +} + +template < class TVector > +void +DistanceToCentroidMembershipFunction< TVector > +::SetCentroid(const CentroidType & centroid) +{ + this->m_DistanceMetric->SetOrigin( centroid ); + this->Modified(); +} + +template< class TVector > +void +DistanceToCentroidMembershipFunction< TVector > +::SetMeasurementVectorSize( MeasurementVectorSizeType s ) +{ + this->Superclass::SetMeasurementVectorSize( s ); + this->m_DistanceMetric->SetMeasurementVectorSize( s ); + this->Modified(); +} + +template < class TVector > +const typename DistanceToCentroidMembershipFunction< TVector >::CentroidType & +DistanceToCentroidMembershipFunction< TVector > +::GetCentroid() const +{ + return this->m_DistanceMetric->GetOrigin(); +} + +template < class TVector > +double +DistanceToCentroidMembershipFunction< TVector > +::Evaluate(const MeasurementVectorType &measurement) const +{ + return this->m_DistanceMetric->Evaluate( measurement ); +} + +template < class TVector > +typename DistanceToCentroidMembershipFunction< TVector >::Pointer +DistanceToCentroidMembershipFunction< TVector > +::Clone() +{ + Pointer membershipFunction = + DistanceToCentroidMembershipFunction<TVector>::New(); + membershipFunction->SetMeasurementVectorSize( this->GetMeasurementVectorSize() ); + membershipFunction->SetCentroid( this->GetCentroid() ); + + return membershipFunction; +} + + +template < class TVector > +void +DistanceToCentroidMembershipFunction< TVector > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << "Distance Metric: " << this->m_DistanceMetric.GetPointer() << std::endl; + +} + +} // end namespace Statistics +} // end of namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkEuclideanDistanceMetric.h b/Utilities/ITK/Code/Review/Statistics/itkEuclideanDistanceMetric.h new file mode 100644 index 0000000000..6ed353f399 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkEuclideanDistanceMetric.h @@ -0,0 +1,79 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkEuclideanDistanceMetric.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkEuclideanDistanceMetric_h +#define __itkEuclideanDistanceMetric_h + +#include "itkNumericTraits.h" +#include "itkDistanceMetric.h" +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +/** \class EuclideanDistanceMetric + * \brief Euclidean distance function. + * + * + */ +template< class TVector > +class ITK_EXPORT EuclideanDistanceMetric : + public DistanceMetric< TVector > +{ +public: + /** Standard "Self" typedef. */ + typedef EuclideanDistanceMetric Self; + typedef DistanceMetric< TVector > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename MeasurementVectorTraitsTypes<MeasurementVectorType>::ValueType ValueType; + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + + typedef typename Superclass::OriginType OriginType; + + /** Run-time type information (and related methods). */ + itkTypeMacro(EuclideanDistanceMetric, DistanceMetric); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Gets the distance between the origin and x */ + double Evaluate(const MeasurementVectorType &x) const; + + /** Gets the distance between x1 and x2 */ + double Evaluate(const MeasurementVectorType &x1, const MeasurementVectorType &x2) const; + + /** Gets the cooridnate distance between a and b. NOTE: a and b + * should be type of component. This method is used by + * KdTreeKMeans estimators. When the estimator is refactored, + * this method should be removed. */ + double Evaluate(const ValueType &a, const ValueType &b) const; + +protected: + EuclideanDistanceMetric() {} + virtual ~EuclideanDistanceMetric() {} +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkEuclideanDistanceMetric.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkEuclideanDistanceMetric.txx b/Utilities/ITK/Code/Review/Statistics/itkEuclideanDistanceMetric.txx new file mode 100644 index 0000000000..0a3a403b2f --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkEuclideanDistanceMetric.txx @@ -0,0 +1,82 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkEuclideanDistanceMetric.txx,v $ + Language: C++ + Date: $Date: 2009-05-22 19:26:30 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkEuclideanDistanceMetric_txx +#define __itkEuclideanDistanceMetric_txx + + +namespace itk { +namespace Statistics { + +template< class TVector > +inline double +EuclideanDistanceMetric< TVector > +::Evaluate(const MeasurementVectorType &x) const +{ + MeasurementVectorSizeType + measurementVectorSize = this->GetMeasurementVectorSize(); + if(measurementVectorSize == 0) + { + itkExceptionMacro( << "Please set the MeasurementVectorSize first" ); + } + MeasurementVectorTraits::Assert( this->GetOrigin(), measurementVectorSize, + "EuclideanDistanceMetric::Evaluate Origin and input vector have different lengths"); + + double temp, distance = NumericTraits< double >::Zero; + + for(unsigned int i = 0; i < measurementVectorSize; i++) + { + temp = this->GetOrigin()[i] - x[i]; + distance += temp * temp; + } + + return vcl_sqrt(distance); +} + +template< class TVector > +inline double +EuclideanDistanceMetric< TVector > +::Evaluate(const MeasurementVectorType &x1, const MeasurementVectorType &x2) const +{ + MeasurementVectorSizeType measurementVectorSize = MeasurementVectorTraits::GetLength( x1 ); + if (measurementVectorSize != MeasurementVectorTraits::GetLength(x2)) + { + itkExceptionMacro( << "The two measurement vectors have unequal size" ); + } + + double temp, distance = NumericTraits< double >::Zero; + for(unsigned int i = 0; i < measurementVectorSize; i++) + { + temp = x1[i] - x2[i]; + distance += temp * temp; + } + + return vcl_sqrt(distance); +} + +template< class TVector > +inline double +EuclideanDistanceMetric< TVector > +::Evaluate(const ValueType &a, const ValueType &b) const +{ + double temp = a - b; + return vcl_sqrt(temp * temp); +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkEuclideanSquareDistanceMetric.h b/Utilities/ITK/Code/Review/Statistics/itkEuclideanSquareDistanceMetric.h new file mode 100644 index 0000000000..54fb0ac398 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkEuclideanSquareDistanceMetric.h @@ -0,0 +1,72 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkEuclideanSquareDistanceMetric.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkEuclideanSquareDistanceMetric_h +#define __itkEuclideanSquareDistanceMetric_h + +#include "itkNumericTraits.h" +#include "itkDistanceMetric.h" +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +/** \class EuclideanSquareDistanceMetric + * \brief Computes Euclidean distance between origin and given measurement vector. + * + * \sa DistanceMetric + * \sa EuclideanDistanceMetric + * \sa ManhattanDistanceMetric + */ +template< class TVector > +class ITK_EXPORT EuclideanSquareDistanceMetric : + public DistanceMetric< TVector > +{ +public: + /** Standard "Self" typedef. */ + typedef EuclideanSquareDistanceMetric Self; + typedef DistanceMetric< TVector > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + + /** Run-time type information (and related methods). */ + itkTypeMacro(EuclideanSquareDistanceMetric, DistanceMetric); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Gets the distance between the origin and x */ + double Evaluate(const MeasurementVectorType &x) const; + + /** Gets the distance between x1 and x2 */ + double Evaluate(const MeasurementVectorType &x1, const MeasurementVectorType &x2) const; + +protected: + EuclideanSquareDistanceMetric() {} + virtual ~EuclideanSquareDistanceMetric() {} +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkEuclideanSquareDistanceMetric.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkEuclideanSquareDistanceMetric.txx b/Utilities/ITK/Code/Review/Statistics/itkEuclideanSquareDistanceMetric.txx new file mode 100644 index 0000000000..5309cfb44e --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkEuclideanSquareDistanceMetric.txx @@ -0,0 +1,74 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkEuclideanSquareDistanceMetric.txx,v $ + Language: C++ + Date: $Date: 2009-05-23 04:17:05 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkEuclideanSquareDistanceMetric_txx +#define __itkEuclideanSquareDistanceMetric_txx + + +namespace itk { +namespace Statistics { + +template< class TVector > +inline double +EuclideanSquareDistanceMetric< TVector > +::Evaluate(const MeasurementVectorType &x) const +{ + MeasurementVectorSizeType + measurementVectorSize = this->GetMeasurementVectorSize(); + if(measurementVectorSize == 0) + { + itkExceptionMacro( << "Please set the MeasurementVectorSize first" ); + } + MeasurementVectorTraits::Assert( this->GetOrigin(),measurementVectorSize, + "EuclideanSquareDistanceMetric::Evaluate Origin and input vector have different lengths"); + + double temp, distance = NumericTraits< double >::Zero; + + for(unsigned int i = 0; i < measurementVectorSize; i++) + { + temp = this->GetOrigin()[i] - x[i]; + distance += temp * temp; + } + + return distance; +} + +template< class TVector > +inline double +EuclideanSquareDistanceMetric< TVector > +::Evaluate(const MeasurementVectorType &x1, const MeasurementVectorType &x2) const +{ + MeasurementVectorSizeType measurementVectorSize = MeasurementVectorTraits::GetLength( x1 ); + if (measurementVectorSize != MeasurementVectorTraits::GetLength(x2)) + { + itkExceptionMacro( << "EuclideanSquareDistanceMetric:: The two measurement vectors have unequal size" ); + } + + double temp, distance = NumericTraits< double >::Zero; + for(unsigned int i = 0; i < measurementVectorSize; i++) + { + temp = x1[i] - x2[i]; + distance += temp * temp; + } + + return distance; +} + + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkExpectationMaximizationMixtureModelEstimator.h b/Utilities/ITK/Code/Review/Statistics/itkExpectationMaximizationMixtureModelEstimator.h new file mode 100644 index 0000000000..72f3e30f12 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkExpectationMaximizationMixtureModelEstimator.h @@ -0,0 +1,200 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkExpectationMaximizationMixtureModelEstimator.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkExpectationMaximizationMixtureModelEstimator_h +#define __itkExpectationMaximizationMixtureModelEstimator_h + +#include "itkMembershipFunctionBase.h" +#include "itkMixtureModelComponentBase.h" +#include "itkGaussianMembershipFunction.h" + +namespace itk { +namespace Statistics { + +/** \class ExpectationMaximizationMixtureModelEstimator + * \brief This class generates the parameter estimates for a mixture + * model using expectation maximization strategy. + * + * The first template argument is the type of the target sample + * data. This estimator expects one or more mixture model component + * objects of the classes derived from the + * MixtureModelComponentBase. The actual component (or module) + * parameters are updated by each component. Users can think this + * class as a strategy or a integration point for the EM + * procedure. The initial proportion (SetInitialProportions), the + * input sample (SetSample), the mixture model components + * (AddComponent), and the maximum iteration (SetMaximumIteration) are + * required. The EM procedure terminates when the current iteration + * reaches the maximum iteration or the model parameters converge. + * + * <b>Recent API changes:</b> + * The static const macro to get the length of a measurement vector, + * \c MeasurementVectorSize has been removed to allow the length of a measurement + * vector to be specified at run time. It is now obtained at run time from the + * sample set as input. Please use the function + * GetMeasurementVectorSize() to get the length. + * + * \sa MixtureModelComponentBase, GaussianMixtureModelComponent + */ + +template< class TSample > +class ITK_EXPORT ExpectationMaximizationMixtureModelEstimator : public Object +{ +public: + /** Standard class typedef */ + typedef ExpectationMaximizationMixtureModelEstimator Self; + typedef Object Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Standard macros */ + itkTypeMacro(ExpectationMaximizationMixtureModelEstimator, + Object); + itkNewMacro(Self); + + /** TSample template argument related typedefs */ + typedef TSample SampleType; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + + + /** Typedef requried to generate dataobject decorated output that can + * be plugged into SampleClassifierFilter */ + typedef GaussianMembershipFunction< MeasurementVectorType > + GaussianMembershipFunctionType; + + typedef typename GaussianMembershipFunctionType::Pointer + GaussianMembershipFunctionPointer; + + typedef MembershipFunctionBase< MeasurementVectorType > MembershipFunctionType; + typedef typename MembershipFunctionType::ConstPointer MembershipFunctionPointer; + typedef std::vector< MembershipFunctionPointer > MembershipFunctionVectorType; + typedef SimpleDataObjectDecorator< + MembershipFunctionVectorType > MembershipFunctionVectorObjectType; + typedef typename + MembershipFunctionVectorObjectType::Pointer MembershipFunctionVectorObjectPointer; + + /** Type of the mixture model component base class */ + typedef MixtureModelComponentBase< TSample > ComponentType; + + /** Type of the component pointer storage */ + typedef std::vector< ComponentType* > ComponentVectorType; + + /** Type of the membership function base class */ + typedef MembershipFunctionBase< MeasurementVectorType > + ComponentMembershipFunctionType; + + /** Type of the array of the proportion values */ + typedef Array< double > ProportionVectorType; + + /** Sets the target data that will be classified by this */ + void SetSample(const TSample* sample); + + /** Returns the target data */ + const TSample* GetSample() const; + + /** Set/Gets the initial proportion values. The size of proportion + * vector should be same as the number of component (or classes) */ + void SetInitialProportions(ProportionVectorType &propotion); + const ProportionVectorType& GetInitialProportions() const; + + /** Gets the result proportion values */ + const ProportionVectorType& GetProportions() const; + + /** typedef for decorated array of proportion */ + typedef SimpleDataObjectDecorator< + ProportionVectorType> MembershipFunctionsWeightsArrayObjectType; + typedef typename + MembershipFunctionsWeightsArrayObjectType::Pointer MembershipFunctionsWeightsArrayPointer; + + /** Get method for data decorated Membership functions weights array */ + const MembershipFunctionsWeightsArrayObjectType * GetMembershipFunctionsWeightsArray() const; + + /** Set/Gets the maximum number of iterations. When the optimization + * process reaches the maximum number of interations, even if the + * class parameters aren't converged, the optimization process + * stops. */ + void SetMaximumIteration(int numberOfIterations); + int GetMaximumIteration() const; + + /** Gets the current iteration. */ + int GetCurrentIteration() + { + return m_CurrentIteration; + } + + /** Adds a new component (or class). */ + int AddComponent(ComponentType* component); + + /** Gets the total number of classes currently plugged in. */ + unsigned int GetNumberOfComponents() const; + + /** Runs the optimization process. */ + void Update(); + + /** Termination status after running optimization */ + enum TERMINATION_CODE { CONVERGED = 0, NOT_CONVERGED = 1 }; + + /** Gets the termination status */ + TERMINATION_CODE GetTerminationCode() const; + + /** Gets the membership function specified by componentIndex + argument. */ + ComponentMembershipFunctionType* GetComponentMembershipFunction(int componentIndex) const; + + /** Output Membership function vector containing the membership functions with + * the final optimized paramters */ + const MembershipFunctionVectorObjectType * GetOutput() const; + +protected: + ExpectationMaximizationMixtureModelEstimator(); + virtual ~ExpectationMaximizationMixtureModelEstimator() {} + void PrintSelf(std::ostream& os, Indent indent) const; + + bool CalculateDensities(); + double CalculateExpectation() const; + bool UpdateComponentParameters(); + bool UpdateProportions(); + + /** Starts the estimation process */ + void GenerateData(); + +private: + /** Target data sample pointer*/ + const TSample* m_Sample; + + int m_MaxIteration; + int m_CurrentIteration; + + TERMINATION_CODE m_TerminationCode; + ComponentVectorType m_ComponentVector; + ProportionVectorType m_InitialProportions; + ProportionVectorType m_Proportions; + + MembershipFunctionVectorObjectPointer m_MembershipFunctionsObject; + MembershipFunctionsWeightsArrayPointer m_MembershipFunctionsWeightArrayObject; +}; // end of class + + +} // end of namespace Statistics +} // end of namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkExpectationMaximizationMixtureModelEstimator.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkExpectationMaximizationMixtureModelEstimator.txx b/Utilities/ITK/Code/Review/Statistics/itkExpectationMaximizationMixtureModelEstimator.txx new file mode 100644 index 0000000000..378e729587 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkExpectationMaximizationMixtureModelEstimator.txx @@ -0,0 +1,431 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkExpectationMaximizationMixtureModelEstimator.txx,v $ + Language: C++ + Date: $Date: 2009-05-12 14:27:58 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkExpectationMaximizationMixtureModelEstimator_txx +#define __itkExpectationMaximizationMixtureModelEstimator_txx + +#include "itkExpectationMaximizationMixtureModelEstimator.h" +#include "itkNumericTraits.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +ExpectationMaximizationMixtureModelEstimator< TSample > +::ExpectationMaximizationMixtureModelEstimator() +{ + m_TerminationCode = NOT_CONVERGED; + + m_MembershipFunctionsObject = MembershipFunctionVectorObjectType::New(); + m_MembershipFunctionsWeightArrayObject = + MembershipFunctionsWeightsArrayObjectType::New(); + m_Sample = 0; +} + +template< class TSample > +void +ExpectationMaximizationMixtureModelEstimator< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Maximum Iteration: " + << this->GetMaximumIteration() << std::endl; + os << indent << "Sample: " + << this->GetSample() << std::endl; + os << indent << "Number Of Components: " + << this->GetNumberOfComponents() << std::endl; + for (unsigned int i = 0; i < this->GetNumberOfComponents(); i++) + { + os << indent << "Component Membership Function[" << i << "]: " + << this->GetComponentMembershipFunction(i) << std::endl; + } + os << indent << "Termination Code: " + << this->GetTerminationCode() << std::endl; + os << indent << "Initial Proportions: " + << this->GetInitialProportions() << std::endl; + os << indent << "Proportions: " + << this->GetProportions() << std::endl; + os << indent << "Calculated Expectation: " << this->CalculateExpectation() << std::endl; +} + + +template< class TSample > +void +ExpectationMaximizationMixtureModelEstimator< TSample > +::SetMaximumIteration(int numberOfIterations) +{ + m_MaxIteration = numberOfIterations; +} + +template< class TSample > +int +ExpectationMaximizationMixtureModelEstimator< TSample > +::GetMaximumIteration() const +{ + return m_MaxIteration; +} + +template< class TSample > +void +ExpectationMaximizationMixtureModelEstimator< TSample > +::SetInitialProportions(ProportionVectorType &proportions) +{ + m_InitialProportions = proportions; +} + +template< class TSample > +const typename ExpectationMaximizationMixtureModelEstimator< TSample >::ProportionVectorType& +ExpectationMaximizationMixtureModelEstimator< TSample > +::GetInitialProportions() const +{ + return m_InitialProportions; +} + +template< class TSample > +const typename ExpectationMaximizationMixtureModelEstimator< TSample >::ProportionVectorType& +ExpectationMaximizationMixtureModelEstimator< TSample > +::GetProportions() const +{ + return m_Proportions; +} + +template< class TSample > +void +ExpectationMaximizationMixtureModelEstimator< TSample > +::SetSample(const TSample* sample) +{ + m_Sample = sample; +} + +template< class TSample > +const TSample * +ExpectationMaximizationMixtureModelEstimator< TSample > +::GetSample() const +{ + return m_Sample; +} + + +template< class TSample > +int +ExpectationMaximizationMixtureModelEstimator< TSample > +::AddComponent(ComponentType* component) +{ + m_ComponentVector.push_back(component); + return static_cast<int>( m_ComponentVector.size() ); +} + +template< class TSample > +unsigned int +ExpectationMaximizationMixtureModelEstimator< TSample > +::GetNumberOfComponents() const +{ + return m_ComponentVector.size(); +} + +template< class TSample > +typename ExpectationMaximizationMixtureModelEstimator< TSample >::TERMINATION_CODE +ExpectationMaximizationMixtureModelEstimator< TSample > +::GetTerminationCode() const +{ + return m_TerminationCode; +} + +template< class TSample > +typename ExpectationMaximizationMixtureModelEstimator< TSample >::ComponentMembershipFunctionType* +ExpectationMaximizationMixtureModelEstimator< TSample > +::GetComponentMembershipFunction(int componentIndex) const +{ + return (m_ComponentVector[componentIndex])->GetMembershipFunction(); +} + + +template< class TSample > +bool +ExpectationMaximizationMixtureModelEstimator< TSample > +::CalculateDensities() +{ + bool componentModified = false; + + for (unsigned int i = 0; i < m_ComponentVector.size(); i++) + { + if ( (m_ComponentVector[i])->AreParametersModified() ) + { + componentModified = true; + } + } + + if (!componentModified) + { + return false; + } + + double temp; + int numberOfComponents = static_cast<int>( m_ComponentVector.size() ); + std::vector< double > tempWeights(numberOfComponents); + + typename TSample::ConstIterator iter = m_Sample->Begin(); + typename TSample::ConstIterator last = m_Sample->End(); + + int componentIndex; + + typedef typename TSample::AbsoluteFrequencyType FrequencyType; + FrequencyType frequency; + FrequencyType zeroFrequency = NumericTraits< FrequencyType >::Zero; + typename TSample::MeasurementVectorType mvector; + double density; + double densitySum; + double minDouble = NumericTraits< double >::NonpositiveMin(); + + long measurementVectorIndex = 0; + + while (iter != last) + { + mvector = iter.GetMeasurementVector(); + frequency = iter.GetFrequency(); + densitySum = 0.0; + if ( frequency > zeroFrequency ) + { + for (componentIndex = 0; componentIndex < numberOfComponents; + componentIndex++) + { + density = m_Proportions[componentIndex] * + m_ComponentVector[componentIndex]->Evaluate(mvector); + tempWeights[componentIndex] = density; + densitySum += density; + } + + for (componentIndex = 0; componentIndex < numberOfComponents; + componentIndex++) + { + temp = tempWeights[componentIndex]; + temp /= densitySum; + m_ComponentVector[componentIndex]->SetWeight(measurementVectorIndex, + temp); + } + } + else + { + for (componentIndex = 0; componentIndex < numberOfComponents; + componentIndex++) + { + m_ComponentVector[componentIndex]->SetWeight(measurementVectorIndex, + minDouble); + } + } + + ++iter; + ++measurementVectorIndex; + } + + return true; +} + +template< class TSample > +double +ExpectationMaximizationMixtureModelEstimator< TSample > +::CalculateExpectation() const +{ + double sum = 0.0; + if (m_Sample) + { + unsigned int componentIndex, measurementVectorIndex; + unsigned long size = m_Sample->Size(); + double logProportion; + double temp; + for (componentIndex = 0; componentIndex < m_ComponentVector.size(); + componentIndex++) + { + logProportion = vcl_log(m_Proportions[componentIndex]); + for (measurementVectorIndex = 0; measurementVectorIndex < size; + measurementVectorIndex++) + { + temp = m_ComponentVector[componentIndex]-> + GetWeight(measurementVectorIndex); + sum += temp * ( logProportion + + vcl_log(m_ComponentVector[componentIndex]-> + GetWeight(measurementVectorIndex) ) ); + } + } + } + return sum; +} + +template< class TSample > +bool +ExpectationMaximizationMixtureModelEstimator< TSample > +::UpdateComponentParameters() +{ + unsigned int componentIndex; + bool updated = false; + ComponentType* component; + + for (componentIndex = 0; componentIndex < m_ComponentVector.size(); + componentIndex++) + { + component = m_ComponentVector[componentIndex]; + component->Update(); + if (component->AreParametersModified()) + { + updated = true; + } + } + + return updated; +} + +template< class TSample > +bool +ExpectationMaximizationMixtureModelEstimator< TSample > +::UpdateProportions() +{ + int numberOfComponents = m_ComponentVector.size(); + long sampleSize = m_Sample->Size(); + double totalFrequency = (double) (m_Sample->GetTotalFrequency()); + long i, j; + double tempSum; + bool updated = false; + + for (i = 0; i < numberOfComponents; i++) + { + tempSum = 0.0; + for (j = 0; j < sampleSize; j++) + { + tempSum += (m_ComponentVector[i]->GetWeight(j) * + m_Sample->GetFrequency(j)); + } + + tempSum /= totalFrequency; + + if (tempSum != m_Proportions[i]) + { + m_Proportions[i] = tempSum; + updated = true; + } + } + + return updated; +} + +template< class TSample > +void +ExpectationMaximizationMixtureModelEstimator< TSample > +::GenerateData() +{ + m_Proportions = m_InitialProportions; + + int iteration = 0; + m_CurrentIteration = 0; + while (iteration < m_MaxIteration) + { + m_CurrentIteration = iteration; + if (this->CalculateDensities()) + { + this->UpdateComponentParameters(); + this->UpdateProportions(); + } + else + { + m_TerminationCode = CONVERGED; + break; + } + ++iteration; + } + + m_TerminationCode = NOT_CONVERGED; +} + +template< class TSample > +const typename ExpectationMaximizationMixtureModelEstimator< TSample >::MembershipFunctionVectorObjectType * +ExpectationMaximizationMixtureModelEstimator< TSample > +::GetOutput() const +{ + + unsigned int numberOfComponents = m_ComponentVector.size(); + MembershipFunctionVectorType & membershipFunctionsVector = m_MembershipFunctionsObject->Get(); + + typename SampleType::MeasurementVectorSizeType measurementVectorSize = + m_Sample->GetMeasurementVectorSize(); + + typename GaussianMembershipFunctionType::MeanType mean; + MeasurementVectorTraits::SetLength( mean, measurementVectorSize); + + typename GaussianMembershipFunctionType::CovarianceType covariance; + covariance.SetSize(measurementVectorSize,measurementVectorSize); + + typename ComponentType::ParametersType parameters; + + for( unsigned int i=0; i < numberOfComponents; i++ ) + { + parameters = m_ComponentVector[i]->GetFullParameters(); + typename GaussianMembershipFunctionType::Pointer membershipFunction = + GaussianMembershipFunctionType::New(); + membershipFunction->SetMeasurementVectorSize( measurementVectorSize ); + unsigned int parameterIndex = 0; + for(unsigned int j=0; j < measurementVectorSize; j++) + { + mean[j] = parameters[j]; + ++parameterIndex; + } + + for ( unsigned int ii = 0; ii < measurementVectorSize; ii++ ) + { + for ( unsigned int jj = 0; jj < measurementVectorSize; jj++ ) + { + covariance.GetVnlMatrix().put(ii, jj, parameters[parameterIndex]); + ++parameterIndex; + } + } + + membershipFunction->SetMean( mean ); + membershipFunction->SetCovariance( covariance ); + membershipFunctionsVector.push_back( membershipFunction.GetPointer() ); + } + + return static_cast< const MembershipFunctionVectorObjectType*>(m_MembershipFunctionsObject); +} + +template< class TSample > +const typename ExpectationMaximizationMixtureModelEstimator< TSample +>::MembershipFunctionsWeightsArrayObjectType * +ExpectationMaximizationMixtureModelEstimator< TSample > +::GetMembershipFunctionsWeightsArray() const +{ + + unsigned int numberOfComponents = m_ComponentVector.size(); + ProportionVectorType & membershipFunctionsWeightVector = + m_MembershipFunctionsWeightArrayObject->Get(); + membershipFunctionsWeightVector.SetSize( numberOfComponents ); + for( unsigned int i=0; i < numberOfComponents; i++ ) + { + membershipFunctionsWeightVector[i] = m_Proportions[i]; + } + + return static_cast< const MembershipFunctionsWeightsArrayObjectType*>(m_MembershipFunctionsWeightArrayObject); +} + +template< class TSample > +void +ExpectationMaximizationMixtureModelEstimator< TSample > +::Update() +{ + this->GenerateData(); +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.cxx b/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.cxx new file mode 100644 index 0000000000..b4e27bb4df --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.cxx @@ -0,0 +1,525 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGaussianDistribution.cxx,v $ + Language: C++ + Date: $Date: 2009-05-10 18:27:08 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "itkGaussianDistribution.h" +#include "itkNumericTraits.h" +#include "vnl/vnl_math.h" +#include "vnl/vnl_erf.h" + +namespace itk { +namespace Statistics { + +GaussianDistribution +::GaussianDistribution() +{ + m_Parameters = ParametersType(2); + m_Parameters[0] = 0.0; + m_Parameters[1] = 1.0; +} + + +double +GaussianDistribution +::GetMean() const +{ + if (m_Parameters.GetSize() != 2) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << m_Parameters.size() + << " parameters."); + } + return m_Parameters[0]; +} + +void +GaussianDistribution +::SetMean(double mean) +{ + bool modified=false; + + if (m_Parameters.GetSize() > 0) + { + if (m_Parameters[0] != mean) + { + modified = true; + } + } + + if (m_Parameters.GetSize() != 2) + { + bool cache = false; + double t = 1.0; + + // cache current variance if there is one + if (m_Parameters.GetSize() > 1) + { + t = m_Parameters[1]; + cache = true; + } + + // create a parameters array of the right length + m_Parameters = ParametersType(2); + + // reapply variance if there was one, otherwise use a default value + if (cache) + { + m_Parameters[1] = t; + } + else + { + m_Parameters[1] = 1.0; + } + + modified = true; + } + + m_Parameters[0] = mean; + + if (modified) + { + this->Modified(); + } +} + +double +GaussianDistribution +::GetVariance() const +{ + if (m_Parameters.GetSize() != 2) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << m_Parameters.size() + << " parameters."); + } + return m_Parameters[1]; +} + +void +GaussianDistribution +::SetVariance(double variance) +{ + bool modified = false; + + if (m_Parameters.GetSize() > 1) + { + if (m_Parameters[1] != variance) + { + modified = true; + } + } + + if (m_Parameters.GetSize() != 2) + { + bool cache = false; + double t = 0.0; + + // cache current mean if there is one + if (m_Parameters.GetSize() > 0) + { + t = m_Parameters[0]; + cache = true; + } + + // create a parameters array of the right length + m_Parameters = ParametersType(2); + + // reapply mean if there was one, otherwise use a default value + if (cache) + { + m_Parameters[0] = t; + } + else + { + m_Parameters[0] = 0.0; + } + + modified = true; + } + + m_Parameters[1] = variance; + + if (modified) + { + this->Modified(); + } +} + + +double +GaussianDistribution +::PDF(double x) +{ + static const double oneonsqrttwopi = 1.0 / sqrt( 2.0 * vnl_math::pi ); + + return oneonsqrttwopi * vcl_exp(-0.5*x*x); +} + +double +GaussianDistribution +::PDF(double x, double mean, double variance) +{ + static const double oneonsqrttwopi = 1.0 / sqrt( 2.0 * vnl_math::pi ); + + double xminusmean = x - mean; + + return (oneonsqrttwopi / sqrt(variance)) + * vcl_exp(-0.5*xminusmean*xminusmean / variance); +} + +double +GaussianDistribution +::PDF(double x, const ParametersType& p) +{ + // verify the parameter vector length + if (p.GetSize() == 2) + { + return PDF(x, p[0], p[1]); + } + else + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << p.size() + << " parameters."); + } +} + +double +GaussianDistribution +::CDF(double x) +{ + return 0.5 * (vnl_erf(vnl_math::sqrt1_2 * x) + 1.0); +} + + +double +GaussianDistribution +::CDF(double x, double mean, double variance) +{ + // convert to zero mean unit variance + double u = (x - mean) / sqrt(variance); + + return 0.5 * (vnl_erf(vnl_math::sqrt1_2 * u) + 1.0); +} + + +double +GaussianDistribution +::CDF(double x, const ParametersType& p) +{ + if (p.GetSize() != 2) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << p.size() + << " parameters."); + } + return GaussianDistribution::CDF(x, p[0], p[1]); +} + +double +GaussianDistribution +::InverseCDF(double p) +{ + double dp , dx , dt , ddq , dq; + int newt; + + dp = (p <= 0.5) ? (p) : (1.0-p); /* make between 0 and 0.5 */ + + // if original value is invalid, return +infinity or -infinity + // changed from original code to reflect the fact that the + // the inverse of P(x) not Q(x) is desired. + // + // Original line: used for inverse of Q(x) + // if( dp <= 0.0 ){ dx = 13.0; return ( (p <= 0.5) ? (dx) : (-dx) ); } + + // replaced with this if construct for the inverse of P(x) + if (p <= 0.0) + { + return itk::NumericTraits<double>::NonpositiveMin(); + } + else if (p >= 1.0) + { + return itk::NumericTraits<double>::max(); + } + + + /** Step 1: use 26.2.23 from Abramowitz and Stegun */ + + dt = sqrt( -2.0 * log(dp) ); + dx = dt + - ((.010328e+0*dt + .802853e+0)*dt + 2.515517e+0) + /(((.001308e+0*dt + .189269e+0)*dt + 1.432788e+0)*dt + 1.e+0); + + /** Step 2: do 3 Newton steps to improve this */ + + for( newt=0; newt < 3; newt++ ) + { + dq = 0.5e+0 * vnl_erfc( dx / 1.414213562373095e+0 ) - dp; + ddq = vcl_exp( -0.5e+0 * dx * dx ) / 2.506628274631000e+0; + dx = dx + dq / ddq; + } + + // original line when computing the inverse of Q(x) + // return ( (p <= 0.5) ? (dx) : (-dx) ); /* return with correct sign */ + // + // Note that P(-x) = Q(x), so whatever x was calculated for Q(x) = p, + // we simply need to return the negative of x to get P(xp) = p. + // + dx = ( (p <= 0.5) ? (-dx) : (dx) ); // return with correct sign + + return dx; +} + + +double +GaussianDistribution +::InverseCDF(double p, double mean, double variance) +{ + double x = GaussianDistribution::InverseCDF(p); + + if (x == itk::NumericTraits<double>::NonpositiveMin()) + { + return x; + } + else if (x == itk::NumericTraits<double>::max()) + { + return x; + } + else + { + // apply the mean and variance to provide the value for the + // prescribed Gaussian + x = x*sqrt(variance) + mean; + return x; + } +} + +double +GaussianDistribution +::InverseCDF(double p, const ParametersType& params) +{ + + if (params.GetSize() != 2) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << params.size() + << " parameters."); + } + return GaussianDistribution::InverseCDF(p, params[0], params[1]); +} + +double +GaussianDistribution +::EvaluatePDF(double x) const +{ + if (m_Parameters.GetSize() == 2) + { + if (m_Parameters[0] == 0.0 && m_Parameters[1] == 1.0) + { + return GaussianDistribution::PDF(x); + } + + return GaussianDistribution::PDF(x, m_Parameters[0], m_Parameters[1]); + } + else + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << m_Parameters.size() + << " parameters."); + } +} + +double +GaussianDistribution +::EvaluatePDF(double x, const ParametersType&p) const +{ + if (p.GetSize() == 2) + { + if (p[0] == 0.0 && p[1] == 1.0) + { + return GaussianDistribution::PDF(x); + } + + return GaussianDistribution::PDF(x, p[0], p[1]); + } + else + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << p.size() + << " parameters."); + } +} + +double +GaussianDistribution +::EvaluatePDF(double x, double mean, double variance) const +{ + if (mean == 0.0 && variance == 1.0) + { + return GaussianDistribution::PDF(x); + } + + return GaussianDistribution::PDF(x, mean, variance); +} + + +double +GaussianDistribution +::EvaluateCDF(double x) const +{ + if (m_Parameters.GetSize() == 2) + { + if (m_Parameters[0] == 0.0 && m_Parameters[1] == 1.0) + { + return GaussianDistribution::CDF(x); + } + + return GaussianDistribution::CDF(x, m_Parameters[0], m_Parameters[1]); + } + else + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << m_Parameters.size() + << " parameters."); + } +} + +double +GaussianDistribution +::EvaluateCDF(double x, const ParametersType& p) const +{ + if (p.GetSize() == 2) + { + if (p[0] == 0.0 && p[1] == 1.0) + { + return GaussianDistribution::CDF(x); + } + + return GaussianDistribution::CDF(x, p[0], p[1]); + } + else + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << p.size() + << " parameters."); + } +} + +double +GaussianDistribution +::EvaluateCDF(double x, double mean, double variance) const +{ + if (mean == 0.0 && variance == 1.0) + { + return GaussianDistribution::CDF(x); + } + + return GaussianDistribution::CDF(x, mean, variance); +} + + +double +GaussianDistribution +::EvaluateInverseCDF(double p) const +{ + if (m_Parameters.GetSize() == 2) + { + if (m_Parameters[0] == 0.0 && m_Parameters[1] == 1.0) + { + return GaussianDistribution::InverseCDF(p); + } + + return GaussianDistribution::InverseCDF(p,m_Parameters[0],m_Parameters[1]); + } + else + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << m_Parameters.size() + << " parameters."); + } +} + +double +GaussianDistribution +::EvaluateInverseCDF(double p, const ParametersType& params) const +{ + if (params.GetSize() == 2) + { + if (params[0] == 0.0 && params[1] == 1.0) + { + return GaussianDistribution::InverseCDF(p); + } + + return GaussianDistribution::InverseCDF(p,params[0],params[1]); + } + else + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 2 parameters, but got " + << params.size() + << " parameters."); + } +} + +double +GaussianDistribution +::EvaluateInverseCDF(double p, double mean, double variance) const +{ + if (mean == 0.0 && variance == 1.0) + { + return GaussianDistribution::InverseCDF(p); + } + + return GaussianDistribution::InverseCDF(p,mean,variance); +} + +void +GaussianDistribution +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + if (m_Parameters.GetSize() > 0) + { + os << indent << "Mean: " << m_Parameters[0] << std::endl; + } + else + { + os << indent << "Mean: (unknown)" << std::endl; + } + + if (m_Parameters.GetSize() > 1) + { + os << indent << "Variance: " << m_Parameters[1] << std::endl; + } + else + { + os << indent << "Variance: (unknown)" << std::endl; + } +} + +} // end of namespace Statistics +} // end namespace itk diff --git a/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.h b/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.h new file mode 100644 index 0000000000..8d717748b4 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.h @@ -0,0 +1,240 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGaussianDistribution.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkGaussianDistribution_h +#define __itkGaussianDistribution_h + +#include "itkProbabilityDistribution.h" + +namespace itk { +namespace Statistics { + +/** \class GaussianDistribution + * \brief GaussianDistribution class defines the interface for a + * univariate Gaussian distribution (pdfs, cdfs, etc.). + * + * GaussianDistribution provides access to the probability density + * function (pdf), the cumulative distribution function (cdf), and the + * inverse cumulative distribution function for a Gaussian distribution. + * + * The EvaluatePDF(), EvaluateCDF, EvaluateInverseCDF() methods are + * all virtual, allowing algorithms to be written with an abstract + * interface to a distribution (with said distribution provided to the + * algorithm at run-time). Static methods, not requiring an instance + * of the distribution, are also provided. The static methods allow + * for optimized access to distributions when the distribution is + * known a priori to the algorithm. + * + * GaussianDistributions are univariate. Multivariate versions may + * be provided under a separate superclass (since the parameters to the + * pdf and cdf would have to be vectors not scalars). + * + * GaussianDistributions can be used for Z-score statistical tests. + * + * \note This work is part of the National Alliance for Medical Image + * Computing (NAMIC), funded by the National Institutes of Health + * through the NIH Roadmap for Medical Research, Grant U54 EB005149. + * Information on the National Centers for Biomedical Computing + * can be obtained from http://nihroadmap.nih.gov/bioinformatics. + */ +class ITK_EXPORT GaussianDistribution : + public ProbabilityDistribution +{ +public: + /** Standard class typedefs */ + typedef GaussianDistribution Self; + typedef ProbabilityDistribution Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Strandard macros */ + itkTypeMacro(GaussianDistribution, ProbabilityDistribution); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Return the number of parameters. For a univariate Gaussian, + * this is 2 (mean, variance). */ + virtual unsigned long GetNumberOfParameters() const { return 2; } + + /** Evaluate the probability density function (pdf). The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluatePDF(double x) const; + + /** Evaluate the probability density function (pdf). The parameters + * for the distribution are passed as a parameters vector. The + * ordering of the parameters is (mean, variance). */ + virtual double EvaluatePDF(double x, const ParametersType&) const; + + /** Evaluate the probability density function (pdf). The parameters + * of the distribution are passed as separate parameters. */ + virtual double EvaluatePDF(double x, double mean, double variance) const; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluateCDF(double x) const; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * for the distribution are passed as a parameters vector. The + * ordering of the parameters is (mean, variance). */ + virtual double EvaluateCDF(double x, const ParametersType&) const; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * of the distribution are passed as separate parameters. */ + virtual double EvaluateCDF(double x, double mean, double variance) const; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluateInverseCDF(double p) const; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * for the distribution are passed as a parameters vector. The + * ordering of the parameters is (mean, variance). */ + virtual double EvaluateInverseCDF(double p, const ParametersType&) const; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * of the distribution are passed as separate parameters. */ + virtual double EvaluateInverseCDF(double p, + double mean, + double variance) const; + + /** Set the mean of the Gaussian distribution. Defaults to 0.0. The + * mean is stored in position 0 of the parameters vector. */ + virtual void SetMean(double); + + /** Get the mean of the Gaussian distribution. Defaults to 0.0. The + * mean is stored in position 0 of the parameters vector. */ + virtual double GetMean() const; + + /** Does this distribution have a mean? */ + virtual bool HasMean() const { return true; } + + /** Set the variance of the Gaussian distribution. Defaults + * to 1.0. The variance is stored in position 1 of the parameters + * vector. */ + virtual void SetVariance(double); + + /** Get the variance of the Gaussian distribution. Defaults to + * 1.0. The variance is stored in position 1 of the parameters vector. */ + virtual double GetVariance() const; + + /** Does this distribution have a variance? */ + virtual bool HasVariance() const { return true; } + + /** Static method to evaluate the probability density function (pdf) + * of a standardized (mean zero, unit variance) Gaussian. The static + * method provides optimized access without requiring an instance of + * the class. */ + static double PDF(double x); + + /** Static method to evaluate the probability density function (pdf) + * of a Gaussian. The parameters of the distribution are passed as a + * parameter vector. The ordering of the parameters is (mean, + * variance). The static method provides optimized access without + * requiring an instance of the class. */ + static double PDF(double x, const ParametersType&); + + /** Static method to evaluate the probability density function (pdf) + * of a Gaussian. The parameters of the distribution are passed as + * separate values. The static method provides optimized access + * without requiring an instance of the class. */ + static double PDF(double x, double mean, double variance); + + /** Static method to evaluate the cumulative distribution function + * (cdf) of a standardized (mean zero, unit variance) Gaussian. The + * static method provides optimized access without requiring an + * instance of the class. Accuracy is approximately 10^-8. */ + static double CDF(double x); + + /** Static method to evaluate the cumulative distribution function + * (cdf) of a Gaussian. The parameters of the distribution are passed + * as a parameter vector. The ordering of the parameters is (mean, + * variance). The static method provides optimized access + * without requiring an instance of the class. */ + static double CDF(double x, const ParametersType&); + + /** Static method to evaluate the cumulative distribution function + * (cdf) of a Gaussian. The parameters of the distribution are + * passed as separate values. The static method provides optimized access + * without requiring an instance of the class. */ + static double CDF(double x, double mean, double variance); + + /** Static method to evaluate the inverse cumulative distribution + * function of a standardized (mean zero, unit variance) Gaussian. + * The static method provides optimized access without requiring an + * instance of the class. Parameter p must be between 0.0 and 1.0. + * + * THis implementation was provided by Robert W. Cox from the + * Biophysics Research Institute at the Medical College of + * Wisconsin. This function is based off of a rational polynomial + * approximation to the inverse Gaussian CDF which can be found in + * M. Abramowitz and I.A. Stegun. Handbook of Mathematical Functions + * with Formulas, Graphs, and Mathematical Tables. John Wiley & Sons. + * New York. Equation 26.2.23. pg. 933. 1972. + * + * Since the initial approximation only provides an estimate within + * 4.5 E-4 of the true value, 3 Newton-Raphson interations are used + * to refine the approximation. Accuracy is approximately 10^-8. + * + * Let, + * Q(x) = (1/sqrt(2*pi)) Int_{x}^{infinity} e^{-t^2/2} dt + * = 0.5 * erfc(x/sqrt(2)) + * + * Given p, this function computes x such that Q(x) = p, for 0 < p < 1 + * + * Note that the Gaussian CDF is defined as + * P(x) = (1/sqrt(2*pi)) Int_{-infinity}{x} e^{-t^2/2} dt + * = 1 - Q(x) + * + * This function has been modified to compute the inverse of P(x) instead + * of Q(x). + */ + static double InverseCDF(double p); + + /** Static method to evaluate the inverse cumulative distribution + * function of a Gaussian. The parameters of the distribution are + * passed as a parameter vector. The ordering of the parameters is + * (mean, variance). The static method provides optimized access + * without requiring an instance of the class. Parameter p must be + * between 0.0 and 1.0 */ + static double InverseCDF(double p, const ParametersType&); + + /** Static method to evaluate the inverse cumulative distribution + * function of a Gaussian. The parameters of the distribution are + * passed as separate values. The static method provides optimized + * access without requiring an instance of the class. Parameter p + * must be between 0.0 and 1.0 */ + static double InverseCDF(double p, double mean, double variance); + +protected: + GaussianDistribution(void); + virtual ~GaussianDistribution(void) {} + + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + GaussianDistribution(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end of namespace Statistics +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.h b/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.h new file mode 100644 index 0000000000..7e89f752d9 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.h @@ -0,0 +1,112 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGaussianMembershipFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkGaussianMembershipFunction_h +#define __itkGaussianMembershipFunction_h + +#include "itkArray.h" +#include "itkMatrix.h" +#include "itkMembershipFunctionBase.h" + +namespace itk { +namespace Statistics { + +/** \class GaussianMembershipFunction + * \brief GaussianMembershipFunction class represents Gaussian function. + * + * This class keeps parameter to define Gaussian function and has + * method to return the probability density of an instance (pattern) . + * If the all element of the covariance matrix is zero the "usual" density + * calculations ignored. if the measurement vector to be evaluated is equal to + * the mean, then the Evaluate method will return maximum value of + * double and return 0 for others + * + * + */ + +template< class TMeasurementVector > +class ITK_EXPORT GaussianMembershipFunction : + public MembershipFunctionBase< TMeasurementVector > +{ +public: + /** Standard class typedefs */ + typedef GaussianMembershipFunction Self; + typedef MembershipFunctionBase< TMeasurementVector > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Strandard macros */ + itkTypeMacro(GaussianMembershipFunction, MembershipFunction); + itkNewMacro(Self); + + /** Typedef alias for the measurement vectors */ + typedef TMeasurementVector MeasurementVectorType; + + /** Length of each measurement vector */ + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + + /** Type of the mean vector */ + typedef Array< double > MeanType; + + /** Type of the covariance matrix */ + typedef VariableSizeMatrix< double > CovarianceType; + + /** Set/Get the mean */ + void SetMean( const MeanType & mean ); + itkGetConstMacro( Mean, MeanType ); + + /** Sets the covariance matrix. + * Also, this function calculates inverse covariance and pre factor of + * Gaussian Distribution to speed up GetProbability */ + void SetCovariance(const CovarianceType & cov); + itkGetConstMacro( Covariance, CovarianceType ); + + /** Gets the probability density of a measurement vector. */ + double Evaluate(const MeasurementVectorType &measurement) const; + + /** Return a copy of the current membership function */ + Pointer Clone(); + +protected: + GaussianMembershipFunction(void); + virtual ~GaussianMembershipFunction(void) {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + MeanType m_Mean; // mean + CovarianceType m_Covariance; // covariance matrix + + // inverse covariance matrix which is automatically calculated + // when covariace matirx is set. This speed up the GetProbability() + CovarianceType m_InverseCovariance; + + // pre_factor which is automatically calculated + // when covariace matirx is set. This speeds up the GetProbability() + double m_PreFactor; + + /** if the all element of the given covarinace is zero, then this + * value set to true */ + bool m_IsCovarianceZero; +}; + +} // end of namespace Statistics +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkGaussianMembershipFunction.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.txx b/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.txx new file mode 100644 index 0000000000..bf1fb0b568 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.txx @@ -0,0 +1,188 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGaussianMembershipFunction.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkGaussianMembershipFunction_txx +#define __itkGaussianMembershipFunction_txx + +#include "itkGaussianMembershipFunction.h" + +namespace itk { +namespace Statistics { + +template < class TMeasurementVector > +GaussianMembershipFunction< TMeasurementVector > +::GaussianMembershipFunction() +{ + m_PreFactor = 0.0; + m_Covariance.SetIdentity(); +} + +template < class TMeasurementVector > +void +GaussianMembershipFunction< TMeasurementVector > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Mean: " << m_Mean << std::endl; + os << indent << "Covariance: " << std::endl; + os << m_Covariance.GetVnlMatrix(); + os << indent << "InverseCovariance: " << std::endl; + os << indent << m_InverseCovariance.GetVnlMatrix(); + os << indent << "Prefactor: " << m_PreFactor << std::endl; + +} + +template < class TMeasurementVector > +void +GaussianMembershipFunction< TMeasurementVector > +::SetMean( const MeanType & mean ) +{ + if( this->GetMeasurementVectorSize() ) + { + MeasurementVectorTraits::Assert(mean, this->GetMeasurementVectorSize(), + "GaussianMembershipFunction::SetMean Size of measurement vectors in \ + the sample must the same as the size of the mean." ); + } + else + { + this->SetMeasurementVectorSize( mean.Size() ); + } + + if ( m_Mean != mean) + { + m_Mean = mean; + this->Modified(); + } +} + +template < class TMeasurementVector > +void +GaussianMembershipFunction< TMeasurementVector > +::SetCovariance(const CovarianceType & cov) +{ + // Sanity check + if( cov.GetVnlMatrix().rows() != cov.GetVnlMatrix().cols() ) + { + itkExceptionMacro( << "Covariance matrix must be square" ); + } + if( this->GetMeasurementVectorSize() ) + { + if( cov.GetVnlMatrix().rows() != this->GetMeasurementVectorSize() ) + { + itkExceptionMacro( << "Length of measurement vectors in the sample must be" + << " the same as the size of the covariance." ); + } + } + else + { + this->SetMeasurementVectorSize( cov.GetVnlMatrix().rows() ); + } + + m_Covariance = cov; + + m_IsCovarianceZero = m_Covariance.GetVnlMatrix().is_zero(); + + if ( !m_IsCovarianceZero ) + { + // allocate the memory for m_InverseCovariance matrix + m_InverseCovariance.GetVnlMatrix() = + vnl_matrix_inverse< double >(m_Covariance.GetVnlMatrix()); + + // the determinant of the covaraince matrix + double det = vnl_determinant(m_Covariance.GetVnlMatrix()); + + // calculate coefficient C of multivariate gaussian + m_PreFactor = 1.0 / (sqrt(det) * + vcl_pow(sqrt(2.0 * vnl_math::pi), double(this->GetMeasurementVectorSize()))); + } +} + +template < class TMeasurementVector > +inline double +GaussianMembershipFunction< TMeasurementVector > +::Evaluate(const MeasurementVectorType &measurement) const +{ + + double temp; + + const MeasurementVectorSizeType measurementVectorSize = + this->GetMeasurementVectorSize(); + MeanType tempVector; + MeasurementVectorTraits::SetLength( tempVector, measurementVectorSize ); + MeanType tempVector2; + MeasurementVectorTraits::SetLength( tempVector2, measurementVectorSize ); + + if ( !m_IsCovarianceZero ) + { + // Compute |y - mean | + for ( unsigned int i = 0; i < measurementVectorSize; i++) + { + tempVector[i] = measurement[i] - m_Mean[i]; + } + + + // Compute |y - mean | * inverse(cov) + for (unsigned int i = 0; i < measurementVectorSize; i++) + { + temp = 0; + for (unsigned int j = 0; j < measurementVectorSize; j++) + { + temp += tempVector[j] * m_InverseCovariance.GetVnlMatrix().get(j, i); + } + tempVector2[i] = temp; + } + + + // Compute |y - mean | * inverse(cov) * |y - mean|^T + temp = 0; + for (unsigned int i = 0; i < measurementVectorSize; i++) + { + temp += tempVector2[i] * tempVector[i]; + } + + return m_PreFactor * vcl_exp(-0.5 * temp ); + } + else + { + for ( unsigned int i = 0; i < measurementVectorSize; i++) + { + if ( m_Mean[i] != (double) measurement[i] ) + { + return 0; + } + } + return NumericTraits< double >::max(); + } +} + +template < class TVector > +typename GaussianMembershipFunction<TVector>::Pointer +GaussianMembershipFunction< TVector > +::Clone() +{ + Pointer membershipFunction = GaussianMembershipFunction< TVector >::New(); + membershipFunction->SetMeasurementVectorSize( this->GetMeasurementVectorSize() ); + membershipFunction->SetMean( this->GetMean() ); + membershipFunction->SetCovariance( this->GetCovariance() ); + + return membershipFunction; +} + +} // end namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkGaussianMixtureModelComponent.h b/Utilities/ITK/Code/Review/Statistics/itkGaussianMixtureModelComponent.h new file mode 100644 index 0000000000..4c61b940bd --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkGaussianMixtureModelComponent.h @@ -0,0 +1,119 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGaussianMixtureModelComponent.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkGaussianMixtureModelComponent_h +#define __itkGaussianMixtureModelComponent_h + +#include "itkMixtureModelComponentBase.h" +#include "itkGaussianMembershipFunction.h" +#include "itkWeightedMeanSampleFilter.h" +#include "itkWeightedCovarianceSampleFilter.h" + +namespace itk { +namespace Statistics { + +/** \class GaussianMixtureModelComponent + * \brief is a component (derived from MixtureModelComponentBase) for + * Gaussian class. This class is used in + * ExpectationMaximizationMixtureModelEstimator. + * + * On every iteration of EM estimation, this class's GenerateData + * method is called to compute the new distribution parameters. + * + * <b>Recent API changes:</b> + * The static const macro to get the length of a measurement vector, + * \c MeasurementVectorSize has been removed to allow the length of a measurement + * vector to be specified at run time. It is now obtained at run time from the + * sample set as input. Please use the function + * GetMeasurementVectorSize() to get the length. + * + * \sa MixtureModelComponentBase, ExpectationMaximizationMixtureModelEstimator + */ + +template< class TSample > +class ITK_EXPORT GaussianMixtureModelComponent : + public MixtureModelComponentBase< TSample > +{ +public: + /**Standard class typedefs. */ + typedef GaussianMixtureModelComponent Self; + typedef MixtureModelComponentBase< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /**Standard Macros */ + itkTypeMacro(GaussianMixtureModelComponent, MixtureModelComponentBase); + itkNewMacro(Self); + + + /** Typedefs from the superclass */ + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + typedef typename Superclass::MembershipFunctionType MembershipFunctionType; + typedef typename Superclass::WeightArrayType WeightArrayType; + typedef typename Superclass::ParametersType ParametersType; + + /** Type of the membership function. Gaussian density function */ + typedef GaussianMembershipFunction< MeasurementVectorType > + NativeMembershipFunctionType; + + /** Types of the mean and the covariance calculator that will update + * this component's distribution parameters */ + typedef WeightedMeanSampleFilter< TSample > MeanEstimatorType; + typedef WeightedCovarianceSampleFilter< TSample > CovarianceEstimatorType; + + /** Type of the mean vector */ + typedef typename MeanEstimatorType::OutputType MeanType; + + /** Type of the covariance matrix */ + typedef typename CovarianceEstimatorType::OutputType CovarianceType; + + /** Sets the input sample */ + void SetSample(const TSample* sample); + + /** Sets the component's distribution parameters. */ + void SetParameters(const ParametersType ¶meters); + +protected: + GaussianMixtureModelComponent(); + virtual ~GaussianMixtureModelComponent() {} + void PrintSelf(std::ostream& os, Indent indent) const; + + /** Returns the sum of squared changes in parameters between + * iterations */ + double CalculateParametersChange(); + + /** Computes the new distribution parameters */ + void GenerateData(); + +private: + typename NativeMembershipFunctionType::Pointer m_GaussianMembershipFunction; + + typename MeanEstimatorType::MeasurementVectorType m_Mean; + typename CovarianceEstimatorType::MatrixType m_Covariance; + typename MeanEstimatorType::Pointer m_MeanEstimator; + typename CovarianceEstimatorType::Pointer m_CovarianceEstimator; +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkGaussianMixtureModelComponent.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkGaussianMixtureModelComponent.txx b/Utilities/ITK/Code/Review/Statistics/itkGaussianMixtureModelComponent.txx new file mode 100644 index 0000000000..62fe1c4de8 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkGaussianMixtureModelComponent.txx @@ -0,0 +1,312 @@ +/*========================================================================= + +Program: Insight Segmentation & Registration Toolkit +Module: $RCSfile: itkGaussianMixtureModelComponent.txx,v $ +Language: C++ +Date: $Date: 2009-05-02 05:43:55 $ +Version: $Revision: 1.1 $ + +Copyright (c) Insight Software Consortium. All rights reserved. +See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkGaussianMixtureModelComponent_txx +#define __itkGaussianMixtureModelComponent_txx + +#include <iostream> + +#include "itkGaussianMixtureModelComponent.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +GaussianMixtureModelComponent< TSample > +::GaussianMixtureModelComponent() +{ + m_MeanEstimator = MeanEstimatorType::New(); + m_CovarianceEstimator = CovarianceEstimatorType::New(); + m_GaussianMembershipFunction = NativeMembershipFunctionType::New(); + this->SetMembershipFunction((MembershipFunctionType*) + m_GaussianMembershipFunction.GetPointer()); + m_Mean.Fill(0.0); + m_Covariance.SetIdentity(); +} + +template< class TSample > +void +GaussianMixtureModelComponent< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "Mean: " << m_Mean << std::endl; + os << indent << "Covariance: " << m_Covariance << std::endl; + os << indent << "Mean Estimator: " << m_MeanEstimator << std::endl; + os << indent << "Covariance Estimator: " << m_CovarianceEstimator << std::endl; + os << indent << "GaussianMembershipFunction: " << m_GaussianMembershipFunction << std::endl; +} + +template< class TSample > +void +GaussianMixtureModelComponent< TSample > +::SetSample(const TSample* sample) +{ + Superclass::SetSample(sample); + + m_MeanEstimator->SetInput(sample); + m_CovarianceEstimator->SetInput(sample); + + const MeasurementVectorSizeType measurementVectorLength = + sample->GetMeasurementVectorSize(); + m_GaussianMembershipFunction->SetMeasurementVectorSize( measurementVectorLength ); + + MeasurementVectorTraits::SetLength( m_Mean, measurementVectorLength ); + m_Covariance.SetSize( measurementVectorLength, measurementVectorLength ); + + m_Mean.Fill( NumericTraits< double >::Zero ); + + m_Covariance.Fill( NumericTraits< double >::Zero ); + + typename NativeMembershipFunctionType::MeanType mean; + + MeasurementVectorTraits::SetLength( mean, measurementVectorLength); + + for( unsigned int i=0; i < measurementVectorLength; ++i ) + { + mean[i] = m_Mean[i]; + } + + m_GaussianMembershipFunction->SetMean(mean); +} + +template< class TSample > +void +GaussianMixtureModelComponent< TSample > +::SetParameters(const ParametersType ¶meters) +{ + Superclass::SetParameters(parameters); + + unsigned int paramIndex = 0; + unsigned int i, j; + + bool changed = false; + + MeasurementVectorSizeType measurementVectorSize = + this->GetSample()->GetMeasurementVectorSize(); + + for ( i = 0; i < measurementVectorSize; i++) + { + if ( m_Mean[i] != parameters[paramIndex] ) + { + m_Mean[i] = parameters[paramIndex]; + changed = true; + } + + ++paramIndex; + } + + typename NativeMembershipFunctionType::MeanType mean; + + MeasurementVectorTraits::SetLength( mean, measurementVectorSize); + + for( i=0; i < measurementVectorSize; ++i ) + { + mean[i] = m_Mean[i]; + } + + m_GaussianMembershipFunction->SetMean(mean); + + for ( i = 0; i < measurementVectorSize; i++ ) + { + for ( j = 0; j < measurementVectorSize; j++ ) + { + if ( m_Covariance.GetVnlMatrix().get(i, j) != + parameters[paramIndex] ) + { + m_Covariance.GetVnlMatrix().put(i, j, parameters[paramIndex]); + changed = true; + } + ++paramIndex; + } + } + m_GaussianMembershipFunction->SetCovariance(m_Covariance); + + this->AreParametersModified(changed); +} + + +template< class TSample > +double +GaussianMixtureModelComponent< TSample > +::CalculateParametersChange() +{ + unsigned int i, j; + + typename MeanType::MeasurementVectorType meanEstimate = + m_MeanEstimator->GetMean(); + + CovarianceType covEstimateDecoratedObject = m_CovarianceEstimator->GetOutput(); + typename CovarianceType::MeasurementVectorType covEstimate = covEstimateDecoratedObject->et(); + + double temp; + double changes = 0.0; + MeasurementVectorSizeType measurementVectorSize = + this->GetSample()->GetMeasurementVectorSize(); + + for ( i = 0; i < measurementVectorSize; i++) + { + temp = m_Mean[i] - meanEstimate[i]; + changes += temp * temp; + } + + for ( i = 0; i < measurementVectorSize; i++ ) + { + for ( j = 0; j < measurementVectorSize; j++ ) + { + temp = m_Covariance.GetVnlMatrix().get(i, j) - + covEstimate.GetVnlMatrix().get(i, j); + changes += temp * temp; + } + } + + changes = vcl_sqrt(changes); + return changes; +} + +template< class TSample > +void +GaussianMixtureModelComponent< TSample > +::GenerateData() +{ + MeasurementVectorSizeType measurementVectorSize = + this->GetSample()->GetMeasurementVectorSize(); + + this->AreParametersModified(false); + + const WeightArrayType & weights = this->GetWeights(); + + typename TSample::ConstIterator iter = this->GetSample()->Begin(); + typename TSample::ConstIterator end = this->GetSample()->End(); + + typename TSample::MeasurementVectorType measurements; + + while (iter != end) + { + measurements = iter.GetMeasurementVector(); + ++iter; + } + + m_MeanEstimator->SetWeights( weights ); + m_MeanEstimator->Update(); + + + unsigned int i, j; + double temp; + double changes; + bool changed = false; + ParametersType parameters = this->GetFullParameters(); + int paramIndex = 0; + + typename MeanEstimatorType::MeasurementVectorType meanEstimate = m_MeanEstimator->GetMean(); + for ( i = 0; i < measurementVectorSize; i++) + { + temp = m_Mean[i] - meanEstimate[i]; + changes = temp * temp; + changes = vcl_sqrt(changes); + if ( changes > this->GetMinimalParametersChange() ) + { + changed = true; + } + } + + + if ( changed ) + { + m_Mean = meanEstimate; + for ( i = 0; i < measurementVectorSize; i++) + { + parameters[paramIndex] = meanEstimate[i]; + ++paramIndex; + } + this->AreParametersModified(true); + } + else + { + paramIndex = measurementVectorSize; + } + + m_CovarianceEstimator->SetWeights( weights ); + m_CovarianceEstimator->Update(); + typename CovarianceEstimatorType::MatrixType covEstimate = + m_CovarianceEstimator->GetCovarianceMatrix(); + + changed = false; + for ( i = 0; i < measurementVectorSize; i++ ) + { + for ( j = 0; j < measurementVectorSize; j++ ) + { + temp = m_Covariance.GetVnlMatrix().get(i, j) - + covEstimate.GetVnlMatrix().get(i, j); + changes = temp * temp; + changes = vcl_sqrt(changes); + if ( changes > this->GetMinimalParametersChange() ) + { + changed = true; + } + } + } + + if ( changed ) + { + m_Covariance = covEstimate; + for ( i = 0; i < measurementVectorSize; i++ ) + { + for ( j = 0; j < measurementVectorSize; j++ ) + { + parameters[paramIndex] = covEstimate.GetVnlMatrix().get(i, j); + ++paramIndex; + } + } + this->AreParametersModified(true); + } + + //THIS IS NEEDED TO update m_Mean and m_Covariance.SHOULD BE REMOVED + paramIndex = 0; + for ( i = 0; i < measurementVectorSize; i++) + { + m_Mean[i] = parameters[paramIndex]; + ++paramIndex; + } + + typename NativeMembershipFunctionType::MeanType mean; + MeasurementVectorTraits::SetLength( mean, measurementVectorSize); + + for( i=0; i < measurementVectorSize; ++i ) + { + mean[i] = m_Mean[i]; + } + m_GaussianMembershipFunction->SetMean(mean); + + for (i = 0; i < measurementVectorSize; i++ ) + { + for ( j = 0; j < measurementVectorSize; j++ ) + { + m_Covariance.GetVnlMatrix().put(i, j, parameters[paramIndex]); + ++paramIndex; + } + } + m_GaussianMembershipFunction->SetCovariance(m_Covariance); + + Superclass::SetParameters(parameters); +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkHistogram.h b/Utilities/ITK/Code/Review/Statistics/itkHistogram.h new file mode 100644 index 0000000000..88fa66bbaa --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkHistogram.h @@ -0,0 +1,501 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHistogram.h,v $ + Language: C++ + Date: $Date: 2009-05-22 12:54:58 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkHistogram_h +#define __itkHistogram_h + +#include <vector> + +#include "itkArray.h" +#include "itkSample.h" +#include "itkDenseFrequencyContainer2.h" +#include "itkSparseFrequencyContainer2.h" + +namespace itk { +namespace Statistics { + +/** + * Due to a bug in MSVC, an enum value cannot be accessed out of a template + * parameter until the template class opens. In order for templated classes + * to access the dimension of an image template parameter in defining their + * own dimension, this class is needed as a work-around. + */ +template <typename THistogram> +struct GetHistogramDimension +{ + itkStaticConstMacro(HistogramDimension, unsigned int, THistogram::MeasurementVectorSize); +}; + +/** \class Histogram + * \brief This class stores measurement vectors in the context of n-dimensional histogram. + * + * Histogram represents an ND histogram. Histogram bins can be + * regularly or irregularly spaced. The storage for the histogram is + * managed via the FrequencyContainer specified by the template + * argument. The default frequency container is a + * DenseFrequencyContainer. A SparseFrequencyContainer can be used as + * an alternative. + * + * Frequencies of a bin (SetFrequency(), IncreaseFrequency()) can be + * specified by measurement, index, or instance identifier. + * + * Measurements can be queried by bin index or instance + * identifier. In this case, the measurement returned in the centroid + * of the histogram bin. + * + * The Initialize() method is used to specified the number of bins for + * each dimension of the histogram. An overloaded version also allows + * for regularly spaced bins to defined. To define irregularly sized + * bins, use the SetBinMin()/SetBinMax() methods. + * + * If you do not know the length of the measurement vector at compile time, you + * should use the VariableDimensionHistogram class, instead of the Histogram + * class. + * + * If you know the length of the measuremen vector at compile time, you can + * conveniently be obtained from MeasurementVectorTraits. For instance, + * instantiate a histogram as below: + * + * \code + * typedef Histogram< THistogramMeasurement, typename TFrequencyContainer > HistogramType; + * \endcode + * + * \sa Sample, DenseFrequencyContainer, SparseFrequencyContainer, VariableDimensionHistogram + */ + +template < class TMeasurement = float, + class TFrequencyContainer = DenseFrequencyContainer2 > +class ITK_EXPORT Histogram + : public Sample < Array< TMeasurement > > +{ +public: + + // This type serves as the indirect definition of MeasurementVectorType + typedef Array< TMeasurement > ArrayType; + + /** Standard typedefs */ + typedef Histogram Self; + typedef Sample< ArrayType > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(Histogram, Sample); + + /** standard New() method support */ + itkNewMacro(Self); + + /** type of an element of a measurement vector */ + typedef TMeasurement MeasurementType; + + /** Common sample class typedefs */ + itkSuperclassTraitMacro(MeasurementVectorType) + itkSuperclassTraitMacro(InstanceIdentifier) + itkSuperclassTraitMacro(MeasurementVectorSizeType) + typedef MeasurementVectorType ValueType; + + /** frequency container typedef */ + typedef TFrequencyContainer FrequencyContainerType; + typedef typename FrequencyContainerType::Pointer FrequencyContainerPointer; + + /** Frequency and TotalFrequency value type from superclass */ + typedef typename FrequencyContainerType::AbsoluteFrequencyType AbsoluteFrequencyType; + typedef typename FrequencyContainerType::TotalAbsoluteFrequencyType TotalAbsoluteFrequencyType; + typedef typename FrequencyContainerType::RelativeFrequencyType RelativeFrequencyType; + typedef typename FrequencyContainerType::TotalRelativeFrequencyType TotalRelativeFrequencyType; + + /** Index typedef support. An index is used to access pixel values. */ + typedef Array< long > IndexType; + typedef typename IndexType::ValueType IndexValueType; + + /** size array type */ + typedef Array< unsigned long > SizeType; + typedef typename SizeType::ValueType SizeValueType; + + /** bin min max value storage types */ + typedef std::vector< MeasurementType > BinMinVectorType; + typedef std::vector< MeasurementType > BinMaxVectorType; + typedef std::vector< BinMinVectorType > BinMinContainerType; + typedef std::vector< BinMaxVectorType > BinMaxContainerType; + + + /** Initialize the histogram, generating the offset table and + * preparing the frequency container. Subclasses should call this + * method in their Initialize() method. */ + void Initialize(const SizeType &size); + + + /** Initialize the histogram using equal size bins. To assign bin's + * min and max values along each dimension use SetBinMin() and + * SetBinMax() functions. */ + void Initialize(const SizeType &size, MeasurementVectorType& lowerBound, + MeasurementVectorType& upperBound); + + /** Initialize the values of the histogram bins to zero */ + void SetToZero(); + + /** Get the index of a measurement value from the histogram. + * \deprecated Use GetIndex(const MeasurementVectorType & + * measurement, IndexType & index ) const instead. */ + const IndexType & GetIndex(const MeasurementVectorType& measurement) const; + + /** Get the index of histogram corresponding to the specified + * measurement value. Returns true if index is valid and false if + * the measurement is outside the histogram */ + bool GetIndex(const MeasurementVectorType & measurement, + IndexType & index ) const; + + /** Get the index that is uniquely labelled by an instance identifier + * The corresponding id is the offset of the index + * This method uses ImageBase::ComputeIndex() method */ + const IndexType & GetIndex( InstanceIdentifier id) const; + + /** Is set to false if the bins at edges of the histogram extend to + * +/- infinity. */ + itkGetConstMacro(ClipBinsAtEnds, bool); + + /** Set to false to have the bins at edges of the histogram extend to + * +/- infinity. */ + itkSetMacro(ClipBinsAtEnds, bool); + + /** Returns true if the given index is out of bound meaning one of index + * is not between [0, last index] */ + bool IsIndexOutOfBounds(const IndexType &index) const; + + /** Get the instance identifier of the bin that is indexed by the + * index. The corresponding instance identifier is the offset of the index + * This method uses ImageBase::ComputeIndex() method */ + InstanceIdentifier GetInstanceIdentifier(const IndexType &index) const; + + /** Returns the number of instances (bins or cells) in this container */ + InstanceIdentifier Size() const; + + /** Get the size (N-dimensional) of the histogram */ + const SizeType & GetSize() const; + + /** Get the size of histogram along a specified dimension */ + SizeValueType GetSize(unsigned int dimension) const; + + /** Get the minimum value of nth bin of dimension d */ + const MeasurementType& GetBinMin(unsigned int dimension, + InstanceIdentifier nbin) const; + + /** Get the maximum value of nth bin of dimension d */ + const MeasurementType& GetBinMax(unsigned int dimension, + InstanceIdentifier nbin) const; + + /** Set the minimum value of nth bin of dimension d */ + void SetBinMin(unsigned int dimension, InstanceIdentifier nbin, + MeasurementType min); + + /** Set the maximum value of nth bin of dimension d */ + void SetBinMax(unsigned int dimension, + InstanceIdentifier nbin, MeasurementType max); + + /** Get the minimum of the bin along dimension d corresponding to a + * particular measurement. */ + const MeasurementType& GetBinMinFromValue(unsigned int dimension, + float value ) const; + + /** Get the maximum of the bin along dimension d corresponding to a + * particular measurement. */ + const MeasurementType& GetBinMaxFromValue(unsigned int dimension, + float value ) const; + + /** Get the vector of bin minimums along a dimension */ + const BinMinVectorType& GetDimensionMins(unsigned int dimension) const; + + /** Get the vector of maximums along a dimension */ + const BinMaxVectorType& GetDimensionMaxs(unsigned int dimension) const; + + /** Get the minimums of the bins */ + const BinMinContainerType& GetMins() const; + + /** Method the maximums of the bins */ + const BinMaxContainerType& GetMaxs() const; + + /** Get the minimums of the bin corresponding to a particular index */ + const MeasurementVectorType & GetHistogramMinFromIndex(const IndexType &index) const; + + /** Get the maximums of the bin corresponding to a particular index */ + const MeasurementVectorType& GetHistogramMaxFromIndex(const IndexType &index) const; + + /** Get the frequency of an instance indentifier */ + AbsoluteFrequencyType GetFrequency( InstanceIdentifier id ) const; + + /** Get the frequency of an index */ + AbsoluteFrequencyType GetFrequency(const IndexType &index) const; + + /** Set all the bins in the histogram to a specified frequency */ + void SetFrequency( AbsoluteFrequencyType value ); + + /** Set the frequency of an instance identifier. Returns false if the bin is + * out of bounds. */ + bool SetFrequency( InstanceIdentifier id, AbsoluteFrequencyType value); + + /** Set the frequency of an index. Returns false if the bin is + * out of bounds. */ + bool SetFrequency(const IndexType &index, + AbsoluteFrequencyType value); + + /** Set the frequency of a measurement. Returns false if the bin is + * out of bounds. */ + bool SetFrequency(const MeasurementVectorType &measurement, + AbsoluteFrequencyType value); + + + /** Increase the frequency of an instance identifier. + * Frequency is increased by the specified value. Returns false if + * the bin is out of bounds. */ + bool IncreaseFrequency(InstanceIdentifier id, AbsoluteFrequencyType value); + + /** Increase the frequency of an index. Frequency is + * increased by the specified value. Returns false if the bin is out + * of bounds. */ + bool IncreaseFrequency(const IndexType &index, AbsoluteFrequencyType value); + + /** Increase the frequency of a measurement. Frequency is + * increased by the specified value. Returns false if the + * measurement is outside the bounds of the histogram. */ + bool IncreaseFrequency(const MeasurementVectorType &measurement, + AbsoluteFrequencyType value); + + /** Get the measurement of an instance identifier. This is the + * centroid of the bin. + */ + const MeasurementVectorType & GetMeasurementVector( InstanceIdentifier id) const; + + /** Get the measurement of an index. This is the centroid of the bin. */ + const MeasurementVectorType & GetMeasurementVector(const IndexType &index) const; + + /** Get the measurement a bin along a specified dimension. This is + * the midpoint of the bin along that dimension. */ + MeasurementType GetMeasurement(InstanceIdentifier n, + unsigned int dimension) const; + + /** Get the total frequency in the histogram */ + TotalAbsoluteFrequencyType GetTotalFrequency() const; + + /** Get the frequency of a dimension's nth element. */ + AbsoluteFrequencyType GetFrequency(InstanceIdentifier n, + unsigned int dimension) const; + + /** Get the pth percentile value for a dimension. + * + * Let assume n = the index of the bin where the p-th percentile value is, + * min = min value of the dimension of the bin, + * max = max value of the dimension of the bin, + * interval = max - min , + * pp = cumlated proportion until n-1 bin; + * and pb = frequency of the bin / total frequency of the dimension. + * + * If p is less than 0.5, + * the percentile value = + * min + ((p - pp ) / pb) * interval + * If p is greater than or equal to 0.5 + * the percentile value = + * max - ((pp - p) / pb) * interval */ + double Quantile(unsigned int dimension, double p) const; + + /** Method to graft another histogram's output */ + virtual void Graft( const DataObject * ); + +protected: + void PrintSelf(std::ostream& os, Indent indent) const; + +public: + + /** \class Histogram::ConstIterator class that walks through the elements of + * the histogram */ + class ConstIterator + { + public: + + friend class Histogram; + + ConstIterator(const Self * histogram) + { + m_Id = 0; + m_Histogram = histogram; + } + + ConstIterator(const ConstIterator & it) + { + m_Id = it.m_Id; + m_Histogram = it.m_Histogram; + } + + ConstIterator& operator=(const ConstIterator& it) + { + m_Id = it.m_Id; + m_Histogram = it.m_Histogram; + return *this; + } + + AbsoluteFrequencyType GetFrequency() const + { + return m_Histogram->GetFrequency(m_Id); + } + + InstanceIdentifier GetInstanceIdentifier() const + { + return m_Id; + } + + const MeasurementVectorType & GetMeasurementVector() const + { + return m_Histogram->GetMeasurementVector(m_Id); + } + + ConstIterator& operator++() + { + ++m_Id; + return *this; + } + + bool operator!=(const ConstIterator& it) + { + return (m_Id != it.m_Id); + } + + bool operator==(const ConstIterator& it) + { + return (m_Id == it.m_Id); + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // This method is purposely not implemented + ConstIterator(); + + ConstIterator(InstanceIdentifier id, const Self * histogram) + : m_Id(id), m_Histogram(histogram) + {} + + // ConstIterator pointing DenseFrequencyContainer + InstanceIdentifier m_Id; + + // Pointer of DenseFrequencyContainer + const Self* m_Histogram; + }; // end of iterator class + + /** \class Histogram::Iterator */ + class Iterator : public ConstIterator + { + public: + + Iterator(Self * histogram):ConstIterator( histogram ) + { + } + + Iterator(InstanceIdentifier id, Self * histogram) + : ConstIterator( id, histogram ) + {} + + Iterator(const Iterator & it):ConstIterator(it) + { + } + + Iterator & operator=(const Iterator& it) + { + this->ConstIterator::operator=( it ); + return *this; + } + + bool SetFrequency(const AbsoluteFrequencyType value) + { + Self * histogram = const_cast< Self * >( this->m_Histogram ); + return histogram->SetFrequency( this->m_Id, value ); + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // To ensure const-correctness these method must not be in the public API. + // The are purposly not implemented, since they should never be called. + Iterator(); + Iterator(const Self * histogram); + Iterator(InstanceIdentifier id, const Self * histogram); + Iterator(const ConstIterator & it); + ConstIterator& operator=(const ConstIterator& it); + + private: + }; // end of iterator class + + + Iterator Begin() + { + Iterator iter(0, this); + return iter; + } + + Iterator End() + { + return Iterator(m_OffsetTable[this->GetMeasurementVectorSize()], this); + } + + ConstIterator Begin() const + { + ConstIterator iter(0, this); + return iter; + } + + ConstIterator End() const + { + return ConstIterator(m_OffsetTable[this->GetMeasurementVectorSize()], this); + } + +protected: + Histogram(); + virtual ~Histogram() {} + + // The number of bins for each dimension + SizeType m_Size; + +private: + Histogram(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + typedef std::vector< InstanceIdentifier > OffsetTableType; + OffsetTableType m_OffsetTable; + FrequencyContainerPointer m_FrequencyContainer; + unsigned int m_NumberOfInstances; + + // This method is provided here just to avoid a "hidden" warning + // related to the virtual method available in DataObject. + virtual void Initialize() {}; + + // lower bound of each bin + std::vector< std::vector<MeasurementType> > m_Min; + + // upper bound of each bin + std::vector< std::vector<MeasurementType> > m_Max; + + mutable MeasurementVectorType m_TempMeasurementVector; + mutable IndexType m_TempIndex; + + bool m_ClipBinsAtEnds; +}; + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkHistogram.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkHistogram.txx b/Utilities/ITK/Code/Review/Statistics/itkHistogram.txx new file mode 100644 index 0000000000..03d76d0439 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkHistogram.txx @@ -0,0 +1,746 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHistogram.txx,v $ + Language: C++ + Date: $Date: 2009-05-04 15:47:43 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkHistogram_txx +#define __itkHistogram_txx + +#include "itkHistogram.h" +#include "itkNumericTraits.h" + +namespace itk { +namespace Statistics { + +template< class TMeasurement, class TFrequencyContainer > +Histogram<TMeasurement, TFrequencyContainer > +::Histogram() +{ + this->m_ClipBinsAtEnds = true; + this->m_FrequencyContainer = FrequencyContainerType::New(); + this->m_OffsetTable = OffsetTableType( this->GetMeasurementVectorSize() + 1 ); + for( unsigned int i = 0; i < this->GetMeasurementVectorSize() + 1; i++ ) + { + this->m_OffsetTable[i] = itk::NumericTraits< InstanceIdentifier >::Zero; + } +} + +template< class TMeasurement, class TFrequencyContainer > +typename +Histogram<TMeasurement, TFrequencyContainer >::InstanceIdentifier +Histogram<TMeasurement, TFrequencyContainer > +::Size() const +{ + if( this->GetMeasurementVectorSize() == 0 ) + { + return itk::NumericTraits< InstanceIdentifier >::Zero; + } + InstanceIdentifier size = 1; + for (unsigned int i = 0; i < this->GetMeasurementVectorSize(); i++) + { + size *= m_Size[i]; + } + return size; +} + +template< class TMeasurement, class TFrequencyContainer > +const typename +Histogram<TMeasurement, TFrequencyContainer >::SizeType & +Histogram<TMeasurement, TFrequencyContainer > +::GetSize() const +{ + return m_Size; +} + +template< class TMeasurement, class TFrequencyContainer > +typename +Histogram<TMeasurement, TFrequencyContainer >::SizeValueType +Histogram<TMeasurement, TFrequencyContainer > +::GetSize(unsigned int dimension) const +{ + return m_Size[dimension]; +} + +template< class TMeasurement, class TFrequencyContainer > +const typename +Histogram<TMeasurement, TFrequencyContainer >::MeasurementType & +Histogram<TMeasurement, TFrequencyContainer > +::GetBinMin(unsigned int dimension, InstanceIdentifier nbin) const +{ + return m_Min[dimension][nbin]; +} + +template< class TMeasurement, + class TFrequencyContainer > +const typename +Histogram<TMeasurement, TFrequencyContainer >::MeasurementType & +Histogram<TMeasurement, TFrequencyContainer > +::GetBinMax(unsigned int dimension, InstanceIdentifier nbin) const +{ + return m_Max[dimension][nbin]; +} + +template< class TMeasurement, class TFrequencyContainer > +void +Histogram<TMeasurement, TFrequencyContainer > +::SetBinMin( unsigned int dimension, InstanceIdentifier nbin, + MeasurementType min) +{ + m_Min[dimension][nbin] = min; +} + +template< class TMeasurement, class TFrequencyContainer > +void +Histogram<TMeasurement, TFrequencyContainer > +::SetBinMax( unsigned int dimension, InstanceIdentifier nbin, + MeasurementType max) +{ + m_Max[dimension][nbin] = max; +} + +template< class TMeasurement, class TFrequencyContainer > +const typename +Histogram<TMeasurement, TFrequencyContainer >::BinMinVectorType & +Histogram<TMeasurement, TFrequencyContainer > +::GetDimensionMins(unsigned int dimension) const +{ + return m_Min[dimension]; +} + +template< class TMeasurement, class TFrequencyContainer > +const typename +Histogram<TMeasurement, TFrequencyContainer >::BinMaxVectorType & +Histogram<TMeasurement, TFrequencyContainer > +::GetDimensionMaxs(unsigned int dimension) const +{ + return m_Max[dimension]; +} + +template< class TMeasurement, class TFrequencyContainer > +const typename +Histogram<TMeasurement, TFrequencyContainer >::BinMinContainerType & +Histogram<TMeasurement, TFrequencyContainer > +::GetMins() const +{ + return m_Min; +} + +template< class TMeasurement, class TFrequencyContainer > +const typename +Histogram<TMeasurement, TFrequencyContainer >::BinMaxContainerType & +Histogram<TMeasurement, TFrequencyContainer > +::GetMaxs() const +{ + return m_Max; +} + +template< class TMeasurement, class TFrequencyContainer > +typename +Histogram<TMeasurement, TFrequencyContainer >::AbsoluteFrequencyType +Histogram<TMeasurement, TFrequencyContainer > +::GetFrequency( InstanceIdentifier id ) const +{ + return m_FrequencyContainer->GetFrequency(id); +} + +template< class TMeasurement, class TFrequencyContainer > +bool +Histogram<TMeasurement, TFrequencyContainer > +::SetFrequency( InstanceIdentifier id, AbsoluteFrequencyType value) +{ + return m_FrequencyContainer->SetFrequency(id, value); +} + +template< class TMeasurement, class TFrequencyContainer > +bool +Histogram<TMeasurement, TFrequencyContainer > +::IncreaseFrequency(InstanceIdentifier id, AbsoluteFrequencyType value) +{ + return m_FrequencyContainer->IncreaseFrequency(id, value); +} + + +template< class TMeasurement, class TFrequencyContainer > +void +Histogram<TMeasurement, TFrequencyContainer > +::Initialize(const SizeType &size) +{ + + if( this->GetMeasurementVectorSize() == 0 ) + { + itkExceptionMacro("MeasurementVectorSize is Zero. It should be set to a non-zero value before calling Initialize"); + } + + this->m_Size = size; + + // creates offset table which will be used for generation of + // instance identifiers. + InstanceIdentifier num = 1; + + this->m_OffsetTable.resize( this->GetMeasurementVectorSize() + 1 ); + + this->m_OffsetTable[0] = num; + for (unsigned int i = 0; i < this->GetMeasurementVectorSize(); i++) + { + num *= m_Size[i]; + this->m_OffsetTable[i + 1] = num; + } + + this->m_TempIndex.SetSize( this->GetMeasurementVectorSize() ); + + m_NumberOfInstances = num; + + // adjust the sizes of min max value containers + unsigned int dim; + m_Min.resize(this->GetMeasurementVectorSize()); + for ( dim = 0; dim < this->GetMeasurementVectorSize(); dim++) + { + m_Min[dim].resize(m_Size[dim]); + } + + m_Max.resize(this->GetMeasurementVectorSize()); + for ( dim = 0; dim < this->GetMeasurementVectorSize(); dim++) + { + m_Max[dim].resize(m_Size[dim]); + } + + // initialize auxiliary variables + this->m_TempIndex.SetSize( this->GetMeasurementVectorSize() ); + this->m_TempMeasurementVector.SetSize( this->GetMeasurementVectorSize() ); + + // initialize the frequency container + m_FrequencyContainer->Initialize(this->m_OffsetTable[this->GetMeasurementVectorSize()]); + this->SetToZero(); +} + +template< class TMeasurement, class TFrequencyContainer > +void +Histogram<TMeasurement, TFrequencyContainer > +::SetToZero() +{ + m_FrequencyContainer->SetToZero(); +} + +template< class TMeasurement, class TFrequencyContainer > +void +Histogram<TMeasurement, TFrequencyContainer > +::Initialize(const SizeType &size, MeasurementVectorType& lowerBound, + MeasurementVectorType& upperBound) +{ + this->Initialize(size); + + float interval; + for ( unsigned int i = 0; i < this->GetMeasurementVectorSize(); i++) + { + if( size[i] > 0 ) + { + interval = (float) (upperBound[i] - lowerBound[i]) + / static_cast< MeasurementType >(size[i]); + + // Set the min vector and max vector + for (unsigned int j = 0; j < static_cast<unsigned int>(size[i] - 1); j++) + { + this->SetBinMin(i, j, (MeasurementType)(lowerBound[i] + + ((float)j * interval))); + this->SetBinMax(i, j, (MeasurementType)(lowerBound[i] + + (((float)j + 1) * interval))); + } + this->SetBinMin(i, size[i] - 1, + (MeasurementType)(lowerBound[i] + + (((float) size[i] - 1) * interval))); + this->SetBinMax(i, size[i] - 1, + (MeasurementType)(upperBound[i])); + } + } +} + +template< class TMeasurement, class TFrequencyContainer > +inline const typename Histogram<TMeasurement, TFrequencyContainer >::IndexType & +Histogram<TMeasurement, TFrequencyContainer > +::GetIndex(const MeasurementVectorType& measurement) const +{ + // Have this deprecated method call the un-deprecated one.. + this->GetIndex( measurement, m_TempIndex ); + return m_TempIndex; +} + + +/** */ +template< class TMeasurement, class TFrequencyContainer > +bool Histogram<TMeasurement, TFrequencyContainer > +::GetIndex(const MeasurementVectorType & measurement,IndexType & index ) const +{ + // now using something similar to binary search to find + // index. + unsigned int dim; + + if( index.Size() != this->GetMeasurementVectorSize() ) + { + index.SetSize( this->GetMeasurementVectorSize() ); + } + + int begin; + int mid; + int end; + + MeasurementType median; + MeasurementType tempMeasurement; + + for (dim = 0; dim < this->GetMeasurementVectorSize(); dim++) + { + tempMeasurement = measurement[dim]; + begin = 0; + if (tempMeasurement < m_Min[dim][begin]) + { + // one of measurement is below the minimum + // its ok if we extend the bins to infinity.. not ok if we don't + if(!m_ClipBinsAtEnds) + { + index[dim] = (long) 0; + continue; + } + else + { // set an illegal value and return 0 + index[dim] = (long) m_Size[dim]; + return false; + } + } + + end = m_Min[dim].size() - 1; + if (tempMeasurement >= m_Max[dim][end]) + { + // one of measurement is above the maximum + // its ok if we extend the bins to infinity.. not ok if we don't + if(!m_ClipBinsAtEnds) + { + index[dim] = (long) m_Size[dim]-1; + continue; + } + else + { // set an illegal value and return 0 + index[dim] = (long) m_Size[dim]; + return false; + } + } + + // Binary search for the bin where this measurement could be + mid = (end + 1) / 2; + median = m_Min[dim][mid]; + + while(true) + { + if (tempMeasurement < median ) + { + end = mid - 1; + } + else if (tempMeasurement > median) + { + // test whether it is inside the current bin by comparing to the max of this bin. + if( tempMeasurement < m_Max[dim][mid] && + tempMeasurement >= m_Min[dim][mid] ) + { + index[dim] = mid; + break; + } + // otherwise, continue binary search + begin = mid + 1; + } + else + { + index[dim] = mid; + break; + } + mid = begin + (end - begin) / 2; + median = m_Min[dim][mid]; + } // end of while + } // end of for() + return true; +} + + +template< class TMeasurement, class TFrequencyContainer > +inline const typename Histogram<TMeasurement, TFrequencyContainer >::IndexType& +Histogram<TMeasurement, TFrequencyContainer > +::GetIndex( InstanceIdentifier id ) const +{ + InstanceIdentifier id2 = id; + + for (int i = this->GetMeasurementVectorSize() - 1; i > 0; i--) + { + m_TempIndex[i] = static_cast<IndexValueType>(id2 / this->m_OffsetTable[i]); + id2 -= (m_TempIndex[i] * this->m_OffsetTable[i]); + } + m_TempIndex[0] = static_cast<IndexValueType>(id2); + + return m_TempIndex; +} + + +template< class TMeasurement, class TFrequencyContainer > +inline bool +Histogram<TMeasurement, TFrequencyContainer > +::IsIndexOutOfBounds(const IndexType &index) const +{ + for (unsigned int dim = 0; dim < this->GetMeasurementVectorSize(); dim++) + { + if (index[dim] < 0 || index[dim] >= static_cast<IndexValueType>(m_Size[dim])) + { + return true; + } + } + return false; +} + +template< class TMeasurement, class TFrequencyContainer > +inline typename Histogram<TMeasurement, TFrequencyContainer >::InstanceIdentifier +Histogram<TMeasurement, TFrequencyContainer > +::GetInstanceIdentifier(const IndexType &index) const +{ + InstanceIdentifier instanceId = 0; + for (int i= this->GetMeasurementVectorSize() - 1; i > 0; i-- ) + { + instanceId += index[i] * this->m_OffsetTable[i]; + } + + instanceId += index[0]; + + return instanceId; +} + + +template< class TMeasurement, class TFrequencyContainer > +inline const typename Histogram<TMeasurement, TFrequencyContainer >::MeasurementType& +Histogram<TMeasurement, TFrequencyContainer > +::GetBinMinFromValue(const unsigned int dimension, const float value ) const +{ + // If the value is lower than any of min value in the Histogram, + // it returns the lowest min value + if ( value <= this->m_Min[dimension][0] ) + { + return this->m_Min[dimension][0]; + } + + // If the value is higher than any of min value in the Histogram, + // it returns the highest min value + if ( value >= m_Min[dimension][m_Size[dimension]-1] ) + { + return m_Min[dimension][this->m_Size[dimension]-1]; + } + + unsigned int binMinFromValue = 0; + + for ( unsigned int i = 0; i < this->m_Size[dimension]; i++ ) + { + if ( (value >= this->m_Min[dimension][i]) + && (value < this->m_Max[dimension][i]) ) + { + binMinFromValue = i; + } + } + + return this->m_Min[dimension][binMinFromValue]; +} + +template< class TMeasurement, class TFrequencyContainer > +inline const typename Histogram< TMeasurement, TFrequencyContainer >::MeasurementType& +Histogram< TMeasurement, TFrequencyContainer > +::GetBinMaxFromValue(const unsigned int dimension, const float value ) const +{ + // If the value is lower than any of max value in the Histogram, + // it returns the lowest max value + if ( value <= this->m_Max[dimension][0] ) + { + return this->m_Max[dimension][0]; + } + + // If the value is higher than any of max value in the Histogram, + // it returns the highest max value + if ( value >= m_Max[dimension][m_Size[dimension]-1] ) + { + return m_Max[dimension][this->m_Size[dimension]-1]; + } + + unsigned int binMaxFromValue = 0; + + for ( unsigned int i = 0; i < this->m_Size[dimension]; i++ ) + { + if ( (value >= this->m_Min[dimension][i]) + && (value < this->m_Max[dimension][i]) ) + { + binMaxFromValue = i; + } + } + + return this->m_Max[dimension][binMaxFromValue]; +} + +template< class TMeasurement, class TFrequencyContainer > +const typename +Histogram< TMeasurement, TFrequencyContainer >::MeasurementVectorType& +Histogram< TMeasurement, TFrequencyContainer > +::GetHistogramMinFromIndex(const IndexType &index) const +{ + for( unsigned int i=0; i < this->GetMeasurementVectorSize(); i++ ) + { + m_TempMeasurementVector[i] = this->GetBinMin(i, index[i]); + } + return m_TempMeasurementVector; +} + +template< class TMeasurement, class TFrequencyContainer > +const typename +Histogram< TMeasurement, TFrequencyContainer >::MeasurementVectorType& +Histogram< TMeasurement, TFrequencyContainer > +::GetHistogramMaxFromIndex(const IndexType &index) const +{ + for( unsigned int i=0; i < this->GetMeasurementVectorSize(); i++ ) + { + m_TempMeasurementVector[i] = this->GetBinMax(i, index[i]); + } + return m_TempMeasurementVector; +} + +template< class TMeasurement, class TFrequencyContainer > +inline const typename Histogram< TMeasurement, TFrequencyContainer >::MeasurementVectorType & +Histogram< TMeasurement, TFrequencyContainer > +::GetMeasurementVector(const IndexType &index) const +{ + for ( unsigned int i = 0; i < this->GetMeasurementVectorSize(); i++) + { + MeasurementType value = (m_Min[i][index[i]] + m_Max[i][index[i]]); + m_TempMeasurementVector[i] = static_cast< MeasurementType >( value / 2.0 ); + } + return m_TempMeasurementVector; +} + +template< class TMeasurement, class TFrequencyContainer > +inline const typename Histogram< TMeasurement, TFrequencyContainer >::MeasurementVectorType & +Histogram< TMeasurement, TFrequencyContainer > +::GetMeasurementVector( InstanceIdentifier id) const +{ + return this->GetMeasurementVector( this->GetIndex(id) ); +} + +template< class TMeasurement, class TFrequencyContainer > +inline void +Histogram< TMeasurement, TFrequencyContainer > +::SetFrequency(const AbsoluteFrequencyType value) +{ + typename Self::Iterator iter = this->Begin(); + typename Self::Iterator end = this->End(); + + while ( iter != end ) + { + iter.SetFrequency(value); + ++iter; + } +} + +template< class TMeasurement, class TFrequencyContainer > +inline bool +Histogram< TMeasurement, TFrequencyContainer > +::SetFrequency(const IndexType &index, const AbsoluteFrequencyType value) +{ + return this->SetFrequency( this->GetInstanceIdentifier(index), value); +} + +template< class TMeasurement, class TFrequencyContainer > +inline bool +Histogram< TMeasurement, TFrequencyContainer > +::SetFrequency(const MeasurementVectorType &measurement, const AbsoluteFrequencyType value) +{ + return this->SetFrequency( this->GetInstanceIdentifier(GetIndex(measurement)), value); +} + +template< class TMeasurement, class TFrequencyContainer > +inline bool +Histogram< TMeasurement, TFrequencyContainer > +::IncreaseFrequency(const IndexType &index, const AbsoluteFrequencyType value) +{ + const bool result = + this->IncreaseFrequency( this->GetInstanceIdentifier(index), value); + return result; +} + +template< class TMeasurement, class TFrequencyContainer > +inline bool +Histogram< TMeasurement, TFrequencyContainer > +::IncreaseFrequency(const MeasurementVectorType &measurement, const AbsoluteFrequencyType value) +{ + IndexType index; + this->GetIndex( measurement, index ); + return this->IncreaseFrequency( this->GetInstanceIdentifier( index ), value ); +} + + +template< class TMeasurement, class TFrequencyContainer > +inline typename Histogram< TMeasurement, TFrequencyContainer >::AbsoluteFrequencyType +Histogram< TMeasurement, TFrequencyContainer > +::GetFrequency(const IndexType &index) const +{ + return ( this->GetFrequency( this->GetInstanceIdentifier(index)) ); +} + +template< class TMeasurement, class TFrequencyContainer > +typename +Histogram< TMeasurement, TFrequencyContainer >::MeasurementType +Histogram< TMeasurement, TFrequencyContainer > +::GetMeasurement( InstanceIdentifier n, unsigned int dimension) const +{ + return static_cast< MeasurementType >((m_Min[dimension][n] + + m_Max[dimension][n]) / 2); +} + +template< class TMeasurement, class TFrequencyContainer > +typename +Histogram< TMeasurement, TFrequencyContainer >::AbsoluteFrequencyType +Histogram< TMeasurement, TFrequencyContainer > +::GetFrequency( InstanceIdentifier n, unsigned int dimension) const +{ + InstanceIdentifier nextOffset = this->m_OffsetTable[dimension + 1]; + InstanceIdentifier current = this->m_OffsetTable[dimension] * n; + InstanceIdentifier includeLength = this->m_OffsetTable[dimension]; + InstanceIdentifier include; + InstanceIdentifier includeEnd; + InstanceIdentifier last = this->m_OffsetTable[this->GetMeasurementVectorSize()]; + + AbsoluteFrequencyType frequency = 0; + while (current < last) + { + include = current; + includeEnd = include + includeLength; + while(include < includeEnd) + { + frequency += GetFrequency(include); + include++; + } + current += nextOffset; + } + return frequency; +} + +template< class TMeasurement, class TFrequencyContainer > +inline typename Histogram< TMeasurement, TFrequencyContainer >::TotalAbsoluteFrequencyType +Histogram< TMeasurement, TFrequencyContainer > +::GetTotalFrequency() const +{ + return m_FrequencyContainer->GetTotalFrequency(); +} + +template< class TMeasurement, class TFrequencyContainer > +double +Histogram< TMeasurement, TFrequencyContainer > +::Quantile(unsigned int dimension, double p) const +{ + InstanceIdentifier n; + const unsigned int size = this->GetSize(dimension); + double p_n_prev; + double p_n; + double f_n; + double cumulated = 0; + double totalFrequency = double( this->GetTotalFrequency() ); + double binProportion; + double min, max, interval; + + if ( p < 0.5 ) + { + n = 0; + p_n = NumericTraits< double >::Zero; + do + { + f_n = this->GetFrequency(n, dimension); + cumulated += f_n; + p_n_prev = p_n; + p_n = cumulated / totalFrequency; + n++; + } + while( n < size && p_n < p); + + binProportion = f_n / totalFrequency; + + min = double( this->GetBinMin(dimension, n - 1) ); + max = double( this->GetBinMax(dimension, n - 1) ); + interval = max - min; + return min + ((p - p_n_prev) / binProportion) * interval; + } + else + { + n = size - 1; + InstanceIdentifier m = NumericTraits< InstanceIdentifier >::Zero; + p_n = NumericTraits< double >::One; + do + { + f_n = this->GetFrequency(n, dimension); + cumulated += f_n; + p_n_prev = p_n; + p_n = NumericTraits< double >::One - cumulated / totalFrequency; + n--; + m++; + } + while( m < size && p_n > p); + + binProportion = f_n / totalFrequency; + min = double( this->GetBinMin(dimension, n + 1) ); + max = double( this->GetBinMax(dimension, n + 1) ); + interval = max - min; + return max - ((p_n_prev - p) / binProportion) * interval; + } +} + +template< class TMeasurement, class TFrequencyContainer > +void +Histogram< TMeasurement, TFrequencyContainer > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "OffsetTable: " << std::endl; + for(unsigned int i=0; i < this->m_OffsetTable.size(); i++) + { + os << this->m_OffsetTable[i] << " "; + } + os << std::endl; + os << indent << "ClipBinsAtEnds: " << + itk::NumericTraits<bool>::PrintType( this->GetClipBinsAtEnds() ) << std::endl; + os << indent << "FrequencyContainerPointer: " << m_FrequencyContainer + << std::endl; +} + +template< class TMeasurement, class TFrequencyContainer > +void +Histogram< TMeasurement, TFrequencyContainer > +::Graft( const DataObject *thatObject ) +{ + this->Superclass::Graft(thatObject); + + const Self *thatConst = dynamic_cast< const Self * >(thatObject); + if (thatConst) + { + Self *that = const_cast< Self * >(thatConst); + this->m_Size = that->m_Size; + this->m_OffsetTable = that->m_OffsetTable; + this->m_FrequencyContainer = that->m_FrequencyContainer; + this->m_NumberOfInstances = that->m_NumberOfInstances; + this->m_Min = that->m_Min; + this->m_Max = that->m_Max; + this->m_TempMeasurementVector = that->m_TempMeasurementVector; + this->m_TempIndex = that->m_TempIndex; + this->m_ClipBinsAtEnds = that->m_ClipBinsAtEnds; + } +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkHistogramToTextureFeaturesFilter.h b/Utilities/ITK/Code/Review/Statistics/itkHistogramToTextureFeaturesFilter.h new file mode 100644 index 0000000000..ba180156b2 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkHistogramToTextureFeaturesFilter.h @@ -0,0 +1,220 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHistogramToTextureFeaturesFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-08 16:55:05 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkHistogramToTextureFeaturesFilter_h +#define __itkHistogramToTextureFeaturesFilter_h + +#include "itkHistogram.h" +#include "itkMacro.h" +#include "itkProcessObject.h" +#include "itkSimpleDataObjectDecorator.h" + +namespace itk { +namespace Statistics { + +/** \class HistogramToTextureFeaturesFilter +* \brief This class computes texture feature coefficients from a grey level +* co-occurrence matrix. +* +* This class computes features that summarize image texture, given a grey level +* co-occurrence matrix (generated by a ScalarImageToGreyLevelCooccurrenceMatrixGenerator +* or related class). +* +* The features calculated are as follows (where \f$ g(i, j) \f$ is the element in +* cell i, j of a a normalized GLCM): +* +* "Energy" \f$ = f_1 = \sum_{i,j}g(i, j)^2 \f$ +* +* "Entropy" \f$ = f_2 = -\sum_{i,j}g(i, j) \log_2 g(i, j)\f$, or 0 if \f$g(i, j) = 0\f$ +* +* "Correlation" \f$ = f_3 = \sum_{i,j}\frac{(i - \mu)(j - \mu)g(i, j)}{\sigma^2} \f$ +* +* "Difference Moment" \f$= f_4 = \sum_{i,j}\frac{1}{1 + (i - j)^2}g(i, j) \f$ +* +* "Inertia" \f$ = f_5 = \sum_{i,j}(i - j)^2g(i, j) \f$ (sometimes called "contrast.") +* +* "Cluster Shade" \f$ = f_6 = \sum_{i,j}((i - \mu) + (j - \mu))^3 g(i, j) \f$ +* +* "Cluster Prominence" \f$ = f_7 = \sum_{i,j}((i - \mu) + (j - \mu))^4 g(i, j) \f$ +* +* "Haralick's Correlation" \f$ = f_8 = \frac{\sum_{i,j}(i, j) g(i, j) -\mu_t^2}{\sigma_t^2} \f$ +* where \f$\mu_t\f$ and \f$\sigma_t\f$ are the mean and standard deviation of the row +* (or column, due to symmetry) sums. +* +* Above, \f$ \mu = \f$ (weighted pixel average) \f$ = \sum_{i,j}i \cdot g(i, j) = +* \sum_{i,j}j \cdot g(i, j) \f$ (due to matrix summetry), and +* +* \f$ \sigma = \f$ (weighted pixel variance) \f$ = \sum_{i,j}(i - \mu)^2 \cdot g(i, j) = +* \sum_{i,j}(j - \mu)^2 \cdot g(i, j) \f$ (due to matrix summetry) +* +* A good texture feature set to use is the Conners, Trivedi and Harlow set: +* features 1, 2, 4, 5, 6, and 7. There is some correlation between the various +* features, so using all of them at the same time is not necessarialy a good idea. +* +* NOTA BENE: The input histogram will be forcably normalized! +* This algorithm takes three passes through the input +* histogram if the histogram was already normalized, and four if not. +* +* Web references: +* +* http://www.cssip.uq.edu.au/meastex/www/algs/algs/algs.html +* http://www.ucalgary.ca/~mhallbey/texture/texture_tutorial.html +* +* Print references: +* +* Haralick, R.M., K. Shanmugam and I. Dinstein. 1973. Textural Features for +* Image Classification. IEEE Transactions on Systems, Man and Cybernetics. +* SMC-3(6):610-620. +* +* Haralick, R.M. 1979. Statistical and Structural Approaches to Texture. +* Proceedings of the IEEE, 67:786-804. +* +* R.W. Conners and C.A. Harlow. A Theoretical Comaprison of Texture Algorithms. +* IEEE Transactions on Pattern Analysis and Machine Intelligence, 2:204-222, 1980. +* +* R.W. Conners, M.M. Trivedi, and C.A. Harlow. Segmentation of a High-Resolution +* Urban Scene using Texture Operators. Computer Vision, Graphics and Image +* Processing, 25:273-310, 1984. +* +* \sa ScalarImageToGreyLevelCooccurrenceMatrixGenerator +* \sa MaskedScalarImageToGreyLevelCooccurrenceMatrixGenerator +* \sa ScalarImageTextureCalculator +* +* Author: Zachary Pincus */ + +template < class THistogram > +class ITK_EXPORT HistogramToTextureFeaturesFilter : public ProcessObject +{ +public: + /** Standard typedefs */ + typedef HistogramToTextureFeaturesFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(HistogramToTextureFeaturesFilter, ProcessObject); + + /** standard New() method support */ + itkNewMacro(Self); + + typedef THistogram HistogramType; + typedef typename HistogramType::Pointer HistogramPointer; + typedef typename HistogramType::ConstPointer HistogramConstPointer; + typedef typename HistogramType::MeasurementType MeasurementType; + typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; + typedef typename HistogramType::IndexType IndexType; + typedef typename HistogramType::AbsoluteFrequencyType AbsoluteFrequencyType; + typedef typename HistogramType::RelativeFrequencyType RelativeFrequencyType; + + typedef typename HistogramType::TotalAbsoluteFrequencyType + TotalAbsoluteFrequencyType; + + typedef typename HistogramType::TotalRelativeFrequencyType + TotalRelativeFrequencyType; + + /** Container to hold relative frequencies of the histogram */ + typedef std::vector< RelativeFrequencyType > RelativeFrequencyContainerType; + + /** Method to Set/Get the input Histogram */ + void SetInput ( const HistogramType * histogram ); + const HistogramType * GetInput() const; + + /** Smart Pointer type to a DataObject. */ + typedef DataObject::Pointer DataObjectPointer; + + /** Type of DataObjects used for scalar outputs */ + typedef SimpleDataObjectDecorator<MeasurementType> MeasurementObjectType; + + /** Return energy texture value. */ + MeasurementType GetEnergy() const; + const MeasurementObjectType* GetEnergyOutput() const; + + /** Return entropy texture value. */ + MeasurementType GetEntropy() const; + const MeasurementObjectType* GetEntropyOutput() const; + + /** return correlation texture value. */ + MeasurementType GetCorrelation() const; + const MeasurementObjectType* GetCorrelationOutput() const; + + /** Return inverse difference moment texture value. */ + MeasurementType GetInverseDifferenceMoment() const; + const MeasurementObjectType* GetInverseDifferenceMomentOutput() const; + /** Return inertia texture value. */ + MeasurementType GetInertia() const; + const MeasurementObjectType* GetInertiaOutput() const; + + /** Return cluster shade texture value. */ + MeasurementType GetClusterShade() const; + const MeasurementObjectType* GetClusterShadeOutput() const; + + /** Return cluster prominence texture value. */ + MeasurementType GetClusterProminence() const; + const MeasurementObjectType* GetClusterProminenceOutput() const; + + /** Return Haralick correlation texture value. */ + MeasurementType GetHaralickCorrelation() const; + const MeasurementObjectType* GetHaralickCorrelationOutput() const; + + /** Texture feature types */ + typedef enum + { + Energy, + Entropy, + Correlation, + InverseDifferenceMoment, + Inertia, + ClusterShade, + ClusterProminence, + HaralickCorrelation, + InvalidFeatureName + } TextureFeatureName; + + /** convenience method to access the texture values */ + MeasurementType GetFeature( TextureFeatureName name ); + + +protected: + HistogramToTextureFeaturesFilter(); + ~HistogramToTextureFeaturesFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** Make a DataObject to be used for output output. */ + virtual DataObjectPointer MakeOutput( unsigned int ); + + + void GenerateData(); + +private: + HistogramToTextureFeaturesFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + void ComputeMeansAndVariances( double &pixelMean, double &marginalMean, + double &marginalDevSquared, double &pixelVariance ); + + RelativeFrequencyContainerType m_RelativeFrequencyContainer; +}; + + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkHistogramToTextureFeaturesFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkHistogramToTextureFeaturesFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkHistogramToTextureFeaturesFilter.txx new file mode 100644 index 0000000000..3c2dc05935 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkHistogramToTextureFeaturesFilter.txx @@ -0,0 +1,451 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHistogramToTextureFeaturesFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-08 16:55:05 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkHistogramToTextureFeaturesFilter_txx +#define __itkHistogramToTextureFeaturesFilter_txx + +#include "itkHistogramToTextureFeaturesFilter.h" + +#include "itkNumericTraits.h" +#include "vnl/vnl_math.h" + +namespace itk { +namespace Statistics { + +//constructor +template< class THistogram > +HistogramToTextureFeaturesFilter< THistogram >:: +HistogramToTextureFeaturesFilter( void ) +{ + this->ProcessObject::SetNumberOfRequiredInputs(1); + + // allocate the data objects for the outputs which are + // just decorators real types + for (int i=0; i < 8; ++i) + { + this->ProcessObject::SetNthOutput( i, this->MakeOutput(i) ); + } +} + +template< class THistogram > +void +HistogramToTextureFeaturesFilter< THistogram > +::SetInput( const HistogramType * histogram ) +{ + this->ProcessObject::SetNthInput(0, + const_cast< HistogramType* >( histogram ) ); +} + +template< class THistogram > +const typename +HistogramToTextureFeaturesFilter<THistogram>::HistogramType * +HistogramToTextureFeaturesFilter< THistogram > +::GetInput( ) const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const HistogramType * > + (this->ProcessObject::GetInput(0) ); +} + + +template<class THistogram> +typename +HistogramToTextureFeaturesFilter<THistogram>::DataObjectPointer +HistogramToTextureFeaturesFilter<THistogram> +::MakeOutput( unsigned int itkNotUsed( idx ) ) +{ + return static_cast<DataObject*>(MeasurementObjectType::New().GetPointer()); +} + + +template< class THistogram > +void +HistogramToTextureFeaturesFilter< THistogram >:: +GenerateData( void ) +{ + typedef typename HistogramType::ConstIterator HistogramIterator; + + const HistogramType * inputHistogram = this->GetInput(); + + //Normalize the absolute frequencies and populate the relative frequency + //container + TotalRelativeFrequencyType totalFrequency = + static_cast< TotalRelativeFrequencyType >(inputHistogram->GetTotalFrequency()); + + m_RelativeFrequencyContainer.clear(); + + for (HistogramIterator hit = inputHistogram->Begin(); + hit != inputHistogram->End(); ++hit) + { + AbsoluteFrequencyType frequency = hit.GetFrequency(); + RelativeFrequencyType relativeFrequency = frequency / totalFrequency; + m_RelativeFrequencyContainer.push_back( relativeFrequency ); + } + + // Now get the various means and variances. This is takes two passes + // through the histogram. + double pixelMean; + double marginalMean; + double marginalDevSquared; + double pixelVariance; + + this->ComputeMeansAndVariances(pixelMean, marginalMean, marginalDevSquared, + pixelVariance); + + + // Finally compute the texture features. Another one pass. + MeasurementType energy = NumericTraits< MeasurementType>::Zero; + MeasurementType entropy = NumericTraits< MeasurementType>::Zero; + MeasurementType correlation = NumericTraits< MeasurementType>::Zero; + + MeasurementType inverseDifferenceMoment = + NumericTraits< MeasurementType>::Zero; + + MeasurementType inertia = NumericTraits< MeasurementType>::Zero; + MeasurementType clusterShade = NumericTraits< MeasurementType>::Zero; + MeasurementType clusterProminence = NumericTraits< MeasurementType>::Zero; + MeasurementType haralickCorrelation = NumericTraits< MeasurementType>::Zero; + + double pixelVarianceSquared = pixelVariance * pixelVariance; + double log2 = vcl_log(2.0); + + typename RelativeFrequencyContainerType::const_iterator rFreqIterator = + m_RelativeFrequencyContainer.begin(); + + for (HistogramIterator hit = inputHistogram->Begin(); + hit != inputHistogram->End(); ++hit) + { + RelativeFrequencyType frequency = *rFreqIterator; + ++rFreqIterator; + if (frequency == 0) + { + continue; // no use doing these calculations if we're just multiplying by zero. + } + + IndexType index = inputHistogram->GetIndex(hit.GetInstanceIdentifier()); + energy += frequency * frequency; + entropy -= (frequency > 0.0001) ? frequency * vcl_log(frequency) / log2 : 0; + correlation += ( (index[0] - pixelMean) * (index[1] - pixelMean) * frequency) + / pixelVarianceSquared; + inverseDifferenceMoment += frequency / + (1.0 + (index[0] - index[1]) * (index[0] - index[1]) ); + inertia += (index[0] - index[1]) * (index[0] - index[1]) * frequency; + clusterShade += vcl_pow((index[0] - pixelMean) + (index[1] - pixelMean), 3) * + frequency; + clusterProminence += vcl_pow((index[0] - pixelMean) + (index[1] - pixelMean), 4) * + frequency; + haralickCorrelation += index[0] * index[1] * frequency; + } + + haralickCorrelation = (haralickCorrelation - marginalMean * marginalMean) / + marginalDevSquared; + + MeasurementObjectType* energyOutputObject= + static_cast<MeasurementObjectType*>(this->ProcessObject::GetOutput(0)); + energyOutputObject->Set( energy ); + + MeasurementObjectType* entropyOutputObject= + static_cast<MeasurementObjectType*>(this->ProcessObject::GetOutput(1)); + entropyOutputObject->Set( entropy ); + + MeasurementObjectType* correlationOutputObject= + static_cast<MeasurementObjectType*>(this->ProcessObject::GetOutput(2)); + correlationOutputObject->Set( correlation ); + + MeasurementObjectType* inverseDifferenceMomentOutputObject= + static_cast<MeasurementObjectType*>(this->ProcessObject::GetOutput(3)); + inverseDifferenceMomentOutputObject->Set( inverseDifferenceMoment ); + + MeasurementObjectType* inertiaOutputObject= + static_cast<MeasurementObjectType*>(this->ProcessObject::GetOutput(4)); + inertiaOutputObject->Set( inertia ); + + MeasurementObjectType* clusterShadeOutputObject= + static_cast<MeasurementObjectType*>(this->ProcessObject::GetOutput(5)); + clusterShadeOutputObject->Set( clusterShade ); + + MeasurementObjectType* clusterProminenceOutputObject= + static_cast<MeasurementObjectType*>(this->ProcessObject::GetOutput(6)); + clusterProminenceOutputObject->Set( clusterProminence ); + + MeasurementObjectType* haralickCorrelationOutputObject= + static_cast<MeasurementObjectType*>(this->ProcessObject::GetOutput(7)); + haralickCorrelationOutputObject->Set( haralickCorrelation ); +} + +template< class THistogram > +void +HistogramToTextureFeaturesFilter< THistogram >:: +ComputeMeansAndVariances( double &pixelMean, double &marginalMean, + double &marginalDevSquared, double &pixelVariance ) +{ + // This function takes two passes through the histogram and two passes through + // an array of the same length as a histogram axis. This could probably be + // cleverly compressed to one pass, but it's not clear that that's necessary. + + typedef typename HistogramType::ConstIterator HistogramIterator; + + const HistogramType * inputHistogram = this->GetInput(); + + // Initialize everything + typename HistogramType::SizeValueType binsPerAxis = inputHistogram->GetSize(0); + double *marginalSums = new double[binsPerAxis]; + for (double *ms_It = marginalSums; + ms_It < marginalSums + binsPerAxis; ms_It++) + { + *ms_It = 0; + } + pixelMean = 0; + + typename RelativeFrequencyContainerType::const_iterator rFreqIterator = + m_RelativeFrequencyContainer.begin(); + + // Ok, now do the first pass through the histogram to get the marginal sums + // and compute the pixel mean + HistogramIterator hit = inputHistogram->Begin(); + while( hit != inputHistogram->End() ) + { + RelativeFrequencyType frequency = *rFreqIterator; + IndexType index = inputHistogram->GetIndex(hit.GetInstanceIdentifier()); + pixelMean += index[0] * frequency; + marginalSums[index[0]] += frequency; + ++hit; + ++rFreqIterator; + } + + /* Now get the mean and deviaton of the marginal sums. + Compute incremental mean and SD, a la Knuth, "The Art of Computer + Programming, Volume 2: Seminumerical Algorithms", section 4.2.2. + Compute mean and standard deviation using the recurrence relation: + M(1) = x(1), M(k) = M(k-1) + (x(k) - M(k-1) ) / k + S(1) = 0, S(k) = S(k-1) + (x(k) - M(k-1)) * (x(k) - M(k)) + for 2 <= k <= n, then + sigma = vcl_sqrt(S(n) / n) (or divide by n-1 for sample SD instead of + population SD). + */ + marginalMean = marginalSums[0]; + marginalDevSquared = 0; + for (unsigned int arrayIndex = 1; arrayIndex < binsPerAxis; arrayIndex++) + { + int k = arrayIndex + 1; + double M_k_minus_1 = marginalMean; + double S_k_minus_1 = marginalDevSquared; + double x_k = marginalSums[arrayIndex]; + + double M_k = M_k_minus_1 + (x_k - M_k_minus_1) / k; + double S_k = S_k_minus_1 + (x_k - M_k_minus_1) * (x_k - M_k); + + marginalMean = M_k; + marginalDevSquared = S_k; + } + marginalDevSquared = marginalDevSquared / binsPerAxis; + + rFreqIterator = m_RelativeFrequencyContainer.begin(); + // OK, now compute the pixel variances. + pixelVariance = 0; + for (hit = inputHistogram->Begin(); hit != inputHistogram->End(); ++hit) + { + RelativeFrequencyType frequency = *rFreqIterator; + IndexType index = inputHistogram->GetIndex(hit.GetInstanceIdentifier()); + pixelVariance += (index[0] - pixelMean) * (index[0] - pixelMean) * frequency; + ++rFreqIterator; + } + + delete [] marginalSums; +} + +template<class THistogram > +const +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementObjectType* +HistogramToTextureFeaturesFilter<THistogram> +::GetEnergyOutput() const +{ + return static_cast< const MeasurementObjectType*>(this->ProcessObject::GetOutput(0)); +} + +template<class THistogram > +const +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementObjectType* +HistogramToTextureFeaturesFilter<THistogram> +::GetEntropyOutput() const +{ + return static_cast< const MeasurementObjectType*>(this->ProcessObject::GetOutput(1)); +} + +template<class THistogram > +const +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementObjectType* +HistogramToTextureFeaturesFilter<THistogram> +::GetCorrelationOutput() const +{ + return static_cast< const MeasurementObjectType*>(this->ProcessObject::GetOutput(2)); +} + +template<class THistogram > +const +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementObjectType* +HistogramToTextureFeaturesFilter<THistogram> +::GetInverseDifferenceMomentOutput() const +{ + return static_cast< const MeasurementObjectType*>(this->ProcessObject::GetOutput(3)); +} + +template<class THistogram > +const +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementObjectType* +HistogramToTextureFeaturesFilter<THistogram> +::GetInertiaOutput() const +{ + return static_cast< const MeasurementObjectType*>(this->ProcessObject::GetOutput(4)); +} + +template<class THistogram > +const +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementObjectType* +HistogramToTextureFeaturesFilter<THistogram> +::GetClusterShadeOutput() const +{ + return static_cast< const MeasurementObjectType*>(this->ProcessObject::GetOutput(5)); +} + +template<class THistogram > +const +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementObjectType* +HistogramToTextureFeaturesFilter<THistogram> +::GetClusterProminenceOutput() const +{ + return static_cast< const MeasurementObjectType*>(this->ProcessObject::GetOutput(6)); +} + +template<class THistogram > +const +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementObjectType* +HistogramToTextureFeaturesFilter<THistogram> +::GetHaralickCorrelationOutput() const +{ + return static_cast<const MeasurementObjectType*>(this->ProcessObject::GetOutput(7)); +} + +template<class THistogram > +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementType +HistogramToTextureFeaturesFilter<THistogram> +::GetEnergy() const +{ + return this->GetEnergyOutput()->Get(); +} + +template<class THistogram > +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementType +HistogramToTextureFeaturesFilter<THistogram> +::GetEntropy() const +{ + return this->GetEntropyOutput()->Get(); +} + +template<class THistogram > +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementType +HistogramToTextureFeaturesFilter<THistogram> +::GetCorrelation() const +{ + return this->GetCorrelationOutput()->Get(); +} + +template<class THistogram > +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementType +HistogramToTextureFeaturesFilter<THistogram> +::GetInverseDifferenceMoment() const +{ + return this->GetInverseDifferenceMomentOutput()->Get(); +} + +template<class THistogram > +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementType +HistogramToTextureFeaturesFilter<THistogram> +::GetInertia() const +{ + return this->GetInertiaOutput()->Get(); +} + +template<class THistogram > +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementType +HistogramToTextureFeaturesFilter<THistogram> +::GetClusterShade() const +{ + return this->GetClusterShadeOutput()->Get(); +} + +template<class THistogram > +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementType +HistogramToTextureFeaturesFilter<THistogram> +::GetClusterProminence() const +{ + return this->GetClusterProminenceOutput()->Get(); +} + +template<class THistogram > +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementType +HistogramToTextureFeaturesFilter<THistogram> +::GetHaralickCorrelation() const +{ + return this->GetHaralickCorrelationOutput()->Get(); +} + +template<class THistogram > +typename HistogramToTextureFeaturesFilter< THistogram >::MeasurementType +HistogramToTextureFeaturesFilter<THistogram> +:: +GetFeature(TextureFeatureName feature) +{ + switch(feature) + { + case Energy: + return this->GetEnergy(); + case Entropy: + return this->GetEntropy(); + case Correlation: + return this->GetCorrelation(); + case InverseDifferenceMoment: + return this->GetInverseDifferenceMoment(); + case Inertia: + return this->GetInertia(); + case ClusterShade: + return this->GetClusterShade(); + case ClusterProminence: + return this->GetClusterProminence(); + case HaralickCorrelation: + return this->GetHaralickCorrelation(); + default: + return 0; + } +} + +template< class THistogram > +void +HistogramToTextureFeaturesFilter< THistogram > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} + +} // end of namespace Statistics +} // end of namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.h b/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.h new file mode 100644 index 0000000000..df9418f605 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.h @@ -0,0 +1,176 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkImageClassifierFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkImageClassifierFilter_h +#define __itkImageClassifierFilter_h + +#include <vector> + +#include "itkMembershipFunctionBase.h" +#include "itkDecisionRule.h" +#include "itkImageToImageFilter.h" +#include "itkSimpleDataObjectDecorator.h" + +namespace itk { +namespace Statistics { + +/** \class ImageClassifierFilter + * + * \brief Image classification class + * + * This filter takes input image, membership functions, + * decision rule and produces as output image with each pixel labeled + * according to the classification result. + * + * This class is templated over the type of input and output image and + * sample type. + * + * \sa SampleClassifierFilter + */ + +template< class TSample, class TInputImage, class TOutputImage > +class ITK_EXPORT ImageClassifierFilter : + public ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedef */ + typedef ImageClassifierFilter Self; + typedef ImageToImageFilter<TInputImage,TOutputImage> Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Standard macros */ + itkTypeMacro(ImageClassifierFilter, ProcessObject); + itkNewMacro(Self); + + /** Image pixel value typedef. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + typedef typename TInputImage::PixelType InputPixelType; + typedef typename TOutputImage::PixelType OutputPixelType; + + /** Image related typedefs. */ + typedef typename TInputImage::Pointer InputImagePointer; + typedef typename TOutputImage::Pointer OutputImagePointer; + + typedef typename TInputImage::SizeType InputSizeType; + typedef typename TInputImage::IndexType InputIndexType; + typedef typename TInputImage::RegionType InputImageRegionType; + typedef typename TOutputImage::SizeType OutputSizeType; + typedef typename TOutputImage::IndexType OutputIndexType; + typedef typename TOutputImage::RegionType OutputImageRegionType; + + /** Image related typedefs. */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension ); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TOutputImage::ImageDimension ); + + /** Type of the input Sample */ + typedef TSample SampleType; + + /** typedefs from SampleType object */ + typedef typename SampleType::MeasurementType MeasurementType; + typedef typename SampleType::MeasurementVectorType MeasurementVectorType; + + /** typedef for the MembershipFunction */ + typedef MembershipFunctionBase< MeasurementVectorType > MembershipFunctionType; + typedef typename MembershipFunctionType::ConstPointer MembershipFunctionPointer; + typedef std::vector< MembershipFunctionPointer > MembershipFunctionVectorType; + typedef SimpleDataObjectDecorator< + MembershipFunctionVectorType > MembershipFunctionVectorObjectType; + typedef typename + MembershipFunctionVectorObjectType::Pointer MembershipFunctionVectorObjectPointer; + + /** typedef for membership functions weight proprtion */ + typedef Array< double > MembershipFunctionsWeightsArrayType; + + typedef SimpleDataObjectDecorator< + MembershipFunctionsWeightsArrayType > MembershipFunctionsWeightsArrayObjectType; + typedef typename + MembershipFunctionsWeightsArrayObjectType::Pointer MembershipFunctionsWeightsArrayPointer; + + /** typedef for class label type */ + typedef unsigned long ClassLabelType; + typedef std::vector< ClassLabelType > ClassLabelVectorType; + typedef SimpleDataObjectDecorator< + ClassLabelVectorType > ClassLabelVectorObjectType; + typedef ClassLabelVectorObjectType::Pointer ClassLabelVectorObjectPointer; + + + /** type of the decision rule */ + typedef DecisionRule DecisionRuleType; + typedef DecisionRuleType::ConstPointer DecisionRulePointer; + + /** Sets the input image */ + void SetImage(const InputImageType * image); + const InputImageType * GetImage() const; + + /** Number of classes. This must match the number of labels and membership + * functions provided by the user, otherwise an exception will be thrown at + */ + itkSetMacro( NumberOfClasses, unsigned int ); + itkGetConstMacro( NumberOfClasses, unsigned int ); + + /** Set/Get the decision rule. */ + itkSetConstObjectMacro( DecisionRule, DecisionRuleType ); + itkGetConstObjectMacro( DecisionRule, DecisionRuleType ); + + /** Sets input vector of class labels. The length of this vector must match + * the number of classes, otherwise an exception will be thrown at run time. + * */ + void SetClassLabels(const ClassLabelVectorObjectType * classLabels ); + + /** Sets input vector of membership functions. The length of this vector must match + * the number of classes, otherwise an exception will be thrown at run time. + * */ + void SetMembershipFunctions(const MembershipFunctionVectorObjectType * membershipFunctions ); + + /** Sets array of weights for the membership functions */ + void SetMembershipFunctionsWeightsArray(const MembershipFunctionsWeightsArrayObjectType * weightsArray ); + + +protected: + ImageClassifierFilter(); + virtual ~ImageClassifierFilter() {} + void PrintSelf(std::ostream& os, Indent indent) const; + + ImageClassifierFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + + /** Starts the classification process */ + void GenerateData(); + +private: + + unsigned int m_NumberOfClasses; + + /** Decision Rule */ + DecisionRulePointer m_DecisionRule; + +}; // end of class + + +} // end of namespace Statistics +} // end of namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkImageClassifierFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.txx new file mode 100644 index 0000000000..772bc85352 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.txx @@ -0,0 +1,213 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkImageClassifierFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-22 17:44:20 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkImageClassifierFilter_txx +#define __itkImageClassifierFilter_txx + +#include "itkImageClassifierFilter.h" + +namespace itk { +namespace Statistics { + +template< class TSample, class TInputImage, class TOutputImage > +ImageClassifierFilter<TSample,TInputImage,TOutputImage> +::ImageClassifierFilter() +{ + this->m_NumberOfClasses = 0; + this->SetNumberOfRequiredInputs( 3 ); + this->SetNumberOfRequiredOutputs( 1 ); + + /** Initialize decision rule */ + m_DecisionRule = NULL; + + m_NumberOfClasses = 0; +} + +template< class TSample, class TInputImage, class TOutputImage > +void +ImageClassifierFilter<TSample,TInputImage,TOutputImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Number of classes: " + << this->GetNumberOfClasses() + << std::endl; + os << indent << "Decision Rule: " + << this->GetDecisionRule() + << std::endl; + os << indent << "Image: " + << this->GetImage() + << std::endl; +} + +template< class TSample, class TInputImage, class TOutputImage > +void +ImageClassifierFilter<TSample,TInputImage,TOutputImage> +::SetImage( const InputImageType * image ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(0, + const_cast< InputImageType * >( image ) ); +} + +template< class TSample, class TInputImage, class TOutputImage > +const TInputImage * +ImageClassifierFilter<TSample,TInputImage,TOutputImage> +::GetImage( ) const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const TInputImage * > + (this->ProcessObject::GetInput(0) ); +} + + +template< class TSample, class TInputImage, class TOutputImage > +void +ImageClassifierFilter<TSample,TInputImage,TOutputImage> +::SetClassLabels( const ClassLabelVectorObjectType * classLabels ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(1, + const_cast< ClassLabelVectorObjectType * >( classLabels ) ); +} + +template< class TSample, class TInputImage, class TOutputImage > +void +ImageClassifierFilter<TSample,TInputImage,TOutputImage> +::SetMembershipFunctions( const MembershipFunctionVectorObjectType * membershipFunctions ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(2, + const_cast< MembershipFunctionVectorObjectType * >( membershipFunctions ) ); +} + +template< class TSample, class TInputImage, class TOutputImage > +void +ImageClassifierFilter<TSample,TInputImage,TOutputImage> +::SetMembershipFunctionsWeightsArray( const +MembershipFunctionsWeightsArrayObjectType * weightsArray ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(3, + const_cast< + MembershipFunctionsWeightsArrayObjectType * >( weightsArray ) ); +} + +template< class TSample, class TInputImage, class TOutputImage > +void +ImageClassifierFilter<TSample,TInputImage,TOutputImage> +::GenerateData() +{ + const ClassLabelVectorObjectType * classLabelsDecorated = + static_cast< const ClassLabelVectorObjectType * >( this->ProcessObject::GetInput( 1 ) ); + + const MembershipFunctionVectorObjectType * membershipFunctionsDecorated = + static_cast< const MembershipFunctionVectorObjectType * >( this->ProcessObject::GetInput( 2 ) ); + + const MembershipFunctionsWeightsArrayObjectType * + membershipFunctionsWeightsArrayDecorated = + static_cast< const MembershipFunctionsWeightsArrayObjectType * >( this->ProcessObject::GetInput( 3 ) ); + + const ClassLabelVectorType & classLabels = classLabelsDecorated->Get(); + + const MembershipFunctionVectorType & membershipFunctions = membershipFunctionsDecorated->Get(); + + // Check number of Labels and MembershipSamples against the number of classes */ + if( membershipFunctions.size() != this->m_NumberOfClasses ) + { + itkExceptionMacro("Number of Membership functions does not match the number of classes"); + } + + if( classLabels.size() != this->m_NumberOfClasses ) + { + itkExceptionMacro("Number of class labels does not match the number of classes"); + } + + if( m_DecisionRule.IsNull()) + { + itkExceptionMacro("Decision rule is not set"); + } + + MembershipFunctionsWeightsArrayType membershipFunctionsWeightsArray; + if( membershipFunctionsWeightsArrayDecorated == NULL ) + { + // no weights array is set and hence all membership functions will have equal + // weight + membershipFunctionsWeightsArray.SetSize( this->m_NumberOfClasses ); + membershipFunctionsWeightsArray.Fill(1.0); + } + else + { + membershipFunctionsWeightsArray = membershipFunctionsWeightsArrayDecorated->Get(); + } + + if ( membershipFunctionsWeightsArray.Size() != this->m_NumberOfClasses +) + { + itkExceptionMacro("Membership functions weight array size does not match the\ + number of classes "); + } + + const InputImageType * inputImage = + static_cast< const InputImageType * >( this->ProcessObject::GetInput( 0 ) ); + + std::vector< double > discriminantScores; + discriminantScores.resize( this->m_NumberOfClasses ); + + OutputImageType * outputImage = dynamic_cast< OutputImageType * >( + this->ProcessObject::GetOutput(0)); + + outputImage->CopyInformation( inputImage ); + outputImage->SetRegions( inputImage->GetBufferedRegion() ); + outputImage->Allocate(); + + ImageRegionConstIterator< InputImageType > inpItr( inputImage, inputImage->GetBufferedRegion() ); + ImageRegionIterator< OutputImageType > outItr( outputImage, outputImage->GetBufferedRegion() ); + + inpItr.GoToBegin(); + outItr.GoToBegin(); + + while( !inpItr.IsAtEnd() ) + { + MeasurementVectorType measurements; + + MeasurementVectorTraits::Assign( measurements, inpItr.Get() ); + + for (unsigned int i = 0; i < this->m_NumberOfClasses; i++) + { + discriminantScores[i] = membershipFunctionsWeightsArray[i] * + membershipFunctions[i]->Evaluate(measurements); + } + + unsigned int classIndex; + classIndex = m_DecisionRule->Evaluate(discriminantScores); + + OutputPixelType value = static_cast< OutputPixelType >(classLabels[classIndex]); + outItr.Set(value); + + ++inpItr; + ++outItr; + } +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.h b/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.h new file mode 100644 index 0000000000..add1b6b98f --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.h @@ -0,0 +1,163 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkImageToHistogramFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkImageToHistogramFilter_h +#define __itkImageToHistogramFilter_h + + +#include "itkImageToListSampleAdaptor.h" +#include "itkSampleToHistogramFilter.h" +#include "itkDenseFrequencyContainer2.h" +#include "itkHistogram.h" +#include "itkObject.h" + + +namespace itk { +namespace Statistics { + + +/** \class ImageToHistogramFilter + * \brief This class generates an histogram from an image. + * + * The concept of Histogram in ITK is quite generic. It has been designed to + * manage multiple components data. This class facilitates the computation of + * an histogram from an image. Internally it creates a List that is feed into + * the SampleToHistogramFilter. + * + */ + + +template< class TImageType > +class ITK_EXPORT ImageToHistogramFilter : public ProcessObject +{ +public: + /** Standard typedefs */ + typedef ImageToHistogramFilter Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ImageToHistogramFilter, Object); + + /** standard New() method support */ + itkNewMacro(Self); + + typedef TImageType ImageType; + typedef ImageToListSampleAdaptor< ImageType > AdaptorType; + typedef typename AdaptorType::Pointer AdaptorPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename PixelType::ValueType ValueType; + typedef typename NumericTraits< ValueType >::RealType ValueRealType; + typedef DenseFrequencyContainer2 FrequencyContainerType; + + typedef Histogram< ValueRealType > HistogramType; + typedef typename HistogramType::Pointer HistogramPointer; + typedef typename HistogramType::ConstPointer HistogramConstPointer; + typedef typename HistogramType::SizeType HistogramSizeType; + typedef typename HistogramType::MeasurementType HistogramMeasurementType; + typedef typename HistogramType::MeasurementVectorType HistogramMeasurementVectorType; + + typedef SampleToHistogramFilter< + AdaptorType, HistogramType > GeneratorType; + + typedef typename GeneratorType::Pointer GeneratorPointer; + +public: + + /** Connects the input image for which the histogram is going to be computed */ + void SetInput( const ImageType * ); + const ImageType * GetInput() const; + + /** Return the output histogram. + \warning This output is only valid after the Compute() method has been invoked + \sa Compute */ + const HistogramType * GetOutput() const; + + /** Type of DataObjects to use for Size inputs */ + typedef SimpleDataObjectDecorator< + HistogramSizeType > InputHistogramSizeObjectType; + + /** Type of DataObjects to use for Marginal Scale inputs */ + typedef SimpleDataObjectDecorator< + HistogramMeasurementType > InputHistogramMeasurementObjectType; + + /** Type of DataObjects to use for Minimum and Maximums values of the + * histogram bins. */ + typedef SimpleDataObjectDecorator< + HistogramMeasurementVectorType > InputHistogramMeasurementVectorObjectType; + + /** Type of DataObjects to use for AutoMinimumMaximum input */ + typedef SimpleDataObjectDecorator< bool > InputBooleanObjectType; + + /** Methods for setting and getting the histogram size. The histogram size + * is encapsulated inside a decorator class. For this reason, it is possible + * to set and get the decorator class, but it is only possible to set the + * histogram size by value. This macro declares the methods + * SetHistogramSize(), SetHistogramSizeInput(), GetHistogramSizeInput(). + */ + itkSetDecoratedInputMacro( HistogramSize, HistogramSizeType, 1 ); + + /** Methods for setting and getting the Marginal scale value. The marginal + * scale is used when the type of the measurement vector componets are of + * integer type. */ + itkSetDecoratedInputMacro( MarginalScale, HistogramMeasurementType, 2 ); + + /** Methods for setting and getting the Minimum and Maximum values of the + * histogram bins. */ + itkSetDecoratedInputMacro( HistogramBinMinimum, HistogramMeasurementVectorType, 3 ); + itkSetDecoratedInputMacro( HistogramBinMaximum, HistogramMeasurementVectorType, 4 ); + + /** Methods for setting and getting the boolean flag that defines whether the + * minimum and maximum of the histogram are going to be computed + * automatically from the values of the sample */ + itkSetDecoratedInputMacro( AutoMinimumMaximum, bool, 5 ); + + + /** Method that facilitates the use of this filter in the internal + * pipeline of another filter. */ + virtual void GraftOutput(DataObject *output); + +protected: + ImageToHistogramFilter(); + virtual ~ImageToHistogramFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** Triggers the Computation of the histogram */ + void GenerateData( void ); + + /** Method that construct the outputs */ + DataObject::Pointer MakeOutput( unsigned int ); + +private: + ImageToHistogramFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + AdaptorPointer m_ImageToListAdaptor; + + GeneratorPointer m_HistogramGenerator; + +}; + + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkImageToHistogramFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.txx new file mode 100644 index 0000000000..a52a653dbe --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.txx @@ -0,0 +1,147 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkImageToHistogramFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkImageToHistogramFilter_txx +#define __itkImageToHistogramFilter_txx + +#include "itkImageToHistogramFilter.h" + + +namespace itk { +namespace Statistics { + + +template < class TImage > +ImageToHistogramFilter< TImage > +::ImageToHistogramFilter() +{ + this->SetNumberOfRequiredInputs(1); + this->SetNumberOfRequiredOutputs(1); + + this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); + + this->m_ImageToListAdaptor = AdaptorType::New(); + this->m_HistogramGenerator = GeneratorType::New(); + this->m_HistogramGenerator->SetInput( this->m_ImageToListAdaptor ); +} + + +template < class TImage > +void +ImageToHistogramFilter< TImage > +::SetInput( const ImageType * image ) +{ + this->ProcessObject::SetNthInput(0, const_cast< ImageType * >( image ) ); +} + + +template< class TImage > +const TImage * +ImageToHistogramFilter< TImage > +::GetInput( ) const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const ImageType * >(this->ProcessObject::GetInput(0) ); +} + + +template < class TImage > +DataObject::Pointer +ImageToHistogramFilter< TImage > +::MakeOutput(unsigned int itkNotUsed(idx)) +{ + typename HistogramType::Pointer output = HistogramType::New(); + return static_cast< DataObject * >( output ); +} + + +template < class TImage > +const typename ImageToHistogramFilter< TImage >::HistogramType * +ImageToHistogramFilter< TImage > +::GetOutput() const +{ + const HistogramType * output = + static_cast< const HistogramType * >( this->ProcessObject::GetOutput(0)); + return output; +} + + +template < class TImage > +void +ImageToHistogramFilter< TImage > +::GraftOutput(DataObject *graft) +{ + DataObject * output = + const_cast< HistogramType * >( this->GetOutput() ); + + // Call Histogram to copy meta-information, and the container + output->Graft( graft ); +} + + +template < class TImage > +void +ImageToHistogramFilter< TImage > +::GenerateData() +{ + this->m_ImageToListAdaptor->SetImage( this->GetInput( ) ); + + this->m_HistogramGenerator->SetHistogramSizeInput( this->GetHistogramSizeInput() ); + this->m_HistogramGenerator->SetMarginalScaleInput( this->GetMarginalScaleInput() ); + this->m_HistogramGenerator->SetAutoMinimumMaximumInput( this->GetAutoMinimumMaximumInput() ); + this->m_HistogramGenerator->SetHistogramBinMinimumInput( this->GetHistogramBinMinimumInput() ); + this->m_HistogramGenerator->SetHistogramBinMaximumInput( this->GetHistogramBinMaximumInput() ); + + this->m_HistogramGenerator->GraftOutput( + static_cast< HistogramType * >( this->ProcessObject::GetOutput(0)) ); + + this->m_HistogramGenerator->Update(); + + /** graft the minipipeline output back into this filter's output */ + this->GraftOutput( + const_cast< HistogramType * >( this->m_HistogramGenerator->GetOutput() ) ); +} + + +template < class TImage > +void +ImageToHistogramFilter< TImage > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "ImageToListSample adaptor = " << this->m_ImageToListAdaptor << std::endl; + os << indent << "HistogramGenerator = " << this->m_HistogramGenerator << std::endl; + // m_HistogramBinMinimum + os << indent << "HistogramBinMinimum: " << this->GetHistogramBinMinimumInput() << std::endl; + // m_HistogramBinMaximum + os << indent << "HistogramBinMaximum: " << this->GetHistogramBinMaximumInput() << std::endl; + // m_MarginalScale + os << indent << "MarginalScale: " << this->GetMarginalScaleInput() << std::endl; + // m_AutoMinimumMaximum + os << indent << "AutoMinimumMaximum: " << this->GetAutoMinimumMaximumInput() << std::endl; + // m_HistogramSize + os << indent << "HistogramSize: " << this->GetHistogramSizeInput() << std::endl; +} + + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleAdaptor.h b/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleAdaptor.h new file mode 100644 index 0000000000..15e706f975 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleAdaptor.h @@ -0,0 +1,304 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkImageToListSampleAdaptor.h,v $ + Language: C++ + Date: $Date: 2009-05-22 12:55:00 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkImageToListSampleAdaptor_h +#define __itkImageToListSampleAdaptor_h + +#include <typeinfo> + +#include "itkImage.h" +#include "itkPixelTraits.h" +#include "itkListSample.h" +#include "itkSmartPointer.h" +#include "itkImageRegionIterator.h" +#include "itkFixedArray.h" +#include "itkMacro.h" +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +/** \class ImageToListSampleAdaptor + * \brief This class provides ListSample interface to ITK Image + * + * After calling SetImage( const Image * ) method to plug in the image object, + * users can use Sample interfaces to access Image data. The resulting data + * are a list of measurement vectors. + * + * The measurment vector type is determined from the image pixel type. This class + * handles images with scalar, fixed array or variable length vector pixel types. + * + * + * \sa Sample, ListSample + */ + +template < class TImage > +class ITK_EXPORT ImageToListSampleAdaptor : + public ListSample< typename MeasurementVectorPixelTraits< typename TImage::PixelType >::MeasurementVectorType > +{ +public: + /** Standard class typedefs */ + typedef ImageToListSampleAdaptor Self; + + typedef ListSample< typename MeasurementVectorPixelTraits< + typename TImage::PixelType >::MeasurementVectorType > + Superclass; + + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ImageToListSampleAdaptor, ListSample); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Image typedefs */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::PixelContainerConstPointer PixelContainerConstPointer; + + /** Image Iterator typedef support */ + typedef ImageRegionIterator< ImageType > ImageIteratorType; + typedef ImageRegionConstIterator< ImageType > ImageConstIteratorType; + typedef PixelTraits< typename TImage::PixelType > PixelTraitsType; + + /** Superclass typedefs for Measurement vector, measurement, + * Instance Identifier, frequency, size, size element value */ + typedef typename MeasurementVectorPixelTraits< + PixelType >::MeasurementVectorType MeasurementVectorType; + typedef typename MeasurementVectorTraitsTypes< + MeasurementVectorType >::ValueType MeasurementType; + itkSuperclassTraitMacro( AbsoluteFrequencyType ) + itkSuperclassTraitMacro( TotalAbsoluteFrequencyType ) + itkSuperclassTraitMacro( MeasurementVectorSizeType ) + itkSuperclassTraitMacro( InstanceIdentifier ) + + typedef MeasurementVectorType ValueType; + + /** Method to set the image */ + void SetImage(const TImage* image); + + /** Method to get the image */ + const TImage* GetImage() const; + + /** returns the number of measurement vectors in this container */ + InstanceIdentifier Size() const; + + /** method to return measurement vector for a specified id */ + virtual const MeasurementVectorType & GetMeasurementVector(InstanceIdentifier id) const; + + /** method to return frequency for a specified id */ + AbsoluteFrequencyType GetFrequency(InstanceIdentifier id) const; + + /** method to return the total frequency */ + TotalAbsoluteFrequencyType GetTotalFrequency() const; + + /** Method to set UsePixelContainer flag */ + itkSetMacro( UsePixelContainer, bool ); + + /** Method to get UsePixelContainer flag */ + itkGetConstMacro( UsePixelContainer, bool ); + + /** Convenience methods to turn on/off the UsePixelContainer flag */ + itkBooleanMacro( UsePixelContainer ); + + // PrintSelf(std::ostream& os, Indent indent) const; + + /** \class ListSample::ConstIterator */ + class ConstIterator + { + friend class ImageToListSampleAdaptor; + public: + + ConstIterator( const ImageToListSampleAdaptor * adaptor ) + { + *this = adaptor->Begin(); + } + + ConstIterator(const ConstIterator &iter) + { + m_Iter = iter.m_Iter; + m_InstanceIdentifier = iter.m_InstanceIdentifier; + } + + ConstIterator& operator=( const ConstIterator & iter ) + { + m_Iter = iter.m_Iter; + m_InstanceIdentifier = iter.m_InstanceIdentifier; + return *this; + } + + AbsoluteFrequencyType GetFrequency() const + { + return 1; + } + + const MeasurementVectorType & GetMeasurementVector() const + { + MeasurementVectorTraits::Assign( this->m_MeasurementVectorCache, m_Iter.Get()); + return this->m_MeasurementVectorCache; + } + + InstanceIdentifier GetInstanceIdentifier() const + { + return m_InstanceIdentifier; + } + + ConstIterator& operator++() + { + ++m_Iter; + ++m_InstanceIdentifier; + return *this; + } + + bool operator!=(const ConstIterator &it) + { + return (m_Iter != it.m_Iter); + } + + bool operator==(const ConstIterator &it) + { + return (m_Iter == it.m_Iter); + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // This method should only be available to the ListSample class + ConstIterator( + ImageConstIteratorType iter, + InstanceIdentifier iid) + { + m_Iter = iter; + m_InstanceIdentifier = iid; + } + + // This method is purposely not implemented + ConstIterator(); + + private: + ImageConstIteratorType m_Iter; + mutable MeasurementVectorType m_MeasurementVectorCache; + InstanceIdentifier m_InstanceIdentifier; + }; + + /** \class ImageToListSampleAdaptor::Iterator */ + class Iterator : public ConstIterator + { + + friend class ImageToListSampleAdaptor; + + public: + + Iterator(Self * adaptor):ConstIterator(adaptor) + { + } + + Iterator(const Iterator &iter):ConstIterator( iter ) + { + } + + Iterator& operator =(const Iterator & iter) + { + this->ConstIterator::operator=( iter ); + return *this; + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // To ensure const-correctness these method must not be in the public API. + // The are purposly not implemented, since they should never be called. + Iterator(); + Iterator(const Self * adaptor); + Iterator( ImageConstIteratorType iter, InstanceIdentifier iid); + Iterator(const ConstIterator & it); + ConstIterator& operator=(const ConstIterator& it); + Iterator( + ImageIteratorType iter, + InstanceIdentifier iid):ConstIterator( iter, iid ) + { + } + + private: + }; + + + /** returns an iterator that points to the beginning of the container */ + Iterator Begin() + { + ImagePointer nonConstImage = const_cast< ImageType* >(m_Image.GetPointer()); + ImageIteratorType imageIterator( nonConstImage, nonConstImage->GetLargestPossibleRegion()); + Iterator iter(imageIterator.Begin(), 0); + return iter; + } + + /** returns an iterator that points to the end of the container */ + Iterator End() + { + ImagePointer nonConstImage = const_cast< ImageType* >(m_Image.GetPointer()); + ImageIteratorType imageIterator( nonConstImage, nonConstImage->GetLargestPossibleRegion()); + Iterator iter(imageIterator.End(), m_Image->GetPixelContainer()->Size()); + return iter; + } + + + /** returns an iterator that points to the beginning of the container */ + ConstIterator Begin() const + { + ImageConstIteratorType imageConstIterator( m_Image, m_Image->GetLargestPossibleRegion()); + ConstIterator iter(imageConstIterator.Begin(), 0); + return iter; + } + + /** returns an iterator that points to the end of the container */ + ConstIterator End() const + { + ImageConstIteratorType imageConstIterator( m_Image, m_Image->GetLargestPossibleRegion()); + ConstIterator iter(imageConstIterator.End(), m_Image->GetPixelContainer()->Size()); + return iter; + } + + +protected: + ImageToListSampleAdaptor(); + virtual ~ImageToListSampleAdaptor() {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + ImageToListSampleAdaptor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + ImageConstPointer m_Image; + mutable MeasurementVectorType m_MeasurementVectorInternal; + bool m_UsePixelContainer; + + PixelContainerConstPointer m_PixelContainer; + +}; // end of class ImageToListSampleAdaptor + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkImageToListSampleAdaptor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleAdaptor.txx b/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleAdaptor.txx new file mode 100644 index 0000000000..0b22900177 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleAdaptor.txx @@ -0,0 +1,144 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkImageToListSampleAdaptor.txx,v $ + Language: C++ + Date: $Date: 2009-05-08 16:55:05 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkImageToListSampleAdaptor_txx +#define __itkImageToListSampleAdaptor_txx + +#include "itkImageToListSampleAdaptor.h" + +namespace itk { +namespace Statistics { + +template < class TImage> +ImageToListSampleAdaptor< TImage> +::ImageToListSampleAdaptor() +{ + m_Image = 0; + m_UsePixelContainer = true; +} + +template < class TImage> +const typename ImageToListSampleAdaptor< TImage >::MeasurementVectorType& +ImageToListSampleAdaptor< TImage> +::GetMeasurementVector(InstanceIdentifier id) const +{ + if( m_Image.IsNull() ) + { + itkExceptionMacro("Image has not been set yet"); + } + + if ( m_UsePixelContainer ) + { + MeasurementVectorTraits::Assign( m_MeasurementVectorInternal, + (*m_PixelContainer)[id]); + } + else + { + MeasurementVectorTraits::Assign( m_MeasurementVectorInternal, + m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ); + } + + return m_MeasurementVectorInternal; +} + +/** returns the number of measurement vectors in this container*/ +template < class TImage> +typename ImageToListSampleAdaptor< TImage>::InstanceIdentifier +ImageToListSampleAdaptor< TImage> +::Size() const +{ + if( m_Image.IsNull() ) + { + itkExceptionMacro("Image has not been set yet"); + } + + return m_Image->GetPixelContainer()->Size(); +} + +template < class TImage> +inline typename ImageToListSampleAdaptor< TImage>::AbsoluteFrequencyType +ImageToListSampleAdaptor< TImage> +::GetFrequency( InstanceIdentifier ) const +{ + if( m_Image.IsNull() ) + { + itkExceptionMacro("Image has not been set yet"); + } + + return NumericTraits< AbsoluteFrequencyType >::One; +} + + +template < class TImage> +void +ImageToListSampleAdaptor< TImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Image: "; + if ( m_Image.IsNotNull() ) + { + os << m_Image << std::endl; + } + else + { + os << "not set." << std::endl; + } + os << indent << "UsePixelContainer: " + << this->GetUsePixelContainer() << std::endl; +} + +template < class TImage> +void +ImageToListSampleAdaptor< TImage> +::SetImage(const TImage* image) +{ + m_Image = image; + m_PixelContainer = image->GetPixelContainer(); + this->Modified(); +} + +template < class TImage> +const TImage* +ImageToListSampleAdaptor< TImage> +::GetImage() const +{ + if( m_Image.IsNull() ) + { + itkExceptionMacro("Image has not been set yet"); + } + + return m_Image.GetPointer(); +} + +template < class TImage> +typename ImageToListSampleAdaptor< TImage>::TotalAbsoluteFrequencyType +ImageToListSampleAdaptor< TImage> +::GetTotalFrequency() const +{ + if( m_Image.IsNull() ) + { + itkExceptionMacro("Image has not been set yet"); + } + + return this->Size(); +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleFilter.h b/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleFilter.h new file mode 100644 index 0000000000..bf005304b3 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleFilter.h @@ -0,0 +1,144 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkImageToListSampleFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:56 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkImageToListSampleFilter_h +#define __itkImageToListSampleFilter_h + +#include "itkListSample.h" +#include "itkPixelTraits.h" +#include "itkProcessObject.h" +#include "itkDataObject.h" +#include "itkDataObjectDecorator.h" +#include "itkFixedArray.h" + +namespace itk { +namespace Statistics { + +/** \class ImageToListSampleFilter + * \brief The class takes an image as input and generates a list sample as + * output. + * + * There are differences between this class and ImageToListSampleAdaptor. This + * class is not an adaptor. It creates a new list sample and does not + * provide a pseudo interface to the actual image to make it look like a + * list sample. + * + * The class optionally allows you to specify a mask image as an input. The + * list sample (if a mask is specified) is constructed from pixels that are + * within the mask + * + * \todo + * In future allow the filter to take a Spatial object as input so a + * generic spatial object like an ellipse etc can be used as a mask. + * Sure the ImageMaskSpatialObject + * can represent image masks too, so why not make SpatialObjects the default. I + * think the ImageMaskSpatialObject is slow in terms of inefficient iteration + * through the image. + * + * \sa ImageToListSampleAdaptor + */ +template < class TImage, class TMaskImage = TImage > +class ITK_EXPORT ImageToListSampleFilter : + public ProcessObject +{ +public: + /** Standard class typedefs */ + typedef ImageToListSampleFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ImageToListSampleFilter, ProcessObject); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Image typedefs */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename MeasurementVectorPixelTraits< + PixelType >::MeasurementVectorType MeasurementVectorType; + + /** Mask Image typedefs */ + typedef TMaskImage MaskImageType; + typedef typename MaskImageType::Pointer MaskImagePointer; + typedef typename MaskImageType::ConstPointer MaskImageConstPointer; + typedef typename MaskImageType::PixelType MaskPixelType; + + /** Type of the output list sample */ + typedef ListSample< MeasurementVectorType > ListSampleType; + + /** return the number of components of the input image */ + unsigned int GetMeasurementVectorSize() const; + + /** Method to set/get the image */ + void SetInput( const ImageType* image ); + const ImageType* GetInput() const; + + /** Method to set/get the mask */ + void SetMaskImage( const MaskImageType* image ); + const MaskImageType* GetMaskImage() const; + + /** Method to get the list sample, the generated output. Note that this does + * not invoke Update(). You should have called update on this class to get + * any meaningful output. */ + const ListSampleType * GetOutput() const; + + /** Set the pixel value treated as on in the mask. If a mask has been + * specified, only pixels with this value will be added to the list sample, if + * no mask has been specified all pixels will be added as measurement vectors + * to the list sample. */ + itkSetMacro( MaskValue, MaskPixelType ); + itkGetConstMacro( MaskValue, MaskPixelType ); + +protected: + ImageToListSampleFilter(); + virtual ~ImageToListSampleFilter() {} + void PrintSelf(std::ostream& os, Indent indent) const; + + /** Standard itk::ProcessObject subclass method. */ + typedef DataObject::Pointer DataObjectPointer; + virtual DataObjectPointer MakeOutput(unsigned int idx); + + /** This method causes the filter to generate its output. */ + virtual void GenerateData(); + + /** This method ensures that a mask image if specified has requested regions + * that at least contain the input image's buffered region. */ + virtual void GenerateInputRequestedRegion() + throw(InvalidRequestedRegionError); + + virtual void GenerateOutputInformation(); + +private: + ImageToListSampleFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + MaskPixelType m_MaskValue; + +}; // end of class ImageToListSampleFilter + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkImageToListSampleFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleFilter.txx new file mode 100644 index 0000000000..6624d757b5 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkImageToListSampleFilter.txx @@ -0,0 +1,228 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkImageToListSampleFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:56 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkImageToListSampleFilter_txx +#define __itkImageToListSampleFilter_txx + +#include "itkImageToListSampleFilter.h" +#include "itkImageRegionConstIterator.h" + +namespace itk { +namespace Statistics { + +template < class TImage, class TMaskImage > +ImageToListSampleFilter< TImage, TMaskImage > +::ImageToListSampleFilter() +{ + this->m_MaskValue = itk::NumericTraits< MaskPixelType >::max(); + this->SetNumberOfRequiredInputs(1); + this->SetNumberOfRequiredOutputs(1); + + this->ProcessObject::SetNthOutput(0, this->MakeOutput(0) ); +} + +template < class TImage, class TMaskImage > +void +ImageToListSampleFilter< TImage, TMaskImage > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "MaskValue: " + << static_cast<typename NumericTraits<MaskPixelType>::PrintType>( + this->GetMaskValue()) + << std::endl; +} + +template < class TImage, class TMaskImage > +void +ImageToListSampleFilter< TImage, TMaskImage > +::SetInput(const ImageType* image) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(0, + const_cast< ImageType* >( image ) ); +} + +template < class TImage, class TMaskImage > +void +ImageToListSampleFilter< TImage, TMaskImage > +::SetMaskImage(const MaskImageType* image) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(1, + const_cast< MaskImageType* >( image ) ); +} + +template < class TImage, class TMaskImage > +const TImage* +ImageToListSampleFilter< TImage, TMaskImage > +::GetInput() const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const ImageType * > + (this->ProcessObject::GetInput(0) ); +} + +template < class TImage, class TMaskImage > +const TMaskImage* +ImageToListSampleFilter< TImage, TMaskImage > +::GetMaskImage() const +{ + if (this->GetNumberOfInputs() < 2) + { + return 0; + } + + return static_cast<const MaskImageType * > + (this->ProcessObject::GetInput(1) ); +} + +template < class TImage, class TMaskImage > +typename ImageToListSampleFilter< TImage, TMaskImage >::DataObjectPointer +ImageToListSampleFilter< TImage, TMaskImage > +::MakeOutput(unsigned int itkNotUsed(idx)) +{ + typename ListSampleType::Pointer output = ListSampleType::New(); + return static_cast< DataObject * >( output ); +} + +template < class TImage, class TMaskImage > +unsigned int +ImageToListSampleFilter< TImage, TMaskImage > +::GetMeasurementVectorSize() const +{ + const ImageType *input = this->GetInput(); + + if( input == NULL ) + { + itkExceptionMacro("Input image has not been set yet"); + } + + MeasurementVectorType m; + unsigned int measurementVectorSize; + + if( !MeasurementVectorTraits::IsResizable( m ) ) + { + measurementVectorSize = MeasurementVectorTraits::GetLength( m ); + } + else + { + measurementVectorSize = input->GetNumberOfComponentsPerPixel(); + } + + return measurementVectorSize; +} + +template < class TImage, class TMaskImage > +void +ImageToListSampleFilter< TImage, TMaskImage > +::GenerateData() +{ + ListSampleType * output = + static_cast< ListSampleType * >( this->ProcessObject::GetOutput(0) ); + + const ImageType *input = this->GetInput(); + const MaskImageType *maskImage = NULL; + + // Verify whether the image and the mask have the same LargestPossibleRegion. + // Otherwise, throw an exception. + // + if (this->GetNumberOfInputs() > 1) + { + maskImage = this->GetMaskImage(); + + if( input->GetLargestPossibleRegion() != maskImage->GetLargestPossibleRegion()) + { + itkExceptionMacro("LargestPossibleRegion of the mask does not match the one for the image"); + } + } + + output->Clear(); + + typedef ImageRegionConstIterator< ImageType > IteratorType; + IteratorType it( input, input->GetBufferedRegion() ); + it.GoToBegin(); + + if( maskImage ) // mask specified + { + typedef ImageRegionConstIterator< MaskImageType > MaskIteratorType; + MaskIteratorType mit( maskImage, maskImage->GetBufferedRegion() ); + mit.GoToBegin(); + while( !it.IsAtEnd() ) + { + if( mit.Get() == this->m_MaskValue ) + { + MeasurementVectorType m; + MeasurementVectorTraits::Assign( m, it.Get() ); + output->PushBack( m ); + } + ++mit; + ++it; + } + } + else // no mask specified + { + while (!it.IsAtEnd()) + { + MeasurementVectorType m; + MeasurementVectorTraits::Assign( m, it.Get() ); + output->PushBack( m ); + ++it; + } + } +} + +template < class TImage, class TMaskImage > +void +ImageToListSampleFilter< TImage, TMaskImage > +::GenerateOutputInformation() +{ + Superclass::GenerateOutputInformation(); + + ListSampleType * output = + static_cast< ListSampleType * >( this->ProcessObject::GetOutput(0)); + output->SetMeasurementVectorSize( this->GetMeasurementVectorSize() ); +} + +template < class TImage, class TMaskImage > +void +ImageToListSampleFilter< TImage, TMaskImage > +::GenerateInputRequestedRegion() throw(InvalidRequestedRegionError) +{ + // call the superclass' implementation of this method. this should + // copy the output requested region to the input requested region + Superclass::GenerateInputRequestedRegion(); + +} + +template < class TImage, class TMaskImage > +const typename ImageToListSampleFilter< TImage, TMaskImage >::ListSampleType * +ImageToListSampleFilter< TImage, TMaskImage > +::GetOutput() const +{ + const ListSampleType * output = + static_cast< const ListSampleType * >( this->ProcessObject::GetOutput(0)); + return output; +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkJointDomainImageToListSampleAdaptor.h b/Utilities/ITK/Code/Review/Statistics/itkJointDomainImageToListSampleAdaptor.h new file mode 100644 index 0000000000..e0b60cdd17 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkJointDomainImageToListSampleAdaptor.h @@ -0,0 +1,373 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkJointDomainImageToListSampleAdaptor.h,v $ + Language: C++ + Date: $Date: 2009-05-22 12:55:00 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkJointDomainImageToListSampleAdaptor_h +#define __itkJointDomainImageToListSampleAdaptor_h + +#include "itkMacro.h" +#include "itkFixedArray.h" +#include "itkPoint.h" +#include "itkPixelTraits.h" +#include "itkImageRegionConstIteratorWithIndex.h" +#include "itkImageRegionIterator.h" +#include "itkImageRegionConstIterator.h" +#include "itkListSample.h" + +namespace itk { +namespace Statistics { + +/** \class ImageJointDomainTraits + * \brief This class provides the type defintion for the measurement + * vector in the joint domain (range domain -- pixel values + spatial + * domain -- pixel's physical coordinates). + * + * \sa JointDomainImageToListSampleAdaptor + */ +template< class TImage > +struct ImageJointDomainTraits +{ + typedef ImageJointDomainTraits Self; + typedef PixelTraits< typename TImage::PixelType > PixelTraitsType; + typedef typename PixelTraitsType::ValueType RangeDomainMeasurementType; + typedef typename TImage::IndexType::IndexValueType IndexValueType; + + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); + itkStaticConstMacro(Dimension, + unsigned int, + TImage::ImageDimension + + PixelTraitsType::Dimension ); + + typedef float CoordinateRepType; + typedef Point< CoordinateRepType, itkGetStaticConstMacro(ImageDimension) > PointType; + typedef JoinTraits< RangeDomainMeasurementType, CoordinateRepType > JoinTraitsType; + typedef typename JoinTraitsType::ValueType MeasurementType; + + typedef FixedArray< MeasurementType, itkGetStaticConstMacro(Dimension) > + MeasurementVectorType; +}; // end of ImageJointDomainTraits + + +/** \class JointDomainImageToListSampleAdaptor + * \brief This adaptor returns measurement vectors composed of an + * image pixel's range domain value (pixel value) and spatial domain + * value (pixel's physical coordiantes). + * + * This class is a derived class of the ListSample class. This class + * overrides the GetMeasurementVector method. The GetMeasurementVector + * returns a measurement vector that consist of a pixel's physical + * coordinates and intensity value. For example, if the image + * dimension is 3, and the pixel value is two component vector, the + * measurement vector is a 5 component vector. The first three + * component will be x, y, z physical coordinates (not index) and the + * rest two component is the pixel values. The type of component is + * float or which is determined by the ImageJointDomainTraits + * class. When the pixel value type is double, the component value + * type of a measurement vector is double. In other case, the + * component value type is float becase the physical coordinate value + * type is float. Since the measurment vector is a composition of + * spatial domain and range domain, for many statistical analysis, we + * want to normalize the values from both domains. For this purpose, + * there is the SetNormalizationFactors method. With the above example + * (5 component measurement vector), you can specify a 5 component + * normalization factor array. With such factors, the + * GetMeasurementVector method returns a measurement vector whose each + * component is divided by the corresponding component of the factor array. + * + * \sa Sample, ListSample, ImageToListSampleAdaptor + */ + +template < class TImage > +class ITK_EXPORT JointDomainImageToListSampleAdaptor + : public ListSample< typename ImageJointDomainTraits< TImage >::MeasurementVectorType > +{ +public: + + /** Standard class typedefs */ + typedef JointDomainImageToListSampleAdaptor Self; + + typedef ListSample < + typename ImageJointDomainTraits< TImage >::MeasurementVectorType > Superclass; + + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + + typedef ImageJointDomainTraits< TImage > ImageJointDomainTraitsType; + + typedef typename ImageJointDomainTraitsType::MeasurementVectorType + MeasurementVectorType; + + typedef typename ImageJointDomainTraitsType::MeasurementType + MeasurementType; + + typedef typename ImageJointDomainTraitsType::RangeDomainMeasurementType + RangeDomainMeasurementType; + + typedef typename ImageJointDomainTraitsType::PointType PointType; + + typedef typename ImageJointDomainTraitsType::CoordinateRepType + CoordinateRepType; + /** Run-time type information (and related methods). */ + itkTypeMacro(JointDomainImageToListSampleAdaptor, ListSample); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** the number of components in a measurement vector */ + itkStaticConstMacro(MeasurementVectorSize, + unsigned int, + ImageJointDomainTraitsType::Dimension); + + itkSuperclassTraitMacro( MeasurementVectorSizeType ) + + /** typedefs for Measurement vector, measurement, + * Instance Identifier, frequency, size, size element value */ + itkSuperclassTraitMacro( AbsoluteFrequencyType ) + itkSuperclassTraitMacro( TotalAbsoluteFrequencyType ) + itkSuperclassTraitMacro( InstanceIdentifier ) + + /** Image typedefs */ + typedef TImage ImageType; + typedef ImageRegionIterator< ImageType > ImageIteratorType; + typedef ImageRegionConstIterator< ImageType > ImageConstIteratorType; + + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::PixelContainerConstPointer PixelContainerConstPointer; + typedef typename ImageType::IndexType ImageIndexType; + typedef typename ImageType::IndexType::IndexValueType ImageIndexValueType; + typedef typename ImageType::SizeType ImageSizeType; + typedef typename ImageType::RegionType ImageRegionType; + typedef MeasurementVectorType ValueType; + + /** Method to set the image */ + void SetImage(const TImage* image); + + /** Method to get the image */ + const TImage* GetImage() const; + + /** returns the number of measurement vectors in this container */ + InstanceIdentifier Size() const; + + /** Get frequency */ + AbsoluteFrequencyType GetFrequency(InstanceIdentifier id) const; + + /** Get total frequency */ + TotalAbsoluteFrequencyType GetTotalFrequency() const; + + itkStaticConstMacro(RangeDomainDimension, + unsigned int, + itk::PixelTraits< + typename TImage::PixelType >::Dimension); + + typedef FixedArray< RangeDomainMeasurementType, + itkGetStaticConstMacro( RangeDomainDimension ) > + RangeDomainMeasurementVectorType; + + typedef std::vector< InstanceIdentifier > InstanceIdentifierVectorType; + + typedef FixedArray< float, itkGetStaticConstMacro(MeasurementVectorSize) > + NormalizationFactorsType; + + /** Sets the normalization factors */ + void SetNormalizationFactors(NormalizationFactorsType& factors); + + /** Gets the measurement vector specified by the instance + * identifier. This method overrides superclass method. */ + const MeasurementVectorType & GetMeasurementVector( InstanceIdentifier id) const; + + /** Method to set UsePixelContainer flag */ + itkSetMacro( UsePixelContainer, bool ); + itkGetConstMacro( UsePixelContainer, bool ); + itkBooleanMacro( UsePixelContainer ); + + // void PrintSelf(std::ostream& os, Indent indent) const; + + /** \class ListSample::ConstIterator */ + class ConstIterator + { + friend class JointDomainImageToListSampleAdaptor; + public: + + ConstIterator( const JointDomainImageToListSampleAdaptor * adaptor ) + { + *this = adaptor->Begin(); + } + + ConstIterator(const ConstIterator &iter) + { + m_InstanceIdentifier = iter.m_InstanceIdentifier; + m_Adaptor = iter.m_Adaptor; + } + + ConstIterator& operator=( const ConstIterator & iter ) + { + m_InstanceIdentifier = iter.m_InstanceIdentifier; + return *this; + } + + AbsoluteFrequencyType GetFrequency() const + { + return 1; + } + + const MeasurementVectorType & GetMeasurementVector() const + { + m_MeasurementVectorCache = m_Adaptor->GetMeasurementVector( m_InstanceIdentifier ); + return this->m_MeasurementVectorCache; + } + + InstanceIdentifier GetInstanceIdentifier() const + { + return m_InstanceIdentifier; + } + + ConstIterator& operator++() + { + ++m_InstanceIdentifier; + return *this; + } + + bool operator!=(const ConstIterator &it) + { + return (m_InstanceIdentifier != it.m_InstanceIdentifier); + } + + bool operator==(const ConstIterator &it) + { + return (m_InstanceIdentifier == it.m_InstanceIdentifier); + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // This method should only be available to the ListSample class + ConstIterator( + const JointDomainImageToListSampleAdaptor * adaptor, + InstanceIdentifier iid) + { + m_Adaptor = adaptor; + m_InstanceIdentifier = iid; + } + + // This method is purposely not implemented + ConstIterator(); + + private: + mutable MeasurementVectorType m_MeasurementVectorCache; + InstanceIdentifier m_InstanceIdentifier; + const JointDomainImageToListSampleAdaptor * m_Adaptor; + }; + + class Iterator : public ConstIterator + { + + friend class JointDomainImageToListSampleAdaptor; + + public: + + Iterator(Self * adaptor):ConstIterator(adaptor) + { + } + + Iterator(const Iterator &iter):ConstIterator( iter ) + { + } + + Iterator& operator =(const Iterator & iter) + { + this->ConstIterator::operator=( iter ); + return *this; + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // To ensure const-correctness these method must not be in the public API. + // The are purposly not implemented, since they should never be called. + Iterator(); + Iterator(const Self * adaptor); + Iterator(const ConstIterator & it); + ConstIterator& operator=(const ConstIterator& it); + Iterator( + const JointDomainImageToListSampleAdaptor * adaptor, + InstanceIdentifier iid):ConstIterator( adaptor, iid ) + { + } + + private: + }; + + + /** returns an iterator that points to the beginning of the container */ + Iterator Begin() + { + Iterator iter(this, 0); + return iter; + } + + /** returns an iterator that points to the end of the container */ + Iterator End() + { + Iterator iter(this, m_Image->GetPixelContainer()->Size()); + return iter; + } + + /** returns an iterator that points to the beginning of the container */ + ConstIterator Begin() const + { + ConstIterator iter(this, 0); + return iter; + } + + /** returns an iterator that points to the end of the container */ + ConstIterator End() const + { + ConstIterator iter(this, m_Image->GetPixelContainer()->Size()); + return iter; + } + + +protected: + JointDomainImageToListSampleAdaptor(); + virtual ~JointDomainImageToListSampleAdaptor() {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + JointDomainImageToListSampleAdaptor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + NormalizationFactorsType m_NormalizationFactors; + mutable MeasurementVectorType m_TempVector; + mutable PointType m_TempPoint; + mutable ImageIndexType m_TempIndex; + mutable RangeDomainMeasurementVectorType m_TempRangeVector; + ImageConstPointer m_Image; + bool m_UsePixelContainer; + + PixelContainerConstPointer m_PixelContainer; + +}; // end of class JointDomainImageToListSampleAdaptor + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkJointDomainImageToListSampleAdaptor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkJointDomainImageToListSampleAdaptor.txx b/Utilities/ITK/Code/Review/Statistics/itkJointDomainImageToListSampleAdaptor.txx new file mode 100644 index 0000000000..7a3bbb1169 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkJointDomainImageToListSampleAdaptor.txx @@ -0,0 +1,169 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkJointDomainImageToListSampleAdaptor.txx,v $ + Language: C++ + Date: $Date: 2009-05-08 16:55:05 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkJointDomainImageToListSampleAdaptor_txx +#define __itkJointDomainImageToListSampleAdaptor_txx + +#include "itkJointDomainImageToListSampleAdaptor.h" + +namespace itk { +namespace Statistics { + +template < class TImage > +JointDomainImageToListSampleAdaptor< TImage > +::JointDomainImageToListSampleAdaptor() +{ + m_NormalizationFactors.Fill( 1.0f ); + m_Image = 0; + m_UsePixelContainer = true; +} + +/** returns the number of measurement vectors in this container*/ +template < class TImage> +typename JointDomainImageToListSampleAdaptor< TImage>::InstanceIdentifier +JointDomainImageToListSampleAdaptor< TImage> +::Size() const +{ + if( m_Image.IsNull() ) + { + itkExceptionMacro("Image has not been set yet"); + } + + return m_Image->GetPixelContainer()->Size(); +} + +template < class TImage> +inline typename JointDomainImageToListSampleAdaptor< TImage>::AbsoluteFrequencyType +JointDomainImageToListSampleAdaptor< TImage> +::GetFrequency( InstanceIdentifier ) const +{ + if( m_Image.IsNull() ) + { + itkExceptionMacro("Image has not been set yet"); + } + + return NumericTraits< AbsoluteFrequencyType >::One; +} + + +template < class TImage> +void +JointDomainImageToListSampleAdaptor< TImage> +::PrintSelf( std::ostream& os, Indent indent ) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Image: "; + if ( m_Image.IsNotNull() ) + { + os << m_Image << std::endl; + } + else + { + os << "not set." << std::endl; + } + os << indent << "UsePixelContainer: " + << this->GetUsePixelContainer() << std::endl; +} + +template < class TImage> +void +JointDomainImageToListSampleAdaptor< TImage> +::SetImage(const TImage* image) +{ + m_Image = image; + m_PixelContainer = image->GetPixelContainer(); + this->Modified(); +} + +template < class TImage> +const TImage* +JointDomainImageToListSampleAdaptor< TImage> +::GetImage() const +{ + if( m_Image.IsNull() ) + { + itkExceptionMacro("Image has not been set yet"); + } + + return m_Image.GetPointer(); +} + +template < class TImage> +typename JointDomainImageToListSampleAdaptor< TImage>::TotalAbsoluteFrequencyType +JointDomainImageToListSampleAdaptor< TImage> +::GetTotalFrequency() const +{ + if( m_Image.IsNull() ) + { + itkExceptionMacro("Image has not been set yet"); + } + + return this->Size(); +} + + +template < class TImage > +void +JointDomainImageToListSampleAdaptor< TImage > +::SetNormalizationFactors(NormalizationFactorsType& factors) +{ + if ( m_NormalizationFactors != factors ) + { + m_NormalizationFactors = factors; + this->Modified(); + } +} + +template < class TImage > +const typename JointDomainImageToListSampleAdaptor< TImage >::MeasurementVectorType & +JointDomainImageToListSampleAdaptor< TImage > +::GetMeasurementVector(InstanceIdentifier id) const +{ + m_TempIndex = this->GetImage()->ComputeIndex( id ); + + this->GetImage()->TransformIndexToPhysicalPoint( m_TempIndex, m_TempPoint ); + + for ( unsigned int i = 0; i < TImage::ImageDimension; ++i ) + { + m_TempVector[i] = m_TempPoint[i] / m_NormalizationFactors[i]; + } + + if( m_UsePixelContainer ) + { + MeasurementVectorTraits::Assign( m_TempRangeVector, + (*m_PixelContainer)[id]); + } + else + { + MeasurementVectorTraits::Assign( m_TempRangeVector, + m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ); + } + + for ( unsigned int i = TImage::ImageDimension; i < MeasurementVectorType::Length; ++i ) + { + m_TempVector[i] = m_TempRangeVector[i - TImage::ImageDimension] + / m_NormalizationFactors[i]; + } + + return m_TempVector; +} + + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkKdTree.h b/Utilities/ITK/Code/Review/Statistics/itkKdTree.h new file mode 100644 index 0000000000..53de0cf9f6 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkKdTree.h @@ -0,0 +1,760 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkKdTree.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:56 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkKdTree_h +#define __itkKdTree_h + +#include <queue> +#include <vector> + +#include "itkMacro.h" +#include "itkPoint.h" +#include "itkSize.h" +#include "itkObject.h" +#include "itkNumericTraits.h" +#include "itkArray.h" + +#include "itkSample.h" +#include "itkSubsample.h" + +#include "itkEuclideanDistanceMetric.h" + +namespace itk { +namespace Statistics { + +/** \class KdTreeNode + * \brief This class defines the interface of its derived classes. + * + * The methods defined in this class are a superset of the methods + * defined in its subclases. Therefore, the subclasses implements only + * part of the methods. The template argument, TSample, can be any + * subclass of the Sample class. + * + * There are two categories for the subclasses, terminal and nonterminal + * nodes. The terminal nodes stores the instance identifiers beloging to + * them, while the nonterminal nodes don't. Therefore, the + * AddInstanceIdentifier and the GetInstanceIdentifier have meaning only + * with the terminal ones. The terminal nodes don't have any child (left + * or right). For terminal nodes, the GetParameters method is void. + * + * <b>Recent API changes:</b> + * The static const macro to get the length of a measurement vector, + * \c MeasurementVectorSize has been removed to allow the length of a measurement + * vector to be specified at run time. The \c typedef for \c CentroidType has + * been changed from Array to FixedArray. + * + * \sa KdTreeNonterminalNode, KdTreeWeightedCentroidNonterminalNode, + * KdTreeTerminalNode + */ +template< class TSample > +struct KdTreeNode +{ + /** type alias for itself */ + typedef KdTreeNode< TSample> Self; + + /** Measurement type, not the measurement vector type */ + typedef typename TSample::MeasurementType MeasurementType; + + /** Centroid type */ + typedef Array< double > CentroidType; + + /** Instance identifier type (index value type for the measurement + * vector in a sample */ + typedef typename TSample::InstanceIdentifier InstanceIdentifier; + + /** Returns true if the node is a terminal node, that is a node that + * doesn't have any child. */ + virtual bool IsTerminal() const = 0; + + /** Fills the partitionDimension (the dimension that was chosen to + * split the measurement vectors belong to this node to the left and the + * right child among k dimensions) and the partitionValue (the + * measurement value on the partitionDimension divides the left and the + * right child */ + virtual void GetParameters(unsigned int &partitionDimension, + MeasurementType &partitionValue) const = 0; + + /** Returns the pointer to the left child of this node */ + virtual Self* Left() = 0; + virtual const Self* Left() const = 0; + + /** Returns the pointer to the right child of this node */ + virtual Self* Right() = 0; + virtual const Self* Right() const = 0; + + /** Returs the number of measurement vectors under this node including + * its children */ + virtual unsigned int Size() const = 0; + + /** Returns the vector sum of the all measurement vectors under this node */ + virtual void GetWeightedCentroid(CentroidType ¢roid) = 0; + + /** Returns the centroid. weighted centroid divided by the size */ + virtual void GetCentroid(CentroidType ¢roid) = 0; + + /** Retuns the instance identifier of the index-th measurement vector */ + virtual InstanceIdentifier GetInstanceIdentifier(size_t index) const = 0; + + /** Add an instance to this node */ + virtual void AddInstanceIdentifier(InstanceIdentifier id) = 0; + + /** Destructor */ + virtual ~KdTreeNode() {}; // needed to subclasses will actually be deleted +}; // end of class + +/** \class KdTreeNonterminalNode + * \brief This is a subclass of the KdTreeNode. + * + * KdTreeNonterminalNode doesn't store the information related with the + * centroids. Therefore, the GetWeightedCentroid and the GetCentroid + * methods are void. This class should have the left and the right + * children. If we have a sample and want to generate a KdTree without + * the centroid related information, we can use the KdTreeGenerator. + * + * \sa KdTreeNode, KdTreeWeightedCentroidNonterminalNode, KdTreeGenerator + */ +template< class TSample > +struct KdTreeNonterminalNode: public KdTreeNode< TSample > +{ + typedef KdTreeNode< TSample > Superclass; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::CentroidType CentroidType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + + KdTreeNonterminalNode(unsigned int partitionDimension, + MeasurementType partitionValue, + Superclass* left, + Superclass* right); + + virtual ~KdTreeNonterminalNode() {} + + virtual bool IsTerminal() const + { + return false; + } + + void GetParameters(unsigned int &partitionDimension, + MeasurementType &partitionValue) const; + + Superclass* Left() + { + return m_Left; + } + + Superclass* Right() + { + return m_Right; + } + + const Superclass* Left() const + { + return m_Left; + } + + const Superclass* Right() const + { + return m_Right; + } + + unsigned int Size() const + { + return 0; + } + + void GetWeightedCentroid( CentroidType & ) + { + /* do nothing */ + } + + void GetCentroid( CentroidType & ) + { + /* do nothing */ + } + + // Returns the identifier of the only MeasurementVector associated with + // this node in the tree. This MeasurementVector will be used later during + // the distance computation when querying the tree. + InstanceIdentifier GetInstanceIdentifier(size_t) const + { return this->m_InstanceIdentifier; } + + void AddInstanceIdentifier(InstanceIdentifier valueId) + { this->m_InstanceIdentifier = valueId; } + +private: + unsigned int m_PartitionDimension; + MeasurementType m_PartitionValue; + InstanceIdentifier m_InstanceIdentifier; + Superclass* m_Left; + Superclass* m_Right; +}; // end of class + +/** \class KdTreeWeightedCentroidNonterminalNode + * \brief This is a subclass of the KdTreeNode. + * + * KdTreeNonterminalNode does have the information related with the + * centroids. Therefore, the GetWeightedCentroid and the GetCentroid + * methods returns meaningful values. This class should have the left + * and right children. If we have a sample and want to generate a KdTree + * with the centroid related information, we can use the + * WeightedCentroidKdTreeGenerator. The centroid, the weighted + * centroid, and the size (the number of measurement vectors) can be + * used to accelate the k-means estimation. + * + * \sa KdTreeNode, KdTreeNonterminalNode, WeightedCentroidKdTreeGenerator + */ +template< class TSample > +struct KdTreeWeightedCentroidNonterminalNode: public KdTreeNode< TSample > +{ + typedef KdTreeNode< TSample > Superclass; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::CentroidType CentroidType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; + + KdTreeWeightedCentroidNonterminalNode(unsigned int partitionDimension, + MeasurementType partitionValue, + Superclass* left, + Superclass* right, + CentroidType ¢roid, + unsigned int size); + virtual ~KdTreeWeightedCentroidNonterminalNode() {} + + virtual bool IsTerminal() const + { + return false; + } + + void GetParameters(unsigned int &partitionDimension, + MeasurementType &partitionValue) const; + + /** Return the length of a measurement vector */ + MeasurementVectorSizeType GetMeasurementVectorSize() const + { + return m_MeasurementVectorSize; + } + + Superclass* Left() + { + return m_Left; + } + + Superclass* Right() + { + return m_Right; + } + + + const Superclass* Left() const + { + return m_Left; + } + + const Superclass* Right() const + { + return m_Right; + } + + unsigned int Size() const + { + return m_Size; + } + + void GetWeightedCentroid(CentroidType ¢roid) + { + centroid = m_WeightedCentroid; + } + + void GetCentroid(CentroidType ¢roid) + { + centroid = m_Centroid; + } + + InstanceIdentifier GetInstanceIdentifier(size_t) const + { + return this->m_InstanceIdentifier; + } + + void AddInstanceIdentifier(InstanceIdentifier valueId) + { + this->m_InstanceIdentifier = valueId; + } + +private: + MeasurementVectorSizeType m_MeasurementVectorSize; + unsigned int m_PartitionDimension; + MeasurementType m_PartitionValue; + CentroidType m_WeightedCentroid; + CentroidType m_Centroid; + InstanceIdentifier m_InstanceIdentifier; + unsigned int m_Size; + Superclass* m_Left; + Superclass* m_Right; +}; // end of class + + +/** \class KdTreeTerminalNode + * \brief This class is the node that doesn't have any child node. The + * IsTerminal method returns true for this class. This class stores the + * instance identifiers belonging to this node, while the nonterminal + * nodes do not store them. The AddInstanceIdentifier and + * GetInstanceIdentifier are storing and retrieving the instance + * identifiers belonging to this node. + * + * \sa KdTreeNode, KdTreeNonterminalNode, + * KdTreeWeightedCentroidNonterminalNode + */ +template< class TSample > +struct KdTreeTerminalNode: public KdTreeNode< TSample > +{ + typedef KdTreeNode< TSample > Superclass; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::CentroidType CentroidType; + typedef typename Superclass::InstanceIdentifier InstanceIdentifier; + + KdTreeTerminalNode() {} + + virtual ~KdTreeTerminalNode() {} + + bool IsTerminal() const + { + return true; + } + + void GetParameters(unsigned int &, + MeasurementType &) const {} + + Superclass* Left() + { + return 0; + } + + Superclass* Right() + { + return 0; + } + + const Superclass* Left() const + { + return 0; + } + + const Superclass* Right() const + { + return 0; + } + + unsigned int Size() const + { + return static_cast<unsigned int>( m_InstanceIdentifiers.size() ); + } + + void GetWeightedCentroid(CentroidType &) + { + /* do nothing */ + } + + void GetCentroid(CentroidType &) + { + /* do nothing */ + } + + InstanceIdentifier GetInstanceIdentifier(size_t index) const + { + return m_InstanceIdentifiers[index]; + } + + void AddInstanceIdentifier(InstanceIdentifier id) + { + m_InstanceIdentifiers.push_back(id); + } + +private: + std::vector< InstanceIdentifier > m_InstanceIdentifiers; +}; // end of class + +/** \class KdTree + * \brief This class provides methods for k-nearest neighbor search and + * related data structures for a k-d tree. + * + * An object of this class stores instance identifiers in a k-d tree + * that is a binary tree with childrens split along a dimension among + * k-dimensions. The dimension of the split (or partition) is determined + * for each nonterminal node that has two children. The split process is + * terminated when the node has no children (when the number of + * measurement vectors is less than or equal to the size set by the + * SetBucketSize. That is The split process is a recursive process in + * nature and in implementation. This implementation doesn't support + * dynamic insert and delete operations for the tree. Instead, we can + * use the KdTreeGenerator or WeightedCentroidKdTreeGenerator to + * generate a static KdTree object. + * + * To search k-nearest neighbor, call the Search method with the query + * point in a k-d space and the number of nearest neighbors. The + * GetSearchResult method returns a pointer to a NearestNeighbors object + * with k-nearest neighbors. + * + * <b>Recent API changes:</b> + * The static const macro to get the length of a measurement vector, + * 'MeasurementVectorSize' has been removed to allow the length of a measurement + * vector to be specified at run time. Please use the function + * GetMeasurementVectorSize() instead. + + * \sa KdTreeNode, KdTreeNonterminalNode, + * KdTreeWeightedCentroidNonterminalNode, KdTreeTerminalNode, + * KdTreeGenerator, WeightedCentroidKdTreeNode + */ + +template < class TSample > +class ITK_EXPORT KdTree : public Object +{ +public: + /** Standard class typedefs */ + typedef KdTree Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro(KdTree, Object); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** typedef alias for the source data container */ + typedef TSample SampleType; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::InstanceIdentifier InstanceIdentifier; + typedef typename TSample::AbsoluteFrequencyType AbsoluteFrequencyType; + + typedef unsigned int MeasurementVectorSizeType; + + /** Get Macro to get the length of a measurement vector in the KdTree. + * The length is obtained from the input sample. */ + itkGetConstMacro( MeasurementVectorSize, MeasurementVectorSizeType ); + + /** DistanceMetric type for the distance calculation and comparison */ + typedef EuclideanDistanceMetric< MeasurementVectorType > DistanceMetricType; + + /** Node type of the KdTree */ + typedef KdTreeNode< TSample > KdTreeNodeType; + + /** Neighbor type. The first element of the std::pair is the instance + * identifier and the second one is the distance between the measurement + * vector identified by the first element and the query point. */ + typedef std::pair< InstanceIdentifier, double > NeighborType; + + typedef std::vector< InstanceIdentifier > InstanceIdentifierVectorType; + + /** \class NearestNeighbors + * \brief data structure for storing k-nearest neighbor search result + * (k number of Neighbors) + * + * This class stores the instance identifiers and the distance values + * of k-nearest neighbors. We can also query the farthest neighbor's + * distance from the query point using the GetLargestDistance + * method. + */ + class NearestNeighbors { + public: + /** Constructor */ + NearestNeighbors() {} + + /** Destructor */ + ~NearestNeighbors() {} + + /** Initialize the internal instance identifier and distance holders + * with the size, k */ + void resize(unsigned int k) + { + m_Identifiers.clear(); + m_Identifiers.resize(k, NumericTraits< unsigned long >::max()); + m_Distances.clear(); + m_Distances.resize(k, NumericTraits< double >::max()); + m_FarthestNeighborIndex = 0; + } + + /** Returns the distance of the farthest neighbor from the query point */ + double GetLargestDistance() + { + return m_Distances[m_FarthestNeighborIndex]; + } + + /** Replaces the farthest neighbor's instance identifier and + * distance value with the id and the distance */ + void ReplaceFarthestNeighbor(InstanceIdentifier id, double distance) + { + m_Identifiers[m_FarthestNeighborIndex] = id; + m_Distances[m_FarthestNeighborIndex] = distance; + double farthestDistance = NumericTraits< double >::min(); + const unsigned int size = static_cast<unsigned int>( m_Distances.size() ); + for ( unsigned int i = 0; i < size; i++ ) + { + if ( m_Distances[i] > farthestDistance ) + { + farthestDistance = m_Distances[i]; + m_FarthestNeighborIndex = i; + } + } + } + + /** Returns the vector of k-neighbors' instance identifiers */ + const InstanceIdentifierVectorType & GetNeighbors() const + { + return m_Identifiers; + } + + /** Returns the instance identifier of the index-th neighbor among + * k-neighbors */ + InstanceIdentifier GetNeighbor(unsigned int index) const + { + return m_Identifiers[index]; + } + + /** Returns the vector of k-neighbors' instance identifiers */ + const std::vector< double >& GetDistances() const + { + return m_Distances; + } + + private: + /** The index of the farthest neighbor among k-neighbors */ + unsigned int m_FarthestNeighborIndex; + + /** Storage for the instance identifiers of k-neighbors */ + InstanceIdentifierVectorType m_Identifiers; + + /** Storage for the distance values of k-neighbors from the query + * point */ + std::vector< double > m_Distances; + }; + + /** Sets the number of measurement vectors that can be stored in a + * terminal node */ + void SetBucketSize(unsigned int size); + + /** Sets the input sample that provides the measurement vectors to the k-d + * tree */ + void SetSample(const TSample* sample); + + /** Returns the pointer to the input sample */ + const TSample* GetSample() const + { + return m_Sample; + } + + unsigned long Size() const + { + return m_Sample->Size(); + } + + /** Returns the pointer to the empty terminal node. A KdTree object + * has a single empty terminal node in memory. when the split process + * has to create an empty terminal node, the single instance is reused + * for this case */ + KdTreeNodeType* GetEmptyTerminalNode() + { + return m_EmptyTerminalNode; + } + + /** Sets the root node of the KdTree that is a result of + * KdTreeGenerator or WeightedCentroidKdTreeGenerator. */ + void SetRoot(KdTreeNodeType* root) + { + m_Root = root; + } + + /** Returns the pointer to the root node. */ + KdTreeNodeType* GetRoot() + { + return m_Root; + } + + /** Returns the measurement vector identified by the instance + * identifier that is an identifier defiend for the input sample */ + const MeasurementVectorType & GetMeasurementVector(InstanceIdentifier id) const + { + return m_Sample->GetMeasurementVector(id); + } + + /** Returns the frequency of the measurement vector identified by + * the instance identifier */ + AbsoluteFrequencyType GetFrequency(InstanceIdentifier id) const + { + return m_Sample->GetFrequency( id ); + } + + /** Get the pointer to the distance metric. */ + DistanceMetricType* GetDistanceMetric() + { + return m_DistanceMetric.GetPointer(); + } + + /** Searches the k-nearest neighbors */ + void Search(const MeasurementVectorType &query, + unsigned int numberOfNeighborsRequested, + InstanceIdentifierVectorType& result) const; + + /** Searches the neighbors fallen into a hypersphere */ + void Search(const MeasurementVectorType &query, + double radius, + InstanceIdentifierVectorType& result) const; + + /** Returns the number of measurement vectors that have been visited + * to find the k-nearest neighbors. */ + int GetNumberOfVisits() const + { + return m_NumberOfVisits; + } + + /** Returns true if the intermediate k-nearest neighbors exist within + * the the bounding box defined by the lowerBound and the + * upperBound. Otherwise returns false. Returns false if the ball + * defined by the distance between the query point and the farthest + * neighbor touch the surface of the bounding box. */ + bool BallWithinBounds(const MeasurementVectorType &query, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound, + double radius) const; + + /** Returns true if the ball defined by the distance between the query + * point and the farthest neighbor overlaps with the bounding box + * defined by the lower and the upper bounds. */ + bool BoundsOverlapBall(const MeasurementVectorType &query, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound, + double radius) const; + + /** Deletes the node recursively */ + void DeleteNode(KdTreeNodeType *node); + + /** Prints out the tree information */ + void PrintTree( std::ostream & os ) const; + + /** Prints out the tree information */ + void PrintTree(KdTreeNodeType *node, unsigned int level, + unsigned int activeDimension, + std::ostream & os = std::cout ) const; + + /** Draw out the tree information to a ostream using + * the format of the Graphviz dot tool. */ + void PlotTree( std::ostream & os ) const; + + /** Prints out the tree information */ + void PlotTree(KdTreeNodeType *node, std::ostream & os = std::cout ) const; + + + typedef typename TSample::Iterator Iterator; + typedef typename TSample::ConstIterator ConstIterator; + + Iterator Begin() + { + typename TSample::ConstIterator iter = m_Sample->Begin(); + return iter; + } + + Iterator End() + { + Iterator iter = m_Sample->End(); + return iter; + } + + ConstIterator Begin() const + { + typename TSample::ConstIterator iter = m_Sample->Begin(); + return iter; + } + + ConstIterator End() const + { + ConstIterator iter = m_Sample->End(); + return iter; + } + +protected: + /** Constructor */ + KdTree(); + + /** Destructor: deletes the root node and the empty terminal node. */ + virtual ~KdTree(); + + void PrintSelf(std::ostream& os, Indent indent) const; + + /** search loop */ + int NearestNeighborSearchLoop(const KdTreeNodeType* node, + const MeasurementVectorType &query, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound) const; + + /** search loop */ + int SearchLoop(const KdTreeNodeType* node, const MeasurementVectorType &query, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound) const; +private: + KdTree(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Pointer to the input sample */ + const TSample* m_Sample; + + /** Number of measurement vectors can be stored in a terminal node. */ + int m_BucketSize; + + /** Pointer to the root node */ + KdTreeNodeType* m_Root; + + /** Pointer to the empty terminal node */ + KdTreeNodeType* m_EmptyTerminalNode; + + /** Distance metric smart pointer */ + typename DistanceMetricType::Pointer m_DistanceMetric; + + mutable bool m_IsNearestNeighborSearch; + + mutable double m_SearchRadius; + + mutable InstanceIdentifierVectorType m_Neighbors; + + /** k-nearest neighbors */ + mutable NearestNeighbors m_NearestNeighbors; + + /** Temporary lower bound in the SearchLoop. */ + mutable MeasurementVectorType m_LowerBound; + + /** Temporary upper bound in the SearchLoop. */ + mutable MeasurementVectorType m_UpperBound; + + /** Number of measurment vectors to find k-nearest neighbors. */ + mutable int m_NumberOfVisits; + + /** Flag to stop the SearchLoop. */ + mutable bool m_StopSearch; + + /** Temporary neighbor */ + mutable NeighborType m_TempNeighbor; + + /** Measurement vector size */ + MeasurementVectorSizeType m_MeasurementVectorSize; +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkKdTree.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkKdTree.txx b/Utilities/ITK/Code/Review/Statistics/itkKdTree.txx new file mode 100644 index 0000000000..283509a95c --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkKdTree.txx @@ -0,0 +1,665 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkKdTree.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:56 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkKdTree_txx +#define __itkKdTree_txx + +#include "itkKdTree.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +KdTreeNonterminalNode< TSample > +::KdTreeNonterminalNode(unsigned int partitionDimension, + MeasurementType partitionValue, + Superclass* left, + Superclass* right) +{ + m_PartitionDimension = partitionDimension; + m_PartitionValue = partitionValue; + m_Left = left; + m_Right = right; +} + +template< class TSample > +void +KdTreeNonterminalNode< TSample > +::GetParameters(unsigned int &partitionDimension, + MeasurementType &partitionValue) const +{ + partitionDimension = m_PartitionDimension; + partitionValue = m_PartitionValue; +} + +template< class TSample > +KdTreeWeightedCentroidNonterminalNode< TSample > +::KdTreeWeightedCentroidNonterminalNode(unsigned int partitionDimension, + MeasurementType partitionValue, + Superclass* left, + Superclass* right, + CentroidType ¢roid, + unsigned int size) +{ + m_PartitionDimension = partitionDimension; + m_PartitionValue = partitionValue; + m_Left = left; + m_Right = right; + m_WeightedCentroid = centroid; + m_MeasurementVectorSize = MeasurementVectorTraits::GetLength( centroid ); + + m_Centroid = m_WeightedCentroid / double(size); + + m_Size = size; +} + +template< class TSample > +void +KdTreeWeightedCentroidNonterminalNode< TSample > +::GetParameters(unsigned int &partitionDimension, + MeasurementType &partitionValue) const +{ + partitionDimension = m_PartitionDimension; + partitionValue = m_PartitionValue; +} + +template< class TSample > +KdTree< TSample > +::KdTree() +{ + m_EmptyTerminalNode = + new KdTreeTerminalNode< TSample >(); + + m_DistanceMetric = DistanceMetricType::New(); + m_Sample = 0; + m_Root = 0; + m_BucketSize = 16; + m_MeasurementVectorSize = 0; +} + +template< class TSample > +KdTree< TSample > +::~KdTree() +{ + if ( m_Root != 0 ) + { + this->DeleteNode(m_Root); + } + + delete m_EmptyTerminalNode; +} + +template< class TSample > +void +KdTree< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Input Sample: "; + if ( m_Sample != 0 ) + { + os << m_Sample << std::endl; + } + else + { + os << "not set." << std::endl; + } + + os << indent << "Bucket Size: " << m_BucketSize << std::endl; + os << indent << "Root Node: "; + if ( m_Root != 0 ) + { + os << m_Root << std::endl; + } + else + { + os << "not set." << std::endl; + } + os << indent << "MeasurementVectorSize: " << + m_MeasurementVectorSize << std::endl; +} + +template< class TSample > +void +KdTree< TSample > +::DeleteNode(KdTreeNodeType *node) +{ + if ( node->IsTerminal() ) + { + // terminal node + if (node == m_EmptyTerminalNode) + { + // empty node + return; + } + delete node; + return; + } + + // non-terminal node + if ( node->Left() != 0 ) + { + this->DeleteNode( node->Left() ); + } + + if ( node->Right() != 0 ) + { + this->DeleteNode( node->Right() ); + } + + delete node; +} + +template< class TSample > +void +KdTree< TSample > +::SetSample(const TSample* sample) +{ + m_Sample = sample; + this->m_MeasurementVectorSize = m_Sample->GetMeasurementVectorSize(); + this->m_DistanceMetric->SetMeasurementVectorSize( + this->m_MeasurementVectorSize ); + this->Modified(); +} + +template< class TSample > +void +KdTree< TSample > +::SetBucketSize(unsigned int size) +{ + m_BucketSize = size; +} + + +template< class TSample > +void +KdTree< TSample > +::Search(const MeasurementVectorType &query, unsigned int numberOfNeighborsRequested, + InstanceIdentifierVectorType& result) const +{ + if( numberOfNeighborsRequested > this->Size() ) + { + itkExceptionMacro(<<"The numberOfNeighborsRequested for the nearest neighbor search should be less than or equal to the number of the measurement vectors."); + } + + m_NearestNeighbors.resize(numberOfNeighborsRequested); + + MeasurementVectorType lowerBound; + MeasurementVectorType upperBound; + MeasurementVectorTraits::SetLength( lowerBound, m_MeasurementVectorSize ); + MeasurementVectorTraits::SetLength( upperBound, m_MeasurementVectorSize ); + + for (unsigned int d = 0; d < this->m_MeasurementVectorSize; d++) + { + lowerBound[d] = static_cast< MeasurementType >( -vcl_sqrt( -static_cast<double>( NumericTraits< MeasurementType >::NonpositiveMin() ) ) / 2.0 ); + upperBound[d] = static_cast< MeasurementType >( vcl_sqrt( static_cast<double>( NumericTraits< MeasurementType >::max() ) / 2.0 ) ); + } + + m_NumberOfVisits = 0; + m_StopSearch = false; + + this->NearestNeighborSearchLoop(m_Root, query, lowerBound, upperBound); + + m_Neighbors = m_NearestNeighbors.GetNeighbors(); + result = m_Neighbors; +} + +template< class TSample > +inline int +KdTree< TSample > +::NearestNeighborSearchLoop( const KdTreeNodeType* node, + const MeasurementVectorType &query, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound) const +{ + unsigned int i; + InstanceIdentifier tempId; + double tempDistance; + + if( node->IsTerminal() ) + { + // terminal node + if( node == m_EmptyTerminalNode ) + { + // empty node + return 0; + } + + for( i = 0; i < node->Size(); i++ ) + { + tempId = node->GetInstanceIdentifier(i); + tempDistance = + m_DistanceMetric-> + Evaluate(query, m_Sample->GetMeasurementVector(tempId)); + m_NumberOfVisits++; + if( tempDistance < m_NearestNeighbors.GetLargestDistance() ) + { + m_NearestNeighbors.ReplaceFarthestNeighbor(tempId, tempDistance); + } + } + + if ( this->BallWithinBounds(query, lowerBound, upperBound, + m_NearestNeighbors.GetLargestDistance()) ) + { + return 1; + } + + return 0; + } + + + unsigned int partitionDimension; + MeasurementType partitionValue; + MeasurementType tempValue; + node->GetParameters(partitionDimension, partitionValue); + + + // + // Check the point associated with the nonterminal node + // and potentially add it to the list of nearest neighbors + // + tempId = node->GetInstanceIdentifier(0); + tempDistance = m_DistanceMetric->Evaluate(query, m_Sample->GetMeasurementVector(tempId)); + if( tempDistance < m_NearestNeighbors.GetLargestDistance() ) + { + m_NearestNeighbors.ReplaceFarthestNeighbor(tempId, tempDistance); + } + + + // + // Now check both child sub-trees + // + if( query[partitionDimension] <= partitionValue ) + { + // search the closer child node + tempValue = upperBound[partitionDimension]; + upperBound[partitionDimension] = partitionValue; + if( NearestNeighborSearchLoop(node->Left(), query, lowerBound, upperBound) ) + { + return 1; + } + upperBound[partitionDimension] = tempValue; + + // search the other node, if necessary + tempValue = lowerBound[partitionDimension]; + lowerBound[partitionDimension] = partitionValue; + if( this->BoundsOverlapBall(query, lowerBound, upperBound, + m_NearestNeighbors.GetLargestDistance()) ) + { + NearestNeighborSearchLoop(node->Right(), query, lowerBound, upperBound); + } + lowerBound[partitionDimension] = tempValue; + } + else + { + // search the closer child node + tempValue = lowerBound[partitionDimension]; + lowerBound[partitionDimension] = partitionValue; + if (NearestNeighborSearchLoop(node->Right(), query, lowerBound, upperBound)) + { + return 1; + } + lowerBound[partitionDimension] = tempValue; + + // search the other node, if necessary + tempValue = upperBound[partitionDimension]; + upperBound[partitionDimension] = partitionValue; + if ( this->BoundsOverlapBall(query, lowerBound, upperBound, + m_NearestNeighbors.GetLargestDistance()) ) + { + NearestNeighborSearchLoop(node->Left(), query, lowerBound, upperBound); + } + upperBound[partitionDimension] = tempValue; + } + + // stop or continue search + if ( this->BallWithinBounds(query, lowerBound, upperBound, + m_NearestNeighbors.GetLargestDistance()) ) + { + return 1; + } + + return 0; +} + +template< class TSample > +void +KdTree< TSample > +::Search(const MeasurementVectorType &query, double radius, + InstanceIdentifierVectorType& result) const +{ + MeasurementVectorType lowerBound; + MeasurementVectorType upperBound; + MeasurementVectorTraits::SetLength( lowerBound, m_MeasurementVectorSize ); + MeasurementVectorTraits::SetLength( upperBound, m_MeasurementVectorSize ); + + for (unsigned int d = 0; d < this->m_MeasurementVectorSize; d++) + { + lowerBound[d] = static_cast< MeasurementType >( -vcl_sqrt( -static_cast<double>( NumericTraits< MeasurementType >::NonpositiveMin() ) ) / 2.0 ); + upperBound[d] = static_cast< MeasurementType >( vcl_sqrt( static_cast<double>( NumericTraits< MeasurementType >::max() ) / 2.0 ) ); + } + + m_NumberOfVisits = 0; + m_StopSearch = false; + + m_Neighbors.clear(); + m_SearchRadius = radius; + this->SearchLoop(m_Root, query, lowerBound, upperBound); + result = m_Neighbors; +} + +template< class TSample > +inline int +KdTree< TSample > +::SearchLoop(const KdTreeNodeType* node, + const MeasurementVectorType &query, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound) const +{ + unsigned int i; + InstanceIdentifier tempId; + double tempDistance; + + if ( node->IsTerminal() ) + { + // terminal node + if (node == m_EmptyTerminalNode) + { + // empty node + return 0; + } + + for (i = 0; i < node->Size(); i++) + { + tempId = node->GetInstanceIdentifier(i); + tempDistance = + m_DistanceMetric-> + Evaluate(query, m_Sample->GetMeasurementVector(tempId)); + m_NumberOfVisits++; + if (tempDistance < m_SearchRadius ) + { + m_Neighbors.push_back(tempId); + } + } + + if ( this->BallWithinBounds(query, lowerBound, upperBound, + m_SearchRadius) ) + { + return 1; + } + + return 0; + } + + + unsigned int partitionDimension; + MeasurementType partitionValue; + MeasurementType tempValue; + node->GetParameters(partitionDimension, partitionValue); + + if (query[partitionDimension] <= partitionValue) + { + // search the closer child node + tempValue = upperBound[partitionDimension]; + upperBound[partitionDimension] = partitionValue; + if (SearchLoop(node->Left(), query, lowerBound, upperBound)) + { + return 1; + } + upperBound[partitionDimension] = tempValue; + + // search the other node, if necessary + tempValue = lowerBound[partitionDimension]; + lowerBound[partitionDimension] = partitionValue; + if ( this->BoundsOverlapBall(query, lowerBound, upperBound, + m_SearchRadius) ) + { + SearchLoop(node->Right(), query, lowerBound, upperBound); + } + lowerBound[partitionDimension] = tempValue; + } + else + { + // search the closer child node + tempValue = lowerBound[partitionDimension]; + lowerBound[partitionDimension] = partitionValue; + if (SearchLoop(node->Right(), query, lowerBound, upperBound)) + { + return 1; + } + lowerBound[partitionDimension] = tempValue; + + // search the other node, if necessary + tempValue = upperBound[partitionDimension]; + upperBound[partitionDimension] = partitionValue; + if ( this->BoundsOverlapBall(query, lowerBound, upperBound, + m_SearchRadius) ) + { + SearchLoop(node->Left(), query, lowerBound, upperBound); + } + upperBound[partitionDimension] = tempValue; + } + + // stop or continue search + if ( this->BallWithinBounds(query, lowerBound, upperBound, + m_SearchRadius) ) + { + return 1; + } + + return 0; +} + +template< class TSample > +inline bool +KdTree< TSample > +::BallWithinBounds(const MeasurementVectorType &query, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound, + double radius) const +{ + unsigned int dimension; + for (dimension = 0; dimension < this->m_MeasurementVectorSize; dimension++) + { + if ((m_DistanceMetric->Evaluate(query[dimension] , + lowerBound[dimension]) <= + radius) || + (m_DistanceMetric->Evaluate(query[dimension] , + upperBound[dimension]) <= + radius)) + { + return false; + } + } + return true; +} + +template< class TSample > +inline bool +KdTree< TSample > +::BoundsOverlapBall(const MeasurementVectorType &query, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound, + double radius) const +{ + double sum = NumericTraits< double >::Zero; + double temp; + unsigned int dimension; + double squaredSearchRadius = radius * radius; + for (dimension = 0; dimension < m_MeasurementVectorSize; dimension++) + { + + if (query[dimension] <= lowerBound[dimension]) + { + temp = m_DistanceMetric->Evaluate(query[dimension], + lowerBound[dimension]); + sum += temp * temp; + if (sum < squaredSearchRadius) + { + return true; + } + } + else if (query[dimension] >= upperBound[dimension]) + { + temp = m_DistanceMetric->Evaluate(query[dimension], + upperBound[dimension]); + sum += temp * temp; + if (sum < squaredSearchRadius) + { + return true; + } + } + } + return false; +} + + +template< class TSample > +void +KdTree< TSample > +::PrintTree( std::ostream & os ) const +{ + const unsigned int topLevel = 0; + const unsigned int activeDimension = 0; + this->PrintTree( this->m_Root, topLevel, activeDimension, os ); +} + + +template< class TSample > +void +KdTree< TSample > +::PrintTree(KdTreeNodeType *node, unsigned int level, unsigned int activeDimension, std::ostream & os ) const +{ + level++; + if ( node->IsTerminal() ) + { + // terminal node + if (node == m_EmptyTerminalNode) + { + // empty node + os << "Empty node: level = " << level << std::endl; + return; + } + + os << "Terminal: level = " << level + << " dim = " << activeDimension<< std::endl; + os << " "; + for (unsigned int i = 0; i < node->Size(); i++) + { + os << "[" << node->GetInstanceIdentifier(i) << "] " + << m_Sample->GetMeasurementVector(node->GetInstanceIdentifier(i)) << ", "; + } + os << std::endl; + return; + } + + unsigned int partitionDimension; + MeasurementType partitionValue; + + node->GetParameters(partitionDimension, partitionValue); + typename KdTreeNodeType::CentroidType centroid; + node->GetWeightedCentroid(centroid); + os << "Nonterminal: level = " << level << std::endl; + os << " dim = " << partitionDimension << std::endl; + os << " value = " << partitionValue << std::endl; + os << " weighted centroid = " << centroid; + os << " size = " << node->Size()<< std::endl; + os << " identifier = " << node->GetInstanceIdentifier(0); + os << m_Sample->GetMeasurementVector(node->GetInstanceIdentifier(0)) << std::endl; + + this->PrintTree( node->Left(), level, partitionDimension, os ); + this->PrintTree( node->Right(), level, partitionDimension, os ); +} + + +template< class TSample > +void +KdTree< TSample > +::PlotTree( std::ostream & os ) const +{ + // + // Graph header + // + os << "digraph G {" << std::endl; + + // + // Recursively visit the tree and add entries for the nodes + // + this->PlotTree( this->m_Root, os ); + + // + // Graph footer + // + os << "}" << std::endl; +} + + +template< class TSample > +void +KdTree< TSample > +::PlotTree(KdTreeNodeType *node, std::ostream & os ) const +{ + unsigned int partitionDimension; + MeasurementType partitionValue; + + node->GetParameters(partitionDimension, partitionValue); + + KdTreeNodeType * left = node->Left(); + KdTreeNodeType * right = node->Right(); + + char partitionDimensionCharSymbol = ('X'+partitionDimension); + + if( node->IsTerminal() ) + { + // terminal node + if( node != m_EmptyTerminalNode ) + { + os << "\"" << node << "\" [label=\""; + for( unsigned int i = 0; i < node->Size(); i++ ) + { + os << this->GetMeasurementVector( node->GetInstanceIdentifier(i) ); + os << " "; + } + os << "\" ];" << std::endl; + } + } + else + { + os << "\"" << node << "\" [label=\""; + os << this->GetMeasurementVector( node->GetInstanceIdentifier(0) ); + os << " " << partitionDimensionCharSymbol << "=" << partitionValue; + os << "\" ];" << std::endl; + } + + + if( left && ( left != m_EmptyTerminalNode ) ) + { + os << "\"" << node << "\" -> \"" << left << "\";" << std::endl; + this->PlotTree( left, os ); + } + + if( right && ( right != m_EmptyTerminalNode ) ) + { + os << "\"" << node << "\" -> \"" << right << "\";" << std::endl; + this->PlotTree( right, os ); + } +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.h b/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.h new file mode 100644 index 0000000000..86a311d71b --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.h @@ -0,0 +1,324 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkKdTreeBasedKmeansEstimator.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:56 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkKdTreeBasedKmeansEstimator_h +#define __itkKdTreeBasedKmeansEstimator_h + +#include <vector> +#include "itk_hash_map.h" + +#include "itkObject.h" +#include "itkMeasurementVectorTraits.h" +#include "itkEuclideanDistanceMetric.h" +#include "itkDistanceToCentroidMembershipFunction.h" +#include "itkSimpleDataObjectDecorator.h" + +namespace itk { +namespace Statistics { + +/** \class KdTreeBasedKmeansEstimator + * \brief fast k-means algorithm implementation using k-d tree structure + * + * It returns k mean vectors that are centroids of k-clusters + * using pre-generated k-d tree. k-d tree generation is done by + * the WeightedCentroidKdTreeGenerator. The tree construction needs + * to be done only once. The resulting k-d tree's non-terminal nodes + * that have their children nodes have vector sums of measurement vectors + * that belong to the nodes and the number of measurement vectors + * in addition to the typical node boundary information and pointers to + * children nodes. Instead of reassigning every measurement vector to + * the nearest cluster centroid and recalculating centroid, it maintain + * a set of cluster centroid candidates and using pruning algorithm that + * utilizes k-d tree, it updates the means of only relevant candidates at + * each iterations. It would be faster than traditional implementation + * of k-means algorithm. However, the k-d tree consumes a large amount + * of memory. The tree construction time and pruning algorithm's performance + * are important factors to the whole process's performance. If users + * want to use k-d tree for some purpose other than k-means estimation, + * they can use the KdTreeGenerator instead of the + * WeightedCentroidKdTreeGenerator. It will save the tree construction + * time and memory usage. + * + * Note: There is a second implementation of k-means algorithm in ITK under the + * While the Kd tree based implementation is more time efficient, the GLA/LBG + * based algorithm is more memory efficient. + * + * <b>Recent API changes:</b> + * The static const macro to get the length of a measurement vector, + * \c MeasurementVectorSize has been removed to allow the length of a measurement + * vector to be specified at run time. It is now obtained from the KdTree set + * as input. You may query this length using the function GetMeasurementVectorSize(). + * + * \sa ImageKmeansModelEstimator + * \sa WeightedCentroidKdTreeGenerator, KdTree + */ + +template< class TKdTree > +class ITK_EXPORT KdTreeBasedKmeansEstimator: + public Object +{ +public: + /** Standard Self typedef. */ + typedef KdTreeBasedKmeansEstimator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(KdTreeBasedKmeansEstimator, Obeject); + + /** Types for the KdTree data structure */ + typedef typename TKdTree::KdTreeNodeType KdTreeNodeType; + typedef typename TKdTree::MeasurementType MeasurementType; + typedef typename TKdTree::MeasurementVectorType MeasurementVectorType; + typedef typename TKdTree::InstanceIdentifier InstanceIdentifier; + typedef typename TKdTree::SampleType SampleType; + typedef typename KdTreeNodeType::CentroidType CentroidType; + + + /** Typedef for the length of a measurement vector */ + typedef unsigned int MeasurementVectorSizeType; + + /** Parameters type. + * It defines a position in the optimization search space. */ + typedef Array< double > ParameterType; + typedef std::vector< ParameterType > InternalParametersType; + typedef Array< double > ParametersType; + + + /** Typedef requried to generate dataobject decorated output that can + * be plugged into SampleClassifierFilter */ + typedef DistanceToCentroidMembershipFunction< MeasurementVectorType > + DistanceToCentroidMembershipFunctionType; + + typedef typename DistanceToCentroidMembershipFunctionType::Pointer + DistanceToCentroidMembershipFunctionPointer; + + typedef MembershipFunctionBase< MeasurementVectorType > MembershipFunctionType; + typedef typename MembershipFunctionType::ConstPointer MembershipFunctionPointer; + typedef std::vector< MembershipFunctionPointer > MembershipFunctionVectorType; + typedef SimpleDataObjectDecorator< + MembershipFunctionVectorType > MembershipFunctionVectorObjectType; + typedef typename + MembershipFunctionVectorObjectType::Pointer MembershipFunctionVectorObjectPointer; + + /** Output Membership function vector containing the membership functions with + * the final optimized paramters */ + const MembershipFunctionVectorObjectType * GetOutput() const; + + /** Set the position to initialize the optimization. */ + itkSetMacro( Parameters, ParametersType ); + itkGetConstMacro( Parameters, ParametersType ); + + /** Set/Get maximum iteration limit. */ + itkSetMacro( MaximumIteration, int ); + itkGetConstMacro( MaximumIteration, int ); + + /** Set/Get the termination threshold for the squared sum + * of changes in centroid postions after one iteration */ + itkSetMacro( CentroidPositionChangesThreshold, double ); + itkGetConstMacro( CentroidPositionChangesThreshold, double ); + /** Set/Get the pointer to the KdTree */ + void SetKdTree(TKdTree* tree); + const TKdTree* GetKdTree() const; + + /** Get the length of measurement vectors in the KdTree */ + itkGetConstMacro( MeasurementVectorSize, MeasurementVectorSizeType ); + + itkGetConstMacro( CurrentIteration, int); + itkGetConstMacro( CentroidPositionChanges, double); + + /** Start optimization + * Optimization will stop when it meets either of two termination conditions, + * the maximum iteration limit or epsilon (minimal changes in squared sum + * of changes in centroid positions) */ + void StartOptimization(); + + typedef itk::hash_map< InstanceIdentifier, unsigned int > ClusterLabelsType; + + itkSetMacro( UseClusterLabels, bool ); + itkGetConstMacro( UseClusterLabels, bool ); + +protected: + KdTreeBasedKmeansEstimator(); + virtual ~KdTreeBasedKmeansEstimator() {} + + void PrintSelf(std::ostream& os, Indent indent) const; + + void FillClusterLabels(KdTreeNodeType* node, int closestIndex); + + /** \class CandidateVector */ + class CandidateVector { + public: + CandidateVector() {} + + struct Candidate { + CentroidType Centroid; + CentroidType WeightedCentroid; + int Size; + }; // end of struct + + virtual ~CandidateVector() {} + + /** returns the number of candidate = k */ + int Size() const + { + return static_cast<int>( m_Candidates.size() ); + } + + /** Initialize the centroids with the argument. + * At each iteration, this should be called before filtering. */ + void SetCentroids(InternalParametersType& centroids) + { + this->m_MeasurementVectorSize = MeasurementVectorTraits::GetLength( centroids[0] ); + m_Candidates.resize(centroids.size()); + for (unsigned int i = 0; i < centroids.size(); i++) + { + Candidate candidate; + candidate.Centroid = centroids[i]; + MeasurementVectorTraits::SetLength( candidate.WeightedCentroid, m_MeasurementVectorSize ); + candidate.WeightedCentroid.Fill(0.0); + candidate.Size = 0; + m_Candidates[i] = candidate; + } + } + + /** gets the centroids (k-means) */ + void GetCentroids(InternalParametersType& centroids) + { + unsigned int i; + centroids.resize(this->Size()); + for (i = 0; i < (unsigned int)this->Size(); i++) + { + centroids[i] = m_Candidates[i].Centroid; + } + } + + /** updates the centroids using the vector sum of measurement vectors + * that belongs to each centroid and the number of measurement vectors */ + void UpdateCentroids() + { + unsigned int i, j; + for (i = 0; i < (unsigned int)this->Size(); i++) + { + if (m_Candidates[i].Size > 0) + { + for (j = 0; j < m_MeasurementVectorSize; j++) + { + m_Candidates[i].Centroid[j] = + m_Candidates[i].WeightedCentroid[j] / + double(m_Candidates[i].Size); + } + } + } + } + + /** gets the index-th candidates */ + Candidate& operator[](int index) + { + return m_Candidates[index]; + } + + private: + /** internal storage for the candidates */ + std::vector< Candidate > m_Candidates; + + /** Length of each measurement vector */ + MeasurementVectorSizeType m_MeasurementVectorSize; + };// end of class + + /** gets the sum of squared difference between the previous position + * and current postion of all centroid. This is the primary termination + * condition for this algorithm. If the return value is less than + * the value that was set by the SetCentroidPositionChangesThreshold + * method. */ + double GetSumOfSquaredPositionChanges(InternalParametersType &previous, + InternalParametersType ¤t); + + /** get the index of the closest candidate to the measurements + * measurement vector */ + int GetClosestCandidate(ParameterType &measurements, + std::vector< int > &validIndexes); + + /** returns true if the pointA is farther than pointB to the boundary */ + bool IsFarther(ParameterType &pointA, + ParameterType &pointB, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound); + + /** recursive pruning algorithm. the validIndexes vector contains + * only the indexes of the surviving candidates for the node */ + void Filter(KdTreeNodeType* node, + std::vector< int > validIndexes, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound); + + /** copies the source parameters (k-means) to the target */ + void CopyParameters(InternalParametersType &source, InternalParametersType &target); + + /** copies the source parameters (k-means) to the target */ + void CopyParameters(ParametersType &source, InternalParametersType &target); + + /** copies the source parameters (k-means) to the target */ + void CopyParameters(InternalParametersType &source, ParametersType &target); + + /** imports the measurements measurement vector data to the point */ + void GetPoint(ParameterType &point, MeasurementVectorType measurements); + + void PrintPoint(ParameterType &point); + +private: + /** current number of iteration */ + int m_CurrentIteration; + /** maximum number of iteration. termination criterion */ + int m_MaximumIteration; + /** sum of squared centroid position changes at the current iteration */ + double m_CentroidPositionChanges; + /** threshold for the sum of squared centroid position changes. + * termination criterion */ + double m_CentroidPositionChangesThreshold; + /** pointer to the k-d tree */ + typename TKdTree::Pointer m_KdTree; + /** pointer to the euclidean distance funtion */ + typename EuclideanDistanceMetric< ParameterType >::Pointer m_DistanceMetric; + + /** k-means */ + ParametersType m_Parameters; + + CandidateVector m_CandidateVector; + + ParameterType m_TempVertex; + + bool m_UseClusterLabels; + bool m_GenerateClusterLabels; + ClusterLabelsType m_ClusterLabels; + MeasurementVectorSizeType m_MeasurementVectorSize; + MembershipFunctionVectorObjectPointer m_MembershipFunctionsObject; + +}; // end of class + +} // end of namespace Statistics + +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkKdTreeBasedKmeansEstimator.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.txx b/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.txx new file mode 100644 index 0000000000..f2b3a8a9ba --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.txx @@ -0,0 +1,506 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkKdTreeBasedKmeansEstimator.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:56 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkKdTreeBasedKmeansEstimator_txx +#define __itkKdTreeBasedKmeansEstimator_txx + +#include "itkKdTreeBasedKmeansEstimator.h" +#include "itkStatisticsAlgorithm.h" + +namespace itk { +namespace Statistics { + +template< class TKdTree > +KdTreeBasedKmeansEstimator< TKdTree > +::KdTreeBasedKmeansEstimator() +{ + m_CentroidPositionChangesThreshold = 0.0; + m_KdTree = 0; + m_UseClusterLabels = false; + m_MaximumIteration = 100; + m_DistanceMetric = EuclideanDistanceMetric< ParameterType >::New(); + + m_MembershipFunctionsObject = MembershipFunctionVectorObjectType::New(); + + m_CentroidPositionChanges = 0.0; + m_TempVertex.Fill( 0.0 ); + m_CurrentIteration = 0; + m_MeasurementVectorSize = 0; +} + +template< class TKdTree > +void +KdTreeBasedKmeansEstimator< TKdTree > +::PrintSelf( std::ostream& os, Indent indent ) const +{ + Superclass::PrintSelf(os,indent); + + + os << indent << "Current Iteration: " + << this->GetCurrentIteration() << std::endl; + os << indent << "Maximum Iteration: " + << this->GetMaximumIteration() << std::endl; + + os << indent << "Sum of Centroid Position Changes: " + << this->GetCentroidPositionChanges() << std::endl; + os << indent << "Threshold for the Sum of Centroid Position Changes: " + << this->GetCentroidPositionChangesThreshold() << std::endl; + + os << indent << "Kd Tree:"; + if ( m_KdTree.IsNotNull() ) + { + os << this->GetKdTree() << std::endl; + } + else + { + os << "not set." << std::endl; + } + + os << indent << "Parameters: " << this->GetParameters() << std::endl; + os << indent << "MeasurementVectorSize: " << this->GetMeasurementVectorSize() << std::endl; + os << indent << "UseClusterLabels: " << this->GetUseClusterLabels() << std::endl; +} + + +template< class TKdTree > +double +KdTreeBasedKmeansEstimator< TKdTree > +::GetSumOfSquaredPositionChanges(InternalParametersType &previous, + InternalParametersType ¤t) +{ + double temp; + double sum = 0.0; + unsigned int i; + + + for (i = 0; i < (unsigned int)previous.size(); i++) + { + temp = m_DistanceMetric->Evaluate(previous[i], current[i]); + sum += temp; + } + return sum; +} + +template< class TKdTree > +inline int +KdTreeBasedKmeansEstimator< TKdTree > +::GetClosestCandidate(ParameterType &measurements, + std::vector< int > &validIndexes) +{ + + int closest = 0; + double closestDistance = NumericTraits< double >::max(); + double tempDistance; + std::vector< int >::iterator iter = validIndexes.begin(); + while (iter != validIndexes.end()) + { + tempDistance = + m_DistanceMetric->Evaluate(m_CandidateVector[*iter].Centroid, + measurements); + if (tempDistance < closestDistance) + { + closest = *iter; + closestDistance = tempDistance; + } + ++iter; + } + return closest; +} + +template< class TKdTree > +inline bool +KdTreeBasedKmeansEstimator< TKdTree > +::IsFarther(ParameterType &pointA, + ParameterType &pointB, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound) +{ + // calculates the vertex of the Cell bounded by the lowerBound + // and the upperBound + for (unsigned int i = 0; i < m_MeasurementVectorSize; i++) + { + if ((pointA[i] - pointB[i]) < 0.0) + { + m_TempVertex[i] = lowerBound[i]; + } + else + { + m_TempVertex[i] = upperBound[i]; + } + } + + if (m_DistanceMetric->Evaluate(pointA, m_TempVertex) >= + m_DistanceMetric->Evaluate(pointB, m_TempVertex)) + { + return true; + } + + return false; +} + +template< class TKdTree > +inline void +KdTreeBasedKmeansEstimator< TKdTree > +::Filter(KdTreeNodeType* node, + std::vector< int > validIndexes, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound) +{ + unsigned int i, j; + typename TKdTree::InstanceIdentifier tempId; + int closest; + ParameterType individualPoint; + MeasurementVectorTraits::SetLength( individualPoint, this->m_MeasurementVectorSize ); + + if ( node->IsTerminal() ) + { + // terminal node + if (node == m_KdTree->GetEmptyTerminalNode()) + { + // empty node + return; + } + + for (i = 0; i < (unsigned int)node->Size(); i++) + { + tempId = node->GetInstanceIdentifier(i); + this->GetPoint(individualPoint, + m_KdTree->GetMeasurementVector(tempId)); + closest = + this->GetClosestCandidate(individualPoint, validIndexes); + for (j = 0; j < m_MeasurementVectorSize; j++) + { + m_CandidateVector[closest].WeightedCentroid[j] += + individualPoint[j]; + } + m_CandidateVector[closest].Size += 1; + if ( m_GenerateClusterLabels ) + { + m_ClusterLabels[tempId] = closest; + } + } + } + else + { + CentroidType centroid; + CentroidType weightedCentroid; + ParameterType closestPosition; + node->GetWeightedCentroid(weightedCentroid); + node->GetCentroid(centroid); + + + closest = + this->GetClosestCandidate(centroid, validIndexes); + closestPosition = m_CandidateVector[closest].Centroid; + std::vector< int >::iterator iter = validIndexes.begin(); + + while (iter != validIndexes.end()) + { + if (*iter != closest && + this->IsFarther(m_CandidateVector[*iter].Centroid, + closestPosition, + lowerBound, upperBound)) + { + iter = validIndexes.erase(iter); + continue; + } + + if (iter != validIndexes.end()) + { + ++iter; + } + } + + + if (validIndexes.size() == 1) + { + for (j = 0; j < m_MeasurementVectorSize; j++) + { + m_CandidateVector[closest].WeightedCentroid[j] += + weightedCentroid[j]; + } + m_CandidateVector[closest].Size += node->Size(); + if ( m_GenerateClusterLabels ) + { + this->FillClusterLabels(node, closest); + } + } + else + { + unsigned int partitionDimension; + MeasurementType partitionValue; + MeasurementType tempValue; + node->GetParameters(partitionDimension, partitionValue); + + tempValue = upperBound[partitionDimension]; + upperBound[partitionDimension] = partitionValue; + this->Filter(node->Left(), validIndexes, + lowerBound, upperBound); + upperBound[partitionDimension] = tempValue; + + tempValue = lowerBound[partitionDimension]; + lowerBound[partitionDimension] = partitionValue; + this->Filter(node->Right(), validIndexes, + lowerBound, upperBound); + lowerBound[partitionDimension] = tempValue; + } + } +} + +template< class TKdTree > +void +KdTreeBasedKmeansEstimator< TKdTree > +::FillClusterLabels(KdTreeNodeType* node, int closestIndex) +{ + unsigned int i; + + if ( node->IsTerminal() ) + { + // terminal node + if (node == m_KdTree->GetEmptyTerminalNode()) + { + // empty node + return; + } + + for (i = 0; i < (unsigned int)node->Size(); i++) + { + m_ClusterLabels[node->GetInstanceIdentifier(i)] = closestIndex; + } + } + else + { + this->FillClusterLabels(node->Left(), closestIndex); + this->FillClusterLabels(node->Right(), closestIndex); + } +} + +template< class TKdTree > +void +KdTreeBasedKmeansEstimator< TKdTree > +::CopyParameters(ParametersType &source, InternalParametersType &target) +{ + unsigned int i, j; + int index = 0; + for (i = 0; i < (unsigned int)(source.size() / m_MeasurementVectorSize); i++) + { + for (j = 0; j < m_MeasurementVectorSize; j++) + { + target[i][j] = source[index]; + ++index; + } + } +} + +template< class TKdTree > +void +KdTreeBasedKmeansEstimator< TKdTree > +::CopyParameters(InternalParametersType &source, ParametersType &target) +{ + unsigned int i, j; + int index = 0; + for (i = 0; i < (unsigned int )source.size(); i++) + { + for (j = 0; j < m_MeasurementVectorSize; j++) + { + target[index] = source[i][j]; + ++index; + } + } +} + +template< class TKdTree > +void +KdTreeBasedKmeansEstimator< TKdTree > +::CopyParameters(InternalParametersType &source, InternalParametersType &target) +{ + unsigned int i, j; + for (i = 0; i < (unsigned int)source.size(); i++) + { + for (j = 0; j < m_MeasurementVectorSize; j++) + { + target[i][j] = source[i][j]; + } + } +} + +template< class TKdTree > +void +KdTreeBasedKmeansEstimator< TKdTree > +::StartOptimization() +{ + unsigned int i; + MeasurementVectorType lowerBound; + MeasurementVectorType upperBound; + MeasurementVectorTraits::SetLength( lowerBound, this->m_MeasurementVectorSize ); + MeasurementVectorTraits::SetLength( upperBound, this->m_MeasurementVectorSize ); + + Algorithm::FindSampleBound<SampleType>(m_KdTree->GetSample(), + m_KdTree->GetSample()->Begin(), + m_KdTree->GetSample()->End(), + lowerBound, + upperBound); + + InternalParametersType previousPosition; + //previousPosition.resize(m_Parameters.size() / m_MeasurementVectorSize); + InternalParametersType currentPosition; + //currentPosition.resize(m_Parameters.size() / m_MeasurementVectorSize); + + + for( i=0; i< m_Parameters.size()/ m_MeasurementVectorSize; i++ ) + { + ParameterType m; + ParameterType m1; + MeasurementVectorTraits::SetLength(m, m_MeasurementVectorSize ); + MeasurementVectorTraits::SetLength(m1, m_MeasurementVectorSize ); + previousPosition.push_back( m ); + currentPosition.push_back( m1 ); + } + + + this->CopyParameters(m_Parameters, currentPosition); + m_CurrentIteration = 0; + std::vector< int > validIndexes; + + for (i = 0; i < (unsigned int)(m_Parameters.size() / m_MeasurementVectorSize); i++) + { + validIndexes.push_back(i); + } + + m_GenerateClusterLabels = false; + + while(true) + { + this->CopyParameters(currentPosition, previousPosition); + m_CandidateVector.SetCentroids(currentPosition); + this->Filter(m_KdTree->GetRoot(), validIndexes, + lowerBound, upperBound); + m_CandidateVector.UpdateCentroids(); + m_CandidateVector.GetCentroids(currentPosition); + + if(m_CurrentIteration >= m_MaximumIteration) + { + break; + } + + m_CentroidPositionChanges = + this->GetSumOfSquaredPositionChanges(previousPosition, + currentPosition); + if (m_CentroidPositionChanges <= m_CentroidPositionChangesThreshold) + { + break; + } + + m_CurrentIteration++; + } + + if ( m_UseClusterLabels ) + { + m_GenerateClusterLabels = true; + m_ClusterLabels.clear(); + m_ClusterLabels.resize(m_KdTree->GetSample()->Size()); + for (i = 0; i < (unsigned int)(m_Parameters.size() / m_MeasurementVectorSize); i++) + { + validIndexes.push_back(i); + } + + this->Filter(m_KdTree->GetRoot(), validIndexes, + lowerBound, upperBound); + } + + this->CopyParameters(currentPosition, m_Parameters); +} + +template< class TKdTree > +void +KdTreeBasedKmeansEstimator< TKdTree > +::SetKdTree(TKdTree* tree) +{ + m_KdTree = tree; + m_MeasurementVectorSize = tree->GetMeasurementVectorSize(); + m_DistanceMetric->SetMeasurementVectorSize( m_MeasurementVectorSize ); + MeasurementVectorTraits::SetLength( m_TempVertex, m_MeasurementVectorSize ); + this->Modified(); +} + +template< class TKdTree > +const TKdTree * +KdTreeBasedKmeansEstimator< TKdTree > +::GetKdTree() const +{ + return m_KdTree.GetPointer(); +} + +template< class TKdTree > +const typename KdTreeBasedKmeansEstimator< TKdTree >::MembershipFunctionVectorObjectType * +KdTreeBasedKmeansEstimator< TKdTree > +::GetOutput() const +{ + //INSERT CHECKS if all the required inputs are set and optmization has been run. + unsigned int numberOfClasses = m_Parameters.size() / m_MeasurementVectorSize; + MembershipFunctionVectorType & membershipFunctionsVector = m_MembershipFunctionsObject->Get(); + + for( unsigned int i=0; i < numberOfClasses; i++ ) + { + DistanceToCentroidMembershipFunctionPointer membershipFunction = + DistanceToCentroidMembershipFunctionType::New(); + membershipFunction->SetMeasurementVectorSize( m_MeasurementVectorSize ); + typename DistanceToCentroidMembershipFunctionType::CentroidType centroid; + centroid.SetSize( m_MeasurementVectorSize ); + for(unsigned int j=0; j < m_MeasurementVectorSize; j++) + { + unsigned int parameterIndex = i*m_MeasurementVectorSize+j; + centroid[j] = m_Parameters[parameterIndex]; + } + membershipFunction->SetCentroid( centroid ); + membershipFunctionsVector.push_back( membershipFunction.GetPointer() ); + } + + return static_cast< const MembershipFunctionVectorObjectType*>(m_MembershipFunctionsObject); +} + +template< class TKdTree > +void +KdTreeBasedKmeansEstimator< TKdTree > +:: +GetPoint(ParameterType &point, + MeasurementVectorType measurements) +{ + for (unsigned int i = 0; i < m_MeasurementVectorSize; i++) + { + point[i] = measurements[i]; + } +} + +template< class TKdTree > +void +KdTreeBasedKmeansEstimator< TKdTree > +:: +PrintPoint(ParameterType &point) +{ + std::cout << "[ "; + for (unsigned int i = 0; i < m_MeasurementVectorSize; i++) + { + std::cout << point[i] << " "; + } + std::cout << "]"; +} + + +} // end of namespace Statistics +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkKdTreeGenerator.h b/Utilities/ITK/Code/Review/Statistics/itkKdTreeGenerator.h new file mode 100644 index 0000000000..a9a1ca414a --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkKdTreeGenerator.h @@ -0,0 +1,204 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkKdTreeGenerator.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:56 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkKdTreeGenerator_h +#define __itkKdTreeGenerator_h + +#include <vector> +#include "itkMacro.h" +#include "itkPoint.h" +#include "itkSize.h" +#include "itkObject.h" + +#include "itkSample.h" +#include "itkSubsample.h" +#include "itkKdTree.h" +#include "itkStatisticsAlgorithm.h" + +namespace itk { +namespace Statistics { + +/** \class KdTreeGenerator + * \brief This class generates a KdTree object without centroid information. + * + * The KdTree object stores measurment vectors in a k-d tree structure + * that is a binary tree. The partition value is the median value of one + * of the k dimension (partition dimension). The partition dimension is + * determined by the spread of measurement values in each dimension. The + * partition dimension is the dimension has the widest spread. Our + * implementation of k-d tree doesn't have any construction or insertion + * logic. Users should use this class or the + * WeightedCentroidKdTreeGenerator class. + * + * The number of the measurement vectors in a terminal node is set by + * the SetBucketSize method. If we use too small number for this, it + * might cause computational overhead to calculate bound + * conditions. However, too large number will cause more distance + * calculation between the measurement vectors in a terminal node and + * the query point. + * + * To run this generator, users should provides the bucket size + * (SetBucketSize method) and the input sample (SetSample method). The + * Update method will run this generator. To get the resulting KdTree + * object, call the GetOutput method. + + * <b>Recent API changes:</b> + * The static const macro to get the length of a measurement vector, + * 'MeasurementVectorSize' has been removed to allow the length of a measurement + * vector to be specified at run time. It is now obtained from the sample set + * as input. You may query this length using the function GetMeasurementVectorSize(). + * + * \sa KdTree, KdTreeNode, KdTreeNonterminalNode, KdTreeTerminalNode, + * WeightedCentroidKdTreeGenerator + */ + +template < class TSample > +class ITK_EXPORT KdTreeGenerator : public Object +{ +public: + /** Standard class typedefs */ + typedef KdTreeGenerator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro(KdTreeGenerator, Object); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** typedef alias for the source data container */ + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename TSample::MeasurementType MeasurementType; + + /** Typedef for the length of each measurement vector */ + typedef unsigned int MeasurementVectorSizeType; + + /** Typedef for the k-d tree */ + typedef KdTree< TSample > KdTreeType; + + /** Type alias for the k-d tree type */ + typedef KdTreeType OutputType; + + /** Typedef for the smart pointer to the k-d tree */ + typedef typename KdTreeType::Pointer OutputPointer; + + /** Typedef for the k-d tree node type */ + typedef typename KdTreeType::KdTreeNodeType KdTreeNodeType; + + /** Typedef for the internal Subsample */ + typedef Subsample< TSample > SubsampleType; + + /** Typedef for the smart pointer to the Subsample */ + typedef typename SubsampleType::Pointer SubsamplePointer; + + /** Sets the input sample that provides the measurement vectors. */ + void SetSample(TSample* sample); + + /** Sets the number of measurement vectors that can be stored in a + * terminal node. */ + void SetBucketSize(unsigned int size); + + /** Returns the pointer to the generated k-d tree. */ + OutputPointer GetOutput() + { + return m_Tree; + } + + /** Runs this k-d tree construction algorithm. */ + void Update() + { + this->GenerateData(); + } + + /** Runs this k-d tree construction algorithm. */ + void GenerateData(); + + /** Get macro to get the length of the measurement vectors that are being + * held in the 'sample' that is passed to this class */ + itkGetConstMacro( MeasurementVectorSize, unsigned int ); + +protected: + /** Constructor */ + KdTreeGenerator(); + + /** Destructor */ + virtual ~KdTreeGenerator() {} + + void PrintSelf(std::ostream& os, Indent indent) const; + + /** Returns the smart pointer to the internal Subsample object. */ + SubsamplePointer GetSubsample() + { + return m_Subsample; + } + + /** Nonterminal node generation routine */ + virtual KdTreeNodeType* GenerateNonterminalNode(unsigned int beginIndex, + unsigned int endIndex, + MeasurementVectorType + &lowerBound, + MeasurementVectorType + &upperBound, + unsigned int level); + + /** Tree generation loop */ + KdTreeNodeType* GenerateTreeLoop(unsigned int beginIndex, unsigned int endIndex, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound, + unsigned int level); + +private: + KdTreeGenerator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Pointer to the input (source) sample */ + TSample* m_SourceSample; + + /** Smart pointer to the internal Subsample object. This class needs + * a Subsample object because the partitioning process involves sorting + * and selection. */ + SubsamplePointer m_Subsample; + + /** The number of measurement vectors that can be stored in a terminal + * node. */ + unsigned int m_BucketSize; + + /** Pointer to the resulting k-d tree. */ + OutputPointer m_Tree; + + /** Temporary lower bound for the TreeGenerationLoop */ + MeasurementVectorType m_TempLowerBound; + + /** Temporary upper bound for the TreeGenerationLoop */ + MeasurementVectorType m_TempUpperBound; + + /** Temporary mean for the TreeGenerationLoop */ + MeasurementVectorType m_TempMean; + + /** Length of a measurement vector */ + MeasurementVectorSizeType m_MeasurementVectorSize; +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkKdTreeGenerator.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkKdTreeGenerator.txx b/Utilities/ITK/Code/Review/Statistics/itkKdTreeGenerator.txx new file mode 100644 index 0000000000..a7674171f9 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkKdTreeGenerator.txx @@ -0,0 +1,245 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkKdTreeGenerator.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:56 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkKdTreeGenerator_txx +#define __itkKdTreeGenerator_txx + +namespace itk { +namespace Statistics { + +template< class TSample > +KdTreeGenerator< TSample > +::KdTreeGenerator() +{ + m_SourceSample = 0; + m_BucketSize = 16; + m_Subsample = SubsampleType::New(); + m_MeasurementVectorSize = 0; +} + +template< class TSample > +void +KdTreeGenerator< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Source Sample: "; + if ( m_SourceSample != 0 ) + { + os << m_SourceSample << std::endl; + } + else + { + os << "not set." << std::endl; + } + + os << indent << "Bucket Size: " << m_BucketSize << std::endl; + os << indent << "MeasurementVectorSize: " << + m_MeasurementVectorSize << std::endl; +} + +template< class TSample > +void +KdTreeGenerator< TSample > +::SetSample(TSample* sample) +{ + m_SourceSample = sample; + m_Subsample->SetSample(sample); + m_Subsample->InitializeWithAllInstances(); + m_MeasurementVectorSize = sample->GetMeasurementVectorSize(); + MeasurementVectorTraits::SetLength( m_TempLowerBound, m_MeasurementVectorSize ); + MeasurementVectorTraits::SetLength( m_TempUpperBound, m_MeasurementVectorSize ); + MeasurementVectorTraits::SetLength( m_TempMean, m_MeasurementVectorSize ); +} + + +template< class TSample > +void +KdTreeGenerator< TSample > +::SetBucketSize(unsigned int size) +{ + m_BucketSize = size; +} + +template< class TSample > +void +KdTreeGenerator< TSample > +::GenerateData() +{ + if ( m_SourceSample == 0 ) + { + return; + } + + if ( m_Tree.IsNull() ) + { + m_Tree = KdTreeType::New(); + m_Tree->SetSample(m_SourceSample); + m_Tree->SetBucketSize(m_BucketSize); + } + + MeasurementVectorType lowerBound; + MeasurementVectorTraits::SetLength( lowerBound, m_MeasurementVectorSize ); + MeasurementVectorType upperBound; + MeasurementVectorTraits::SetLength( upperBound, m_MeasurementVectorSize ); + + for(unsigned int d = 0; d < m_MeasurementVectorSize; d++) + { + lowerBound[d] = NumericTraits< MeasurementType >::NonpositiveMin(); + upperBound[d] = NumericTraits< MeasurementType >::max(); + } + + KdTreeNodeType* root = + this->GenerateTreeLoop(0, m_Subsample->Size(), lowerBound, upperBound, 0); + m_Tree->SetRoot(root); +} + +template< class TSample > +inline typename KdTreeGenerator< TSample >::KdTreeNodeType* +KdTreeGenerator< TSample > +::GenerateNonterminalNode(unsigned int beginIndex, + unsigned int endIndex, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound, + unsigned int level) +{ + typedef typename KdTreeType::KdTreeNodeType NodeType; + MeasurementType dimensionLowerBound; + MeasurementType dimensionUpperBound; + MeasurementType partitionValue; + unsigned int partitionDimension = 0; + unsigned int i; + MeasurementType spread; + MeasurementType maxSpread; + unsigned int medianIndex; + + SubsamplePointer subsample = this->GetSubsample(); + + // Sanity check. Verify that the subsample has measurement vectors of the + // same length as the sample generated by the tree. + if( this->GetMeasurementVectorSize() != subsample->GetMeasurementVectorSize() ) + { + itkExceptionMacro( << "Measurement Vector Length mismatch" ); + } + + // find most widely spread dimension + Algorithm::FindSampleBoundAndMean< SubsampleType >(subsample, + beginIndex, endIndex, + m_TempLowerBound, m_TempUpperBound, + m_TempMean); + + maxSpread = NumericTraits< MeasurementType >::NonpositiveMin(); + for (i = 0; i < m_MeasurementVectorSize; i++) + { + spread = m_TempUpperBound[i] - m_TempLowerBound[i]; + if (spread >= maxSpread) + { + maxSpread = spread; + partitionDimension = i; + } + } + + + medianIndex = (endIndex - beginIndex) / 2; + + // + // Find the medial element by using the NthElement function + // based on the STL implementation of the QuickSelect algorithm. + // + partitionValue = + Algorithm::NthElement< SubsampleType >(m_Subsample, + partitionDimension, + beginIndex, endIndex, + medianIndex); + + medianIndex += beginIndex; + + // save bounds for cutting dimension + dimensionLowerBound = lowerBound[partitionDimension]; + dimensionUpperBound = upperBound[partitionDimension]; + + upperBound[partitionDimension] = partitionValue; + const unsigned int beginLeftIndex = beginIndex; + const unsigned int endLeftIndex = medianIndex; + NodeType* left = GenerateTreeLoop(beginLeftIndex, endLeftIndex, lowerBound, upperBound, level + 1); + upperBound[partitionDimension] = dimensionUpperBound; + + lowerBound[partitionDimension] = partitionValue; + const unsigned int beginRightIndex = medianIndex+1; + const unsigned int endRightIndex = endIndex; + NodeType* right = GenerateTreeLoop(beginRightIndex, endRightIndex, lowerBound, upperBound, level + 1); + lowerBound[partitionDimension] = dimensionLowerBound; + + + typedef KdTreeNonterminalNode< TSample > KdTreeNonterminalNodeType; + + KdTreeNonterminalNodeType * nonTerminalNode = + new KdTreeNonterminalNodeType( partitionDimension, + partitionValue, + left, + right); + + nonTerminalNode->AddInstanceIdentifier( + subsample->GetInstanceIdentifier( medianIndex ) ); + + return nonTerminalNode; +} + +template< class TSample > +inline typename KdTreeGenerator< TSample >::KdTreeNodeType* +KdTreeGenerator< TSample > +::GenerateTreeLoop(unsigned int beginIndex, + unsigned int endIndex, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound, + unsigned int level) +{ + if (endIndex - beginIndex <= m_BucketSize) + { + + // numberOfInstances small, make a terminal node + if (endIndex == beginIndex) + { + // return the pointer to empty terminal node + return m_Tree->GetEmptyTerminalNode(); + } + else + { + KdTreeTerminalNode< TSample >* ptr = + new KdTreeTerminalNode< TSample >(); + + for (unsigned int j = beginIndex; j < endIndex; j++) + { + ptr->AddInstanceIdentifier( + this->GetSubsample()->GetInstanceIdentifier(j)); + } + + // return a terminal node + return ptr; + } + } + else + { + return this->GenerateNonterminalNode(beginIndex, endIndex, + lowerBound, upperBound, level + 1); + } +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkListSample.h b/Utilities/ITK/Code/Review/Statistics/itkListSample.h new file mode 100644 index 0000000000..d86c56990e --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkListSample.h @@ -0,0 +1,289 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkListSample.h,v $ + Language: C++ + Date: $Date: 2009-05-22 12:55:02 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkListSample_h +#define __itkListSample_h + +#include "itkObjectFactory.h" +#include "itkFixedArray.h" +#include "itkSample.h" + +#include <vector> + +namespace itk { +namespace Statistics { + +/** \class ListSample + * \brief This class is the native implementation of the a Sample with an STL container + * + * ListSample stores measurements in a list type structure (as opposed to a + * Histogram, etc.). ListSample allows duplicate measurements. ListSample is + * not sorted. + * + * ListSample does not allow the user to specify the frequency of + * a measurement directly. The GetFrequency() methods returns 1 if + * the measurement exists in the list, 0 otherwise. + * + *\sa Sample, Histogram + */ + +template< class TMeasurementVector > +class ITK_EXPORT ListSample : public Sample< TMeasurementVector > +{ +public: + /** Standard class typedef. */ + typedef ListSample Self; + typedef Sample< TMeasurementVector > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Standard macros */ + itkTypeMacro(ListSample, Sample); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Typedefs inherited from the superclass */ + itkSuperclassTraitMacro( MeasurementVectorType ) + itkSuperclassTraitMacro( MeasurementVectorSizeType ) + itkSuperclassTraitMacro( MeasurementType ) + itkSuperclassTraitMacro( AbsoluteFrequencyType ) + itkSuperclassTraitMacro( TotalAbsoluteFrequencyType ) + itkSuperclassTraitMacro( InstanceIdentifier ) + + /** Value type of a measurement (component of the measurement + * vector) */ + typedef MeasurementVectorType ValueType; + + + /** internal data container type */ + typedef std::vector< MeasurementVectorType > InternalDataContainerType; + + /** Resize the container. Using Resize() and then SetMeasurementVector() is + * about nine times faster than usign PushBack() continously. Which means that + * whenever the total number of Measurement vectors is known, the users + * should prefer calling Resize() first and then set the values by calling + * SetMeasurementVector(). On the other hand, if the number of measurement + * vectors is not known from the beginning, then calling PushBack() + * sequentially is a convenient option. */ + void Resize( InstanceIdentifier newsize ); + + /** Removes all the elements in the Sample */ + void Clear(); + + /** Inserts a measurement at the end of the list */ + void PushBack( const MeasurementVectorType & mv ); + + /** Get the number of measurement vectors in the sample */ + InstanceIdentifier Size() const; + + /** Get the measurement associated with the specified + * InstanceIdentifier */ + const MeasurementVectorType & GetMeasurementVector(InstanceIdentifier id) const; + + /** Set a component a measurement to a particular value. */ + void SetMeasurement(InstanceIdentifier id, + unsigned int dim, + const MeasurementType &value); + + /** Replace a measurement with a different measurement */ + void SetMeasurementVector( InstanceIdentifier id, + const MeasurementVectorType &mv); + + /** Get the frequency of a measurement. Returns 1 if the measurement + * exist. */ + AbsoluteFrequencyType GetFrequency( InstanceIdentifier id ) const; + + /** Get the total frequency of the sample. This is equivalent to + * the size of the sample. */ + TotalAbsoluteFrequencyType GetTotalFrequency() const; + + /** Method to graft another sample */ + virtual void Graft( const DataObject *thatObject ); + + /** \class ListSample::ConstIterator */ + class ConstIterator + { + friend class ListSample; + + public: + + ConstIterator( const ListSample * sample ) + { + *this = sample->Begin(); + } + + ConstIterator(const ConstIterator &iter) + { + m_Iter = iter.m_Iter; + m_InstanceIdentifier = iter.m_InstanceIdentifier; + } + + ConstIterator& operator=( const ConstIterator & iter ) + { + m_Iter = iter.m_Iter; + m_InstanceIdentifier = iter.m_InstanceIdentifier; + return *this; + } + + + AbsoluteFrequencyType GetFrequency() const + { + return 1; + } + + const MeasurementVectorType & GetMeasurementVector() const + { + return static_cast<const MeasurementVectorType&>(*m_Iter); + } + + InstanceIdentifier GetInstanceIdentifier() const + { + return m_InstanceIdentifier; + } + + ConstIterator& operator++() + { + ++m_Iter; + ++m_InstanceIdentifier; + return *this; + } + + bool operator!=(const ConstIterator &it) + { + return (m_Iter != it.m_Iter); + } + + bool operator==(const ConstIterator &it) + { + return (m_Iter == it.m_Iter); + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // This method should only be available to the ListSample class + ConstIterator( + typename InternalDataContainerType::const_iterator iter, + InstanceIdentifier iid) + { + m_Iter = iter; + m_InstanceIdentifier = iid; + } + + // This method is purposely not implemented + ConstIterator(); + + private: + typedef typename InternalDataContainerType::const_iterator InternalIterator; + InternalIterator m_Iter; + InstanceIdentifier m_InstanceIdentifier; + + }; + + /** \class ListSample::Iterator */ + class Iterator : public ConstIterator + { + + friend class ListSample; + + public: + + Iterator(Self * sample):ConstIterator(sample) + { + } + + Iterator(const Iterator &iter):ConstIterator( iter ) + { + } + + Iterator& operator =(const Iterator & iter) + { + this->ConstIterator::operator=( iter ); + return *this; + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // To ensure const-correctness these method must not be in the public API. + // The are purposly not implemented, since they should never be called. + Iterator(); + Iterator(const Self * sample); + Iterator( typename InternalDataContainerType::const_iterator iter, InstanceIdentifier iid); + Iterator(const ConstIterator & it); + ConstIterator& operator=(const ConstIterator& it); + Iterator( + typename InternalDataContainerType::iterator iter, + InstanceIdentifier iid):ConstIterator( iter, iid ) + { + } + + private: + }; + + + /** returns an iterator that points to the beginning of the container */ + Iterator Begin() + { + Iterator iter(m_InternalContainer.begin(), 0); + return iter; + } + + /** returns an iterator that points to the end of the container */ + Iterator End() + { + Iterator iter(m_InternalContainer.end(), m_InternalContainer.size()); + return iter; + } + + /** returns an iterator that points to the beginning of the container */ + ConstIterator Begin() const + { + ConstIterator iter(m_InternalContainer.begin(), 0); + return iter; + } + + /** returns an iterator that points to the end of the container */ + ConstIterator End() const + { + ConstIterator iter(m_InternalContainer.end(), m_InternalContainer.size()); + return iter; + } + +protected: + + ListSample(); + virtual ~ListSample() {} + void PrintSelf(std::ostream& os, Indent indent) const; + + +private: + ListSample(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + InternalDataContainerType m_InternalContainer; + +}; + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkListSample.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkListSample.txx b/Utilities/ITK/Code/Review/Statistics/itkListSample.txx new file mode 100644 index 0000000000..a4ee816be8 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkListSample.txx @@ -0,0 +1,162 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkListSample.txx,v $ + Language: C++ + Date: $Date: 2009-05-04 15:47:46 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkListSample_txx +#define __itkListSample_txx + +#include "itkListSample.h" + +namespace itk { +namespace Statistics { + +template< class TMeasurementVector > +ListSample< TMeasurementVector > +::ListSample() +{ +} + +template< class TMeasurementVector > +void +ListSample< TMeasurementVector > +::Resize( InstanceIdentifier newsize ) +{ + this->m_InternalContainer.resize( newsize ); +} + + +template< class TMeasurementVector > +void +ListSample< TMeasurementVector > +::Clear() +{ + this->m_InternalContainer.clear(); +} + +template< class TMeasurementVector > +void +ListSample< TMeasurementVector > +::PushBack( const MeasurementVectorType & mv ) +{ + if( this->GetMeasurementVectorSize() != MeasurementVectorTraits::GetLength( mv ) ) + { + itkExceptionMacro("MeasurementVector instance doesn't match MeasurementVectorSize"); + } + this->m_InternalContainer.push_back( mv ); +} + +template< class TMeasurementVector > +typename ListSample< TMeasurementVector >::InstanceIdentifier +ListSample< TMeasurementVector > +::Size() const +{ + return static_cast<InstanceIdentifier>( + this->m_InternalContainer.size() ); +} + +template< class TMeasurementVector > +typename ListSample< TMeasurementVector >::TotalAbsoluteFrequencyType +ListSample< TMeasurementVector > +::GetTotalFrequency() const +{ + // Since the entries are unique, the total + // frequency is equal to the numbe of entries. + return this->Size(); +} + + +template< class TMeasurementVector > +const typename ListSample< TMeasurementVector >::MeasurementVectorType & +ListSample< TMeasurementVector > +::GetMeasurementVector(InstanceIdentifier instanceId) const +{ + if ( instanceId < m_InternalContainer.size() ) + { + return m_InternalContainer[instanceId]; + } + itkExceptionMacro("MeasurementVector " << instanceId << " does not exist"); +} + +template< class TMeasurementVector > +void +ListSample< TMeasurementVector > +::SetMeasurement( InstanceIdentifier instanceId, + unsigned int dim, + const MeasurementType &value) +{ + if ( instanceId < m_InternalContainer.size() ) + { + m_InternalContainer[instanceId][dim] = value; + } +} + +template< class TMeasurementVector > +void +ListSample< TMeasurementVector > +::SetMeasurementVector( InstanceIdentifier instanceId, + const MeasurementVectorType &mv) +{ + if ( instanceId < m_InternalContainer.size() ) + { + m_InternalContainer[instanceId] = mv; + } +} + +template< class TMeasurementVector > +typename ListSample< TMeasurementVector >::AbsoluteFrequencyType +ListSample< TMeasurementVector > +::GetFrequency( InstanceIdentifier instanceId ) const +{ + if ( instanceId < m_InternalContainer.size() ) + { + return 1; + } + else + { + return 0; + } +} + +template< class TMeasurementVector > +void +ListSample< TMeasurementVector > +::Graft( const DataObject *thatObject ) +{ + this->Superclass::Graft(thatObject); + + const Self *thatConst = dynamic_cast< const Self * >(thatObject); + if (thatConst) + { + Self *that = const_cast< Self * >(thatConst); + this->m_InternalContainer = that->m_InternalContainer; + } +} + +template< class TMeasurementVector > +void +ListSample< TMeasurementVector > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Internal Data Container: " + << &m_InternalContainer << std::endl; + os << indent << "Number of samples: " + << this->m_InternalContainer.size() << std::endl; +} +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMembershipFunction.h b/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMembershipFunction.h new file mode 100644 index 0000000000..0e738bd20f --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMembershipFunction.h @@ -0,0 +1,143 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMahalanobisDistanceMembershipFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-10 18:52:26 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMahalanobisDistanceMembershipFunction_h +#define __itkMahalanobisDistanceMembershipFunction_h + +#include <vnl/vnl_vector.h> +#include <vnl/vnl_vector_ref.h> +#include <vnl/vnl_transpose.h> +#include <vnl/vnl_matrix.h> +#include <vnl/algo/vnl_matrix_inverse.h> +#include <vnl/algo/vnl_determinant.h> +#include "itkArray.h" + +#include "itkMembershipFunctionBase.h" + + +namespace itk { +namespace Statistics { + +/** \class MahalanobisDistanceMembershipFunction + * \brief MahalanobisDistanceMembershipFunction class represents MahalanobisDistance Density Function. + * + * This class keeps parameter to define MahalanobisDistance Density Function and has + * method to return the probability density + * of an instance. MeasurementVectorSize is the dimension of measurement space. + * double is type of measurement. + */ + +template< class TVector > +class ITK_EXPORT MahalanobisDistanceMembershipFunction : + public MembershipFunctionBase< TVector > +{ +public: + /** Standard class typedefs */ + typedef MahalanobisDistanceMembershipFunction Self; + typedef MembershipFunctionBase< TVector > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Strandard macros */ + itkTypeMacro(MahalanobisDistanceMembershipFunction, MembershipFunctionBase); + itkNewMacro(Self); + + /** Typedef alias for the measurement vectors */ + typedef TVector MeasurementVectorType; + + /** Typedef to represent the length of measurement vectors */ + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + + /** Type used for representing the mean vector */ + typedef vnl_vector<double> MeanVectorType; + + /** Type used for representing the covariance matrix */ + typedef vnl_matrix<double> CovarianceMatrixType; + + /** Set the length of each measurement vector. */ + virtual void SetMeasurementVectorSize( MeasurementVectorSizeType ); + + /** Method to set mean */ + void SetMean(const MeanVectorType &mean); + void SetMean(const Array< double > &mean); + + /** Method to get mean */ + const MeanVectorType & GetMean() const; + + /** + * Method to set covariance matrix + * Also, this function calculates inverse covariance and pre factor of + * MahalanobisDistance Distribution to speed up GetProbability */ + void SetCovariance(const CovarianceMatrixType &cov); + + /** Method to get covariance matrix */ + itkGetConstReferenceMacro( Covariance, CovarianceMatrixType ); + + /** + * Method to set covariance matrix + * Also, this function calculates inverse covariance and pre factor of + * MahalanobisDistance Distribution to speed up GetProbability */ + void SetInverseCovariance(const CovarianceMatrixType &invcov); + + /** Method to get covariance matrix */ + itkGetConstReferenceMacro( InverseCovariance, CovarianceMatrixType ); + + /** Method to set the number of samples */ + itkSetMacro( NumberOfSamples, double ); + + /** Method to get the number of samples */ + itkGetConstMacro( NumberOfSamples, double ); + + /** + * Method to get probability of an instance. The return value is the + * value of the density function, not probability. */ + double Evaluate(const MeasurementVectorType &measurement) const; + +protected: + MahalanobisDistanceMembershipFunction(void); + virtual ~MahalanobisDistanceMembershipFunction(void) {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + MeanVectorType m_Mean; // mean + CovarianceMatrixType m_Covariance; // covariance matrix + + // inverse covariance matrix which is automatically calculated + // when covariace matirx is set. This speed up the GetProbability() + CovarianceMatrixType m_InverseCovariance; + + // Number of samples defining this density + double m_NumberOfSamples; + // pre_factor which is automatically calculated + // when covariace matirx is set. This speeds up the GetProbability() + double m_PreFactor; + double m_Epsilon; + double m_DoubleMax; + + mutable vnl_matrix< double > m_TempVec; + mutable vnl_matrix< double > m_TempMat; + + void CalculateInverseCovariance(); +}; + +} // end of namespace Statistics +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkMahalanobisDistanceMembershipFunction.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMembershipFunction.txx b/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMembershipFunction.txx new file mode 100644 index 0000000000..25952f7e5f --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMembershipFunction.txx @@ -0,0 +1,257 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMahalanobisDistanceMembershipFunction.txx,v $ + Language: C++ + Date: $Date: 2009-05-04 16:31:03 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMahalanobisDistanceMembershipFunction_txx +#define __itkMahalanobisDistanceMembershipFunction_txx + +#include "itkMahalanobisDistanceMembershipFunction.h" + +namespace itk { +namespace Statistics { + +template < class TVector > +MahalanobisDistanceMembershipFunction< TVector > +::MahalanobisDistanceMembershipFunction(): + m_NumberOfSamples(0), + m_PreFactor(0), + m_Epsilon( 1e-100 ), + m_DoubleMax( 1e+20 ) +{ + m_Mean.fill( 0.0f ); + m_Covariance.set_identity(); + m_InverseCovariance.set_identity(); + this->m_MeasurementVectorSize = 0; +} + +template< class TVector > +void +MahalanobisDistanceMembershipFunction< TVector > +::SetMeasurementVectorSize( MeasurementVectorSizeType s ) +{ + if( s == this->m_MeasurementVectorSize ) + { + return; + } + + if( this->m_MeasurementVectorSize != 0 ) + { + itkWarningMacro( << "Destructively resizing paramters of the DistanceToCentroidMembershipFunction." ); + } + this->m_MeasurementVectorSize = s; + m_Mean.set_size( s ); + this->Modified(); +} + +template < class TVector > +void +MahalanobisDistanceMembershipFunction< TVector > +::SetMean(const MeanVectorType & mean) +{ + if( this->m_MeasurementVectorSize != 0 ) + { + if( mean.size() != this->m_MeasurementVectorSize ) + { + itkExceptionMacro( << "Size of the centroid must be same as the length of" + << " each measurement vector."); + } + } + else + { + this->m_MeasurementVectorSize = mean.size(); + } + + m_Mean = mean; +} + + +template < class TVector > +void +MahalanobisDistanceMembershipFunction< TVector > +::SetMean(const Array< double > & mean) +{ + if( this->m_MeasurementVectorSize != 0 ) + { + if( mean.Size() != this->m_MeasurementVectorSize ) + { + itkExceptionMacro( << "Size of the centroid must be same as the length of" + << " each measurement vector."); + } + } + else + { + this->m_MeasurementVectorSize = mean.Size(); + } + + m_Mean = dynamic_cast< MeanVectorType & >(const_cast< Array< double >& >(mean)); +} + + +template < class TVector > +const typename +MahalanobisDistanceMembershipFunction< TVector >::MeanVectorType & +MahalanobisDistanceMembershipFunction< TVector > +::GetMean() const +{ + return m_Mean; +} + +template < class TVector > +void +MahalanobisDistanceMembershipFunction< TVector > +::SetCovariance(const CovarianceMatrixType &cov) +{ + if( this->m_MeasurementVectorSize != 0 ) + { + if( cov.rows() != this->m_MeasurementVectorSize || + cov.cols() != this->m_MeasurementVectorSize ) + { + itkExceptionMacro( << "Size of the centroid must be same as the length of" + << " each measurement vector."); + } + } + else + { + this->m_MeasurementVectorSize = cov.rows(); + } + + m_Covariance = cov; + this->CalculateInverseCovariance(); +} + +template < class TVector > +void +MahalanobisDistanceMembershipFunction< TVector > +::SetInverseCovariance(const CovarianceMatrixType &invcov) +{ + if( this->m_MeasurementVectorSize != 0 ) + { + if( invcov.rows() != this->m_MeasurementVectorSize || + invcov.cols() != this->m_MeasurementVectorSize ) + { + itkExceptionMacro( << "Size of the centroid must be same as the length of" + << " each measurement vector."); + } + } + else + { + this->m_MeasurementVectorSize = invcov.rows(); + } + + // use the inverse computation + m_Covariance = invcov; + this->CalculateInverseCovariance(); + m_Covariance = m_InverseCovariance; + m_InverseCovariance = invcov; +} + +template < class TVector > +void +MahalanobisDistanceMembershipFunction< TVector > +::CalculateInverseCovariance() +{ + + // pack the cov matrix from in_model to tmp_cov_mat + double cov_sum = 0; + for(unsigned int band_x = 0; band_x < m_Covariance.cols(); band_x++) + { + for(unsigned int band_y = 0; band_y < m_Covariance.rows(); band_y++) + { + cov_sum += vnl_math_abs( m_Covariance[band_x][band_y] ); + } + } + // check if it is a zero covariance, if it is, we make its + // inverse as an identity matrix with diagonal elements as + // a very large number; otherwise, inverse it + if( cov_sum < m_Epsilon ) + { + m_InverseCovariance.set_size( m_Covariance.rows(), m_Covariance.cols() ); + m_InverseCovariance.set_identity(); + m_InverseCovariance *= m_DoubleMax; + } + else + { + // check if num_bands == 1, if it is, we just use 1 to divide it + if( m_Covariance.rows() < 2 ) + { + m_InverseCovariance.set_size(1,1); + m_InverseCovariance[0][0] = 1.0 / m_Covariance[0][0]; + } + else + { + m_InverseCovariance = vnl_matrix_inverse<double>(m_Covariance); + } + }// end inverse calculations + +}// CalculateInverseCovariance() + +template < class TVector > +double +MahalanobisDistanceMembershipFunction< TVector > +::Evaluate(const MeasurementVectorType &measurement) const +{ + + double temp; + m_TempVec.set_size( 1, this->m_MeasurementVectorSize); + m_TempMat.set_size( 1, this->m_MeasurementVectorSize); + + // Compute |y - mean | + for ( unsigned int i = 0; i < this->m_MeasurementVectorSize; i++ ) + { + m_TempVec[0][i] = measurement[i] - m_Mean[i]; + } + + // Compute |y - mean | * inverse(cov) + m_TempMat= m_TempVec * m_InverseCovariance; + + // Compute |y - mean | * inverse(cov) * |y - mean|^T + temp = dot_product( m_TempMat.as_ref(), m_TempVec.as_ref() ); + + return temp; +} + +template < class TVector > +void +MahalanobisDistanceMembershipFunction< TVector > +::PrintSelf(std::ostream& os, Indent indent) const +{ + unsigned int i; + Superclass::PrintSelf(os,indent); + + if ( this->m_MeasurementVectorSize && + m_Mean.size() == this->m_MeasurementVectorSize ) + { + os << indent << "Mean: ["; + for (i=0; (i + 1) < this->m_MeasurementVectorSize; i++) + { + os << m_Mean[i] << ", "; + } + os << m_Mean[i] << "]" << std::endl; + } + else + { + os << indent << "Mean: not set or size does not match" << std::endl; + } + + os << indent << "Number of Samples: " << m_NumberOfSamples << std::endl; + os << indent << "Covariance: " << std::endl; + os << m_Covariance << std::endl; + os << indent << "Inverse covariance: " << std::endl; + os << m_InverseCovariance << std::endl; +} +} // end namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMetric.h b/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMetric.h new file mode 100644 index 0000000000..dc9e64a11f --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMetric.h @@ -0,0 +1,139 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMahalanobisDistanceMetric.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:56 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMahalanobisDistanceMetric_h +#define __itkMahalanobisDistanceMetric_h + +#include <vnl/vnl_vector.h> +#include <vnl/vnl_vector_ref.h> +#include <vnl/vnl_transpose.h> +#include <vnl/vnl_matrix.h> +#include <vnl/algo/vnl_matrix_inverse.h> +#include <vnl/algo/vnl_determinant.h> +#include "itkArray.h" + +#include "itkDistanceMetric.h" + + +namespace itk { +namespace Statistics{ + +/** \class MahalanobisDistanceMetric + * \brief MahalanobisDistanceMetric class computes a Mahalanobis + * distance given a mean and covariance. + * + * \sa DistanceMetric + * \sa EuclideanDistanceMetric + * \sa EuclideanSquareDistanceMetric + */ + +template< class TVector > +class ITK_EXPORT MahalanobisDistanceMetric : + public DistanceMetric< TVector > +{ +public: + /** Standard class typedefs */ + typedef MahalanobisDistanceMetric Self; + typedef DistanceMetric< TVector > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Strandard macros */ + itkTypeMacro(MahalanobisDistanceMetric, DistanceMetric); + itkNewMacro(Self); + + + /** Typedef to represent the measurement vector type */ + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + + /** Typedef to represent the length of measurement vectors */ + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + + + /** Type used for representing the mean vector */ + typedef typename Superclass::OriginType MeanVectorType; + + /** Type used for representing the covariance matrix */ + typedef vnl_matrix<double> CovarianceMatrixType; + + /** Set the length of each measurement vector. */ + virtual void SetMeasurementVectorSize( MeasurementVectorSizeType ); + + /** Method to set mean */ + void SetMean(const MeanVectorType &mean); + + /** Method to get mean */ + const MeanVectorType & GetMean() const; + + /** + * Method to set covariance matrix + * Also, this function calculates inverse covariance and pre factor of + * MahalanobisDistance Distribution to speed up GetProbability */ + void SetCovariance(const CovarianceMatrixType &cov); + + /** Method to get covariance matrix */ + itkGetConstReferenceMacro( Covariance, CovarianceMatrixType ); + + /** + * Method to set inverse covariance matrix */ + void SetInverseCovariance(const CovarianceMatrixType &invcov); + + /** Method to get covariance matrix */ + itkGetConstReferenceMacro( InverseCovariance, CovarianceMatrixType ); + + /** + * Method to get probability of an instance. The return value is the + * value of the density function, not probability. */ + double Evaluate(const MeasurementVectorType &measurement) const; + + /** Gets the distance between x1 and x2. */ + double Evaluate(const MeasurementVectorType &x1, const MeasurementVectorType &x2) const; + + /** Set/Get tolerance values */ + itkSetMacro( Epsilon, double ); + itkGetConstMacro( Epsilon, double ); + + itkSetMacro( DoubleMax, double ); + itkGetConstMacro( DoubleMax, double ); + +protected: + MahalanobisDistanceMetric(void); + virtual ~MahalanobisDistanceMetric(void) {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + MeanVectorType m_Mean; // mean + CovarianceMatrixType m_Covariance; // covariance matrix + + // inverse covariance matrix which is automatically calculated + // when covariace matirx is set. This speed up the GetProbability() + CovarianceMatrixType m_InverseCovariance; + + double m_Epsilon; + double m_DoubleMax; + + void CalculateInverseCovariance(); + +}; + +} // end of namespace Statistics +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkMahalanobisDistanceMetric.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMetric.txx b/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMetric.txx new file mode 100644 index 0000000000..1780a26e3c --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMahalanobisDistanceMetric.txx @@ -0,0 +1,237 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMahalanobisDistanceMetric.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMahalanobisDistanceMetric_txx +#define __itkMahalanobisDistanceMetric_txx + +#include "itkMahalanobisDistanceMetric.h" + +namespace itk { +namespace Statistics { + +template < class TVector > +MahalanobisDistanceMetric< TVector > +::MahalanobisDistanceMetric(): + m_Epsilon( 1e-100 ), + m_DoubleMax( 1e+20 ) +{ + MeasurementVectorSizeType size; + size = this->GetMeasurementVectorSize(); + + this->m_Covariance.set_size( size,size ); + this->m_InverseCovariance.set_size( size,size ); + + m_Covariance.set_identity(); + m_InverseCovariance.set_identity(); +} + +template < class TVector > +void +MahalanobisDistanceMetric< TVector > +::SetMean(const MeanVectorType & mean) +{ + Superclass::SetOrigin( mean ); +} + +template < class TVector > +const typename +MahalanobisDistanceMetric< TVector >::MeanVectorType & +MahalanobisDistanceMetric< TVector > +::GetMean() const +{ + return Superclass::GetOrigin(); +} + +template< class TVector > +void +MahalanobisDistanceMetric< TVector > +::SetMeasurementVectorSize( MeasurementVectorSizeType size ) +{ + this->Superclass::SetMeasurementVectorSize( size ); + this->m_Covariance.set_size( size,size ); + this->m_InverseCovariance.set_size( size,size ); + + this->m_Covariance.set_identity(); + this->m_InverseCovariance.set_identity(); + this->Modified(); +} + + +template < class TVector > +void +MahalanobisDistanceMetric< TVector > +::SetCovariance(const CovarianceMatrixType &cov) +{ + if( this->GetMeasurementVectorSize() != 0 ) + { + if( cov.rows() != this->GetMeasurementVectorSize() || + cov.cols() != this->GetMeasurementVectorSize()) + { + itkExceptionMacro( << "Size of the covariance matrix must be same as the length of" + << " the measurement vector."); + } + } + + m_Covariance = cov; + this->CalculateInverseCovariance(); +} + + +template < class TVector > +void +MahalanobisDistanceMetric< TVector > +::SetInverseCovariance(const CovarianceMatrixType &invcov) +{ + if( this->GetMeasurementVectorSize() != 0 ) + { + if( invcov.rows() != this->GetMeasurementVectorSize() || + invcov.cols() != this->GetMeasurementVectorSize() ) + { + itkExceptionMacro( << "Size of the covariance matrix xcmust be same as the length of" + << " each measurement vector."); + } + } + + // use the inverse computation + m_Covariance = invcov; + this->CalculateInverseCovariance(); + m_Covariance = m_InverseCovariance; + m_InverseCovariance = invcov; +} + + +template < class TVector > +void +MahalanobisDistanceMetric< TVector > +::CalculateInverseCovariance() +{ + // pack the cov matrix from in_model to tmp_cov_mat + double cov_sum = 0; + for(unsigned int band_x = 0; band_x < m_Covariance.cols(); band_x++) + { + for(unsigned int band_y = 0; band_y < m_Covariance.rows(); band_y++) + { + cov_sum += vnl_math_abs( m_Covariance[band_x][band_y] ); + } + } + // check if it is a zero covariance, if it is, we make its + // inverse as an identity matrix with diagonal elements as + // a very large number; otherwise, inverse it + if( cov_sum < m_Epsilon ) + { + m_InverseCovariance.set_size( m_Covariance.rows(), m_Covariance.cols() ); + m_InverseCovariance.set_identity(); + m_InverseCovariance *= m_DoubleMax; + } + else + { + // check if num_bands == 1, if it is, we just use 1 to divide it + if( m_Covariance.rows() < 2 ) + { + m_InverseCovariance.set_size(1,1); + m_InverseCovariance[0][0] = 1.0 / m_Covariance[0][0]; + } + else + { + m_InverseCovariance = vnl_matrix_inverse<double>(m_Covariance); + } + }// end inverse calculations + +} + +template < class TVector > +double +MahalanobisDistanceMetric< TVector > +::Evaluate(const MeasurementVectorType &measurement) const +{ + + vnl_matrix < double > tempVec; + vnl_matrix < double > tempMat; + + tempVec.set_size( 1, this->GetMeasurementVectorSize()); + tempMat.set_size( 1, this->GetMeasurementVectorSize()); + + // Compute |y - mean | + for ( unsigned int i = 0; i < this->GetMeasurementVectorSize(); i++ ) + { + tempVec[0][i] = measurement[i] - this->GetOrigin()[i]; + } + + // Compute |y - mean | * inverse(cov) + tempMat= tempVec * m_InverseCovariance; + + // Compute |y - mean | * inverse(cov) * |y - mean|^T + double temp; + temp = vcl_sqrt( dot_product( tempMat.as_ref(), tempVec.as_ref()) ); + + return temp; +} +template< class TVector > +inline double +MahalanobisDistanceMetric< TVector > +::Evaluate(const MeasurementVectorType &x1, const MeasurementVectorType &x2) const +{ + if( MeasurementVectorTraits::GetLength( x1 ) != this->GetMeasurementVectorSize() || + MeasurementVectorTraits::GetLength( x2 ) != this->GetMeasurementVectorSize()) + { + itkExceptionMacro( << "Size of the measurement vectors is not the same as the length of" + << " the measurement vector set in the distance metric."); + } + + vnl_matrix < double > tempVec; + vnl_matrix < double > tempMat; + + tempVec.set_size( 1, this->GetMeasurementVectorSize()); + tempMat.set_size( 1, this->GetMeasurementVectorSize()); + + // Compute |x1 - x2 | + for ( unsigned int i = 0; i < this->GetMeasurementVectorSize(); i++ ) + { + tempVec[0][i] = x1[i] - x2[i]; + } + + // Compute |x1 - x2 | * inverse(cov) + tempMat= tempVec * m_InverseCovariance; + + // Compute |x1 - x2 | * inverse(cov) * |x1 - x2|^T + double temp; + temp = vcl_sqrt( dot_product( tempMat.as_ref(), tempVec.as_ref()) ); + + return temp; +} +template < class TVector > +void +MahalanobisDistanceMetric< TVector > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Covariance: " << std::endl; + os << this->GetCovariance() << std::endl; + os << indent << "Inverse covariance: " << std::endl; + os << this->GetInverseCovariance() << std::endl; + os << indent << "Mean: " << std::endl; + os << this->GetMean() << std::endl; + os << indent << "Epsilon: " << std::endl; + os << this->GetEpsilon() << std::endl; + os << indent << "Double max: " << std::endl; + os << this->GetDoubleMax() << std::endl; +} +} // end namespace Statistics +} // end of namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.h b/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.h new file mode 100644 index 0000000000..5fb014e434 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.h @@ -0,0 +1,75 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkManhattanDistanceMetric.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkManhattanDistanceMetric_h +#define __itkManhattanDistanceMetric_h + +#include "itkNumericTraits.h" +#include "itkDistanceMetric.h" +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +/** \class ManhattanDistanceMetric + * \brief Euclidean distance function. + * + * \sa DistanceMetric + * \sa EuclideanSquareDistanceMetric + * \sa EuclideanDistanceMetric + * + */ +template< class TVector > +class ITK_EXPORT ManhattanDistanceMetric : + public DistanceMetric< TVector > +{ +public: + /** Standard "Self" typedef. */ + typedef ManhattanDistanceMetric Self; + typedef DistanceMetric< TVector > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + + + typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ManhattanDistanceMetric, DistanceMetric); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Gets the distance between the origin and x */ + double Evaluate(const MeasurementVectorType &x) const; + + /** Gets the distance between x1 and x2 */ + double Evaluate(const MeasurementVectorType &x1, const MeasurementVectorType &x2) const; + +protected: + ManhattanDistanceMetric() {} + virtual ~ManhattanDistanceMetric() {} +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkManhattanDistanceMetric.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.txx b/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.txx new file mode 100644 index 0000000000..3a29df84a3 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.txx @@ -0,0 +1,72 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkManhattanDistanceMetric.txx,v $ + Language: C++ + Date: $Date: 2009-05-23 04:17:05 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkManhattanDistanceMetric_txx +#define __itkManhattanDistanceMetric_txx + + +namespace itk { +namespace Statistics { + +template< class TVector > +inline double +ManhattanDistanceMetric< TVector > +::Evaluate(const MeasurementVectorType &x) const +{ + MeasurementVectorSizeType + measurementVectorSize = this->GetMeasurementVectorSize(); + if(measurementVectorSize == 0) + { + itkExceptionMacro( << "Please set the MeasurementVectorSize first" ); + } + MeasurementVectorTraits::Assert( this->GetOrigin(), measurementVectorSize, + "ManhattanDistanceMetric::Evaluate Origin and input vector have different lengths"); + + double temp, distance = NumericTraits< double >::Zero; + + for(unsigned int i = 0; i < measurementVectorSize; i++) + { + temp = fabs( this->GetOrigin()[i] - x[i] ); + distance += temp; + } + return distance; +} + +template< class TVector > +inline double +ManhattanDistanceMetric< TVector > +::Evaluate(const MeasurementVectorType &x1, const MeasurementVectorType &x2) const +{ + MeasurementVectorSizeType measurementVectorSize = MeasurementVectorTraits::GetLength( x1 ); + if (measurementVectorSize != MeasurementVectorTraits::GetLength(x2)) + { + itkExceptionMacro( << "ManhattanDistanceMetric:: The two measurement vectors have unequal size" ); + } + + double temp, distance = NumericTraits< double >::Zero; + for(unsigned int i = 0; i < measurementVectorSize; i++) + { + temp = fabs( x1[i] - x2[i] ); + distance += temp; + } + return distance; +} + + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.cxx b/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.cxx new file mode 100644 index 0000000000..fab5242fac --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.cxx @@ -0,0 +1,46 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMaximumDecisionRule2.cxx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkMaximumDecisionRule2.h" + +namespace itk { +namespace Statistics { + +void +MaximumDecisionRule2::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} + +unsigned int +MaximumDecisionRule2::Evaluate(const MembershipVectorType &discriminantScores) const +{ + double max = discriminantScores[0]; + unsigned int maxIndex = 0; + unsigned int i; + for (i = 1; i < discriminantScores.size(); i++) + { + if (discriminantScores[i] > max) + { + max = discriminantScores[i]; + maxIndex = i; + } + } + return maxIndex; +} + +} // end of namespace itk +} // end of namespace Statistics diff --git a/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.h b/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.h new file mode 100644 index 0000000000..97342bb054 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.h @@ -0,0 +1,65 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMaximumDecisionRule2.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMaximumDecisionRule2_h +#define __itkMaximumDecisionRule2_h + +#include "itkDecisionRule.h" + +namespace itk { +namespace Statistics { + +/** \class MaximumDecisionRule2 + * \brief A Decision rule that choose the class of which discriminant + * score is the largest. This class will replace the MaximumDecisionRule + * in Code/Common + */ + +class ITK_EXPORT MaximumDecisionRule2 : public DecisionRule +{ +public: + /** Standard class typedefs */ + typedef MaximumDecisionRule2 Self; + typedef DecisionRule Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro(MaximumDecisionRule2, DecisionRuleBase); + + /** Standard New() method support */ + itkNewMacro(Self); + + typedef Superclass::MembershipVectorType MembershipVectorType; + + + /** The return value of this function is a class label. + * Basically, using its internal logic based on the discriminant + * scores, this function decides best class label and return it. + */ + virtual unsigned int Evaluate( const MembershipVectorType &discriminantScores) const; + + +protected: + MaximumDecisionRule2() {} + virtual ~MaximumDecisionRule2() {} + void PrintSelf(std::ostream& os, Indent indent) const; +}; // end of class + +} // end of namespace itk +} // end of namespace Statistics + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMaximumRatioDecisionRule2.cxx b/Utilities/ITK/Code/Review/Statistics/itkMaximumRatioDecisionRule2.cxx new file mode 100644 index 0000000000..02fe002177 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMaximumRatioDecisionRule2.cxx @@ -0,0 +1,103 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMaximumRatioDecisionRule2.cxx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkMaximumRatioDecisionRule2.h" + +namespace itk { +namespace Statistics { + +MaximumRatioDecisionRule2::MaximumRatioDecisionRule2() +{ + this->m_NumberOfClasses = 0; +} + + +void MaximumRatioDecisionRule2::SetAPriori(APrioriVectorType& values) +{ + m_NumberOfClasses = values.size(); + m_APrioriRatioMatrix.set_size(values.size(), values.size()); + APrioriVectorSizeType i, j; + double APrioriRatio; + for (i = 0; i < m_NumberOfClasses; i++) + { + for (j = 0; j < m_NumberOfClasses; j++) + { + if ( values[i] > 0 ) + { + APrioriRatio = (double)values[j] / + (double)values[i]; + } + else + { + APrioriRatio = NumericTraits< double >::max(); + } + m_APrioriRatioMatrix.put(i, j, APrioriRatio); + } + } +} + +unsigned int +MaximumRatioDecisionRule2::Evaluate(const MembershipVectorType &discriminantScores) const +{ + unsigned int i, j; + double temp; + + if( this->m_NumberOfClasses == 0 ) + { + itkExceptionMacro("Aprior probability vector for each class not set" ); + } + + if( this->m_NumberOfClasses != discriminantScores.size() ) + { + itkExceptionMacro("MembershipVector(discriminant vector) size is not equal to the number of classes"); + } + + for (i = 0; i < m_NumberOfClasses; i++) + { + j = 0; + while ( j < m_NumberOfClasses ) + { + if ( j != i ) + { + if ( discriminantScores[j] != 0.0 ) + { + temp = discriminantScores[i] / discriminantScores[j]; + } + else + { + temp = NumericTraits< double >::max(); + } + + if ( temp < m_APrioriRatioMatrix.get(i,j) ) + { + break; + } + } + + ++j; + } + + if ( j == m_NumberOfClasses ) + { + break; + } + } + + return i; +} + +} // end of Statistics namespace +} // end of ITK namespace diff --git a/Utilities/ITK/Code/Review/Statistics/itkMaximumRatioDecisionRule2.h b/Utilities/ITK/Code/Review/Statistics/itkMaximumRatioDecisionRule2.h new file mode 100644 index 0000000000..22855bdf51 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMaximumRatioDecisionRule2.h @@ -0,0 +1,92 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMaximumRatioDecisionRule2.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMaximumRatioDecisionRule2_h +#define __itkMaximumRatioDecisionRule2_h + +#include <vector> +#include "vnl/vnl_matrix.h" + +#include "itkNumericTraits.h" +#include "itkDecisionRule.h" + +namespace itk { +namespace Statistics { + + +/** \class MaximumRatioDecisionRule2 + * \brief This rule returns \f$i\f$ if + * \f$\frac{f_{i}(\overrightarrow{x})}{f_{j}(\overrightarrow{x})} > + * \frac{K_{j}}{K_{i}}\f$ for all \f$j \not= i\f$, + * where the \f$i\f$ is the index of a class which has + * membership function \f$f_{i}\f$ and its prior value + * (usually, the a priori probability or the size of a class) is + * \f$K_{i}\f$ + * + * Users should set the a priori values before calling the Evaluate method. + * + * \sa MaximumDecisionRule, MinimumDecisionRule + */ + +class ITK_EXPORT MaximumRatioDecisionRule2 : + public DecisionRule +{ +public: + /** Standard class typedefs */ + typedef MaximumRatioDecisionRule2 Self; + typedef DecisionRule Superclass; + typedef SmartPointer<Self> Pointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro(MaximumRatioDecisionRule2, DecisionRule); + + /** Standard New() method support */ + itkNewMacro(Self); + + typedef float APrioriValueType; + typedef std::vector< APrioriValueType > APrioriVectorType; + typedef APrioriVectorType::size_type APrioriVectorSizeType; + + typedef Superclass::MembershipVectorType MembershipVectorType; + + /** The return value of this function is a class label. + * Basically, using its internal logic based on the discriminant + * scores, this function decides best class label and return it. + */ + virtual unsigned int Evaluate( const MembershipVectorType &discriminantScores) const; + + + /** Sets the a priori probabilities */ + void SetAPriori(APrioriVectorType& values); + +protected: + MaximumRatioDecisionRule2(); + virtual ~MaximumRatioDecisionRule2() {} + +private: + MaximumRatioDecisionRule2(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Number of classes */ + APrioriVectorSizeType m_NumberOfClasses; + + /** a priori probability ratio matrix: internal use */ + vnl_matrix< double > m_APrioriRatioMatrix; +}; // end of class + +} // end of Statistics namespace +} // end of ITK namespace +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMeanSampleFilter.h b/Utilities/ITK/Code/Review/Statistics/itkMeanSampleFilter.h new file mode 100644 index 0000000000..066922ffac --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMeanSampleFilter.h @@ -0,0 +1,105 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMeanSampleFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkMeanSampleFilter_h +#define __itkMeanSampleFilter_h + +#include "itkProcessObject.h" +#include "itkArray.h" +#include "itkSimpleDataObjectDecorator.h" +#include "itkDataObject.h" + +namespace itk { +namespace Statistics { + +/** \class MeanSampleFilter + * \brief Given a sample, this filter computes the sample mean + * + * The sample is plugged in using SetSample method. Then invoke + * update() method to compute the sample mean. + * + * The sample mean is computed as follows + * \f$ = \frac{1}{n}\sum^{n}_{i=1}x_{i}\f$ where \f$n\f$ is the + * number of measurement vectors in the target + * + * Recent API changes: + * The static const macro to get the length of a measurement vector, + * 'MeasurementVectorSize' has been removed to allow the length of a measurement + * vector to be specified at run time. It is now obtained from the input sample. + * Please use the function GetMeasurementVectorSize() to obtain the length. + */ + +template< class TSample > +class ITK_EXPORT MeanSampleFilter : public ProcessObject +{ +public: + /**Standard class typedefs. */ + typedef MeanSampleFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef TSample SampleType; + + /**Standard Macros */ + itkTypeMacro(MeanSampleFilter, ProcessObject); + itkNewMacro(Self); + + /** Length of a measurement vector */ + typedef unsigned int MeasurementVectorSizeType; + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename TSample::MeasurementType MeasurementType; + + /** Method to set/get the sample */ + void SetInput( const SampleType * sample ); + const SampleType * GetInput() const; + + /** MeasurementVector is not a DataObject, we need to decorate it to push it down + * a ProcessObject's pipeline */ + typedef SimpleDataObjectDecorator< MeasurementVectorType > MeasurementVectorDecoratedType; + + typedef MeasurementVectorDecoratedType OutputType; + + /** Get the mean measurement vector */ + const MeasurementVectorDecoratedType * GetOutput() const; + const MeasurementVectorType GetMean() const; + +protected: + MeanSampleFilter(); + virtual ~MeanSampleFilter(); + void PrintSelf(std::ostream& os, Indent indent) const; + + /** DataObject pointer */ + typedef DataObject::Pointer DataObjectPointer; + + virtual DataObjectPointer MakeOutput(unsigned int idx); + + void GenerateData(); + +private: + MeanSampleFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkMeanSampleFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMeanSampleFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkMeanSampleFilter.txx new file mode 100644 index 0000000000..65e6d14c52 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMeanSampleFilter.txx @@ -0,0 +1,150 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMeanSampleFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMeanSampleFilter_txx +#define __itkMeanSampleFilter_txx + +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +MeanSampleFilter< TSample > +::MeanSampleFilter() +{ + this->ProcessObject::SetNumberOfRequiredInputs(1); + this->ProcessObject::SetNumberOfRequiredOutputs(1); + + this->ProcessObject::SetNthOutput(0, this->MakeOutput(0) ); +} + + +template< class TSample > +MeanSampleFilter< TSample > +::~MeanSampleFilter() +{ +} + + +template< class TSample > +void +MeanSampleFilter< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} + +template< class TSample > +void +MeanSampleFilter< TSample > +::SetInput( const SampleType * sample ) +{ + this->ProcessObject::SetNthInput(0, const_cast< SampleType* >( sample ) ); +} + +template< class TSample > +const TSample * +MeanSampleFilter< TSample > +::GetInput( ) const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const SampleType * > (this->ProcessObject::GetInput(0) ); +} + +template< class TSample > +typename MeanSampleFilter< TSample>::DataObjectPointer +MeanSampleFilter< TSample > +::MakeOutput(unsigned int itkNotUsed(idx)) +{ + return static_cast< DataObject * >(MeasurementVectorDecoratedType::New().GetPointer()); +} + +template< class TSample > +const typename MeanSampleFilter< TSample>::MeasurementVectorDecoratedType * +MeanSampleFilter< TSample > +::GetOutput() const +{ + return static_cast< const MeasurementVectorDecoratedType * >( + this->ProcessObject::GetOutput(0)); +} + +template< class TSample > +const typename MeanSampleFilter< TSample>::MeasurementVectorType +MeanSampleFilter< TSample > +::GetMean() const +{ + return this->GetOutput()->Get(); +} + +template< class TSample > +void +MeanSampleFilter< TSample > +::GenerateData() +{ + const SampleType *input = this->GetInput(); + + MeasurementVectorSizeType measurementVectorSize = + input->GetMeasurementVectorSize(); + + MeasurementVectorDecoratedType * decoratedOutput = + static_cast< MeasurementVectorDecoratedType * >( + this->ProcessObject::GetOutput(0)); + + MeasurementVectorType output = decoratedOutput->Get(); + + typename TSample::ConstIterator iter = input->Begin(); + typename TSample::ConstIterator end = input->End(); + double totalFrequency = 0.0; + + for (unsigned int dim = 0; dim < measurementVectorSize; dim++) + { + output[dim] = itk::NumericTraits< MeasurementType >::Zero; + } + + while (iter != end) + { + double frequency = iter.GetFrequency(); + totalFrequency += frequency; + + for (unsigned int dim = 0; dim < measurementVectorSize; dim++) + { + output[dim] += iter.GetMeasurementVector()[dim] * frequency; + } + ++iter; + } + + // compute the mean if the total frequency is different from zero + if ( totalFrequency != 0.0 ) + { + for (unsigned int dim = 0; dim < measurementVectorSize; dim++) + { + output[dim] /= totalFrequency; + } + } + + decoratedOutput->Set( output ); + +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMeasurementVectorTraits.h b/Utilities/ITK/Code/Review/Statistics/itkMeasurementVectorTraits.h new file mode 100644 index 0000000000..2fc01b3c95 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMeasurementVectorTraits.h @@ -0,0 +1,703 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMeasurementVectorTraits.h,v $ + Language: C++ + Date: $Date: 2009-05-23 04:17:05 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMeasurementVectorTraits_h +#define __itkMeasurementVectorTraits_h + +#include "itkMacro.h" +#include "itkArray.h" +#include "itkVariableLengthVector.h" +#include "itkVector.h" +#include "itkFixedArray.h" +#include "vnl/vnl_vector_fixed.h" +#include "itkPoint.h" +#include "itkRGBPixel.h" +#include "itkMatrix.h" +#include "itkVariableSizeMatrix.h" +#include "itkNumericTraits.h" +#include "itkSize.h" +#include <vector> + + +/** THIS DECLARATION OF NUMERICTRAITS IS HERE TEMPORARILY + * + * It should be moved to the Insight/Code/Common/itkNumericTraits.h file + * when the new framework is integrated into ITK + * + */ +#ifdef _WIN64 + +namespace itk { + +/** \class NumericTraits<unsigned long> + * \brief Define traits for type unsigned long. + * \ingroup DataRepresentation + */ +template <> +class NumericTraits< std::vector<int>::size_type > : public vcl_numeric_limits< std::vector<int>::size_type > { +public: + typedef std::vector<int>::size_type SelfType; + typedef SelfType ValueType; + typedef SelfType PrintType; + typedef SelfType AbsType; + typedef SelfType AccumulateType; + typedef long double RealType; + typedef RealType ScalarRealType; + typedef long double FloatType; + + static const SelfType ITKCommon_EXPORT Zero; + static const SelfType ITKCommon_EXPORT One; + + static SelfType NonpositiveMin() { return min(); } + static bool IsPositive(SelfType val) { return val != Zero; } + static bool IsNonpositive(SelfType val) { return val == Zero; } + static bool IsNegative(SelfType) { return false; } + static bool IsNonnegative(SelfType) {return true; } + static SelfType ZeroValue() { return Zero; } +}; +} + +#endif + + +namespace itk +{ +namespace Statistics +{ + +/** \class MeasurementVectorTraits + * \brief + * \ingroup Statistics + */ + + +class MeasurementVectorTraits +{ +public: + + /** In the old framework, the FrequencyType is set to float. The problem is for + large histograms the total frequency can be more than 1e+7, than increasing + the frequency by one does not change the total frequency (because of lack of + precision). Using double type will also ultimately fall into the same problem. + Hence in the new statistics framework, InstanceIdentifier/FrequencyTypes are + set to the the largest possible integer on the machine */ + //typedef typename std::vector<int>::size_type InstanceIdentifier; + typedef unsigned long InstanceIdentifier; + + /** Type defined for representing the frequency of measurement vectors */ + typedef InstanceIdentifier AbsoluteFrequencyType; + typedef NumericTraits< AbsoluteFrequencyType >::RealType RelativeFrequencyType; + typedef NumericTraits< AbsoluteFrequencyType >::AccumulateType TotalAbsoluteFrequencyType; + typedef NumericTraits< RelativeFrequencyType >::AccumulateType TotalRelativeFrequencyType; + + typedef unsigned int MeasurementVectorLength; + + template<class TValueType, unsigned int VLength> + static void SetLength( FixedArray< TValueType, VLength > &m, const unsigned int s ) + { + if( s != VLength ) + { + itkGenericExceptionMacro( << "Cannot set the size of a FixedArray of length " + << VLength << " to " << s ); + } + m.Fill( NumericTraits< TValueType >::Zero ); + } + + template<class TValueType, unsigned int VLength> + static void SetLength( FixedArray< TValueType, VLength > *m, const unsigned int s ) + { + if( s != VLength ) + { + itkGenericExceptionMacro( << "Cannot set the size of a FixedArray of length " + << VLength << " to " << s ); + } + m->Fill( NumericTraits< TValueType >::Zero ); + } + + template< class TValueType > + static void SetLength( Array< TValueType > & m, const unsigned int s ) + { + m.SetSize( s ); + m.Fill( NumericTraits< TValueType >::Zero ); + } + + template< class TValueType > + static void SetLength( Array< TValueType > * m, const unsigned int s ) + { + m->SetSize( s ); + m->Fill( NumericTraits< TValueType >::Zero ); + } + + template< class TValueType > + static void SetLength( VariableLengthVector< TValueType > & m, const unsigned int s ) + { + m.SetSize( s ); + m.Fill( NumericTraits< TValueType >::Zero ); + } + + template< class TValueType > + static void SetLength( VariableLengthVector< TValueType > * m, const unsigned int s ) + { + m->SetSize( s ); + m->Fill( NumericTraits< TValueType >::Zero ); + } + + template< class TValueType > + static void SetLength( std::vector< TValueType > & m, const unsigned int s ) + { + m.resize( s ); + } + + template< class TValueType > + static void SetLength( std::vector< TValueType > * m, const unsigned int s ) + { + m->resize( s ); + } + + + template< class TValueType, unsigned int VLength > + static MeasurementVectorLength + GetLength( const FixedArray< TValueType, VLength > &) + { return VLength; } + + template< class TValueType, unsigned int VLength > + static MeasurementVectorLength + GetLength( const FixedArray< TValueType, VLength > *) + { return VLength; } + + template< class TValueType > + static MeasurementVectorLength + GetLength( const Array< TValueType > &m ) + {return m.GetSize(); } + + template< class TValueType > + static MeasurementVectorLength + GetLength( const Array< TValueType > *m ) + {return m->GetSize(); } + + template< class TValueType > + static MeasurementVectorLength + GetLength( const VariableLengthVector< TValueType > &m ) + {return m.GetSize(); } + + template< class TValueType > + static MeasurementVectorLength + GetLength( const VariableLengthVector< TValueType > *m ) + {return m->GetSize(); } + + template< class TValueType > + static MeasurementVectorLength + GetLength( const std::vector< TValueType > &m ) + {return m.size(); } + + template< class TValueType > + static MeasurementVectorLength + GetLength( const std::vector< TValueType > *m ) + {return m->size(); } + + + template< class TVectorType > + static bool IsResizable( const TVectorType & ) + { + // Test whether the vector type is resizable or not + // + // If the default constructor creates a vector of + // length zero, we assume that it is resizable, + // otherwise that is a pretty useless measurement vector. + TVectorType m; + MeasurementVectorLength len = GetLength( m ); + return ( len == 0 ); + } + + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + template< class TValueType1, unsigned int VLength, class TValueType2, unsigned int VLength2 > + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > &, + const FixedArray< TValueType2, VLength2 > & , const char *errMsg="Length Mismatch") + { + if ( VLength != VLength2 ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + template< class TValueType1, unsigned int VLength, class TValueType2, unsigned int VLength2 > + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > *, + const FixedArray< TValueType2, VLength2 > *, const char *errMsg="Length Mismatch") + { + if ( VLength != VLength2 ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } +#endif + template< class TValueType1, class TValueType2 > + static MeasurementVectorLength Assert( const Array< TValueType1 > &a, + const Array< TValueType2 > &b, const char *errMsg="Length Mismatch") + { + if( b.Size() != a.Size() ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + template< class TValueType1, class TValueType2 > + static MeasurementVectorLength Assert( const Array< TValueType1 > *a, + const Array< TValueType2 > *b, const char *errMsg="Length Mismatch") + { + if( b->Size() != a->Size() ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + + template< class TValueType1, class TValueType2 > + static MeasurementVectorLength Assert( const VariableLengthVector< TValueType1 > &a, + const VariableLengthVector< TValueType2 > &b, const char *errMsg="Length Mismatch") + { + if( b.Size() != a.Size() ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + template< class TValueType1, class TValueType2 > + static MeasurementVectorLength Assert( const VariableLengthVector< TValueType1 > *a, + const VariableLengthVector< TValueType2 > *b, const char *errMsg="Length Mismatch") + { + if( b->Size() != a->Size() ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + + template< class TValueType1, class TValueType2 > + static MeasurementVectorLength Assert( const std::vector< TValueType1 > &a, + const std::vector< TValueType2 > &b, const char *errMsg="Length Mismatch") + { + if( b.size() != a.size() ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + template< class TValueType1, class TValueType2 > + static MeasurementVectorLength Assert( const std::vector< TValueType1 > *a, + const std::vector< TValueType2 > *b, const char *errMsg="Length Mismatch") + { + if( b->size() != a->size() ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + + template< class TValueType1, unsigned int VLength, class TValueType2 > + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > &, + const Array< TValueType2 > &b, const char *errMsg="Length Mismatch") + { + if( b.Size() == 0 ) + { + return VLength; + } + if( b.Size() != 0 ) + { + if (b.Size() != VLength) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + } + return 0; + } + + template< class TValueType1, unsigned int VLength, class TValueType2 > + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > *, + const Array< TValueType2 > *b, const char *errMsg="Length Mismatch") + { + if( b->Size() == 0 ) + { + return VLength; + } + else if (b->Size() != VLength) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + template< class TValueType1, unsigned int VLength, class TValueType2 > + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > &, + const VariableLengthVector< TValueType2 > &b, const char *errMsg="Length Mismatch") + { + if( b.Size() == 0 ) + { + return VLength; + } + if( b.Size() != 0 ) + { + if (b.Size() != VLength) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + } + return 0; + } + + template< class TValueType1, unsigned int VLength, class TValueType2 > + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > *, + const VariableLengthVector< TValueType2 > *b, const char *errMsg="Length Mismatch") + { + if( b->Size() == 0 ) + { + return VLength; + } + else if (b->Size() != VLength) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + template< class TValueType1, unsigned int VLength, class TValueType2 > + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > &, + const std::vector< TValueType2 > &b, const char *errMsg="Length Mismatch") + { + if( b.size() == 0 ) + { + return VLength; + } + if( b.size() != 0 ) + { + if (b.size() != VLength) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + } + return 0; + } + + template< class TValueType1, unsigned int VLength, class TValueType2 > + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > *, + const std::vector< TValueType2 > *b, const char *errMsg="Length Mismatch") + { + if( b->size() == 0 ) + { + return VLength; + } + else if (b->size() != VLength) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + + template< class TValueType1, unsigned int VLength> + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > &, + const MeasurementVectorLength l, const char *errMsg="Length Mismatch") + { + if( l == 0 ) + { + return VLength; + } + else if( l != VLength ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + template< class TValueType1, unsigned int VLength> + static MeasurementVectorLength Assert( const FixedArray< TValueType1, VLength > *, + const MeasurementVectorLength l, const char *errMsg="Length Mismatch") + { + if( l == 0 ) + { + return VLength; + } + else if( l != VLength ) + { + itkGenericExceptionMacro( << errMsg ); + return 0; + } + return 0; + } + + template< class TValueType > + static MeasurementVectorLength Assert( const Array< TValueType > &a, + const MeasurementVectorLength l, const char *errMsg="Length Mismatch") + { + if( ( ( l != 0 ) && ( a.Size() != l ) ) || ( a.Size() == 0 ) ) + { + itkGenericExceptionMacro( << errMsg ); + } + else if( l == 0 ) + { + return a.Size(); + } + return 0; + } + + template< class TValueType > + static MeasurementVectorLength Assert( const Array< TValueType > *a, + const MeasurementVectorLength l, const char *errMsg="Length Mismatch") + { + if( ( ( l != 0 ) && ( a->Size() != l )) || ( a->Size() == 0 ) ) + { + itkGenericExceptionMacro( << errMsg ); + } + else if( l == 0 ) + { + return a->Size(); + } + return 0; + } + + template< class TValueType > + static MeasurementVectorLength Assert( const VariableLengthVector< TValueType > &a, + const MeasurementVectorLength l, const char *errMsg="Length Mismatch") + { + if( ( ( l != 0 ) && ( a.Size() != l ) ) || ( a.Size() == 0 ) ) + { + itkGenericExceptionMacro( << errMsg ); + } + else if( l == 0 ) + { + return a.Size(); + } + return 0; + } + + template< class TValueType > + static MeasurementVectorLength Assert( const VariableLengthVector< TValueType > *a, + const MeasurementVectorLength l, const char *errMsg="Length Mismatch") + { + if( ( ( l != 0 ) && ( a->Size() != l ) ) || ( a->Size() == 0 ) ) + { + itkGenericExceptionMacro( << errMsg ); + } + else if( l == 0 ) + { + return a->Size(); + } + return 0; + } + template< class TValueType > + static MeasurementVectorLength Assert( const std::vector< TValueType > &a, + const MeasurementVectorLength l, const char *errMsg="Length Mismatch") + { + if( ( ( l != 0 ) && ( a.size() != l ) ) || ( a.size() == 0 ) ) + { + itkGenericExceptionMacro( << errMsg ); + } + else if( l == 0 ) + { + return a.size(); + } + return 0; + } + + template< class TValueType > + static MeasurementVectorLength Assert( const std::vector< TValueType > *a, + const MeasurementVectorLength l, const char *errMsg="Length Mismatch") + { + if( ( ( l != 0 ) && ( a->size() != l ) ) || ( a->size() == 0 ) ) + { + itkGenericExceptionMacro( << errMsg ); + } + else if( l == 0 ) + { + return a->size(); + } + return 0; + } + + template< class TArrayType > + static void Assign( TArrayType & m, const TArrayType & v ) + { + m = v; + } + + template< class TValueType, unsigned int VLength > + static void Assign( FixedArray< TValueType, VLength > & m, const TValueType & v ) + { + m[0] = v; + } + +}; + +/** \class MeasurementVectorTraitsTypes + * \brief + * \ingroup Statistics + */ + +template < class TMeasurementVector > +class MeasurementVectorTraitsTypes +{ +public: + typedef typename TMeasurementVector::ValueType ValueType; +}; + +// +// Visual Studio 6.0 and 7.0 are not capable of managing the next +// template implementation. A macro workaround is provided. +#define itkMeasurementVectorTraitsTypesMacro(T) \ +template <> \ +class MeasurementVectorTraitsTypes< std::vector< T > > \ +{ \ +public: \ + typedef T ValueType; \ +}; + +#if defined( _MSC_VER ) && ( _MSC_VER < 1310 ) +itkMeasurementVectorTraitsTypesMacro( char ); +itkMeasurementVectorTraitsTypesMacro( unsigned char ); +itkMeasurementVectorTraitsTypesMacro( short ); +itkMeasurementVectorTraitsTypesMacro( unsigned short ); +itkMeasurementVectorTraitsTypesMacro( int ); +itkMeasurementVectorTraitsTypesMacro( unsigned int ); +itkMeasurementVectorTraitsTypesMacro( long ); +itkMeasurementVectorTraitsTypesMacro( unsigned long ); +itkMeasurementVectorTraitsTypesMacro( float ); +itkMeasurementVectorTraitsTypesMacro( double ); +#else +template< class T > +class MeasurementVectorTraitsTypes< std::vector< T > > +{ +public: + typedef T ValueType; +}; +#endif + +/** Traits for generating the MeasurementVectorType that best matches a + * particular pixel type. */ + +template<class TPixelType> +class MeasurementVectorPixelTraits +{ +public: + /* type of the vector that matches this pixel type */ + typedef TPixelType MeasurementVectorType; +}; + + +template<> +class MeasurementVectorPixelTraits<char> +{ +public: + typedef FixedArray< char, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<unsigned char> +{ +public: + typedef FixedArray< unsigned char, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<signed char> +{ +public: + typedef FixedArray< signed char, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<unsigned short> +{ +public: + typedef FixedArray< unsigned short, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<signed short> +{ +public: + typedef FixedArray< signed short, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<unsigned int> +{ +public: + typedef FixedArray< unsigned int, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<signed int> +{ +public: + typedef FixedArray< signed int, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<unsigned long> +{ +public: + typedef FixedArray< unsigned long, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<signed long> +{ +public: + typedef FixedArray< signed long, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<float> +{ +public: + typedef FixedArray< float, 1 > MeasurementVectorType; +}; + +template<> +class MeasurementVectorPixelTraits<double> +{ +public: + typedef FixedArray< double, 1 > MeasurementVectorType; +}; + + +} // namespace Statistics +} // namespace itk + +#endif // __itkMeasurementVectorTraits_h diff --git a/Utilities/ITK/Code/Review/Statistics/itkMembershipFunctionBase.h b/Utilities/ITK/Code/Review/Statistics/itkMembershipFunctionBase.h new file mode 100644 index 0000000000..709414afd7 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMembershipFunctionBase.h @@ -0,0 +1,120 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMembershipFunctionBase.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMembershipFunctionBase_h +#define __itkMembershipFunctionBase_h + +#include "itkFunctionBase.h" +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +/** \class MembershipFunctionBase + * \brief MembershipFunctionBase class declares common interfaces + * for membership functions. + * + * As a function derived from FunctionBase, users use Evaluate method + * get result. However, the return value type of the method is fixed + * as double. Any function derived from this class returns quantitative + * measure for how well the vector x belong to the class ( or group) + * represented by the function. + */ + +template< class TVector > +class ITK_EXPORT MembershipFunctionBase : + public FunctionBase< TVector, double > +{ +public: + /** Standard class typedefs */ + typedef MembershipFunctionBase Self; + typedef FunctionBase< TVector, double > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Strandard macros */ + itkTypeMacro(MembershipFunctionBase, FunctionBase); + + /** MeasurementVector typedef support */ + typedef TVector MeasurementVectorType; + + /** Typedef for the length of each measurement vector */ + typedef unsigned int MeasurementVectorSizeType; + + /** Method to get membership score (discriminant score) of an entity. */ + virtual double Evaluate(const MeasurementVectorType &x) const = 0; + + /** Set method for the length of the measurement vector */ + virtual void SetMeasurementVectorSize( MeasurementVectorSizeType s ) + { + // Test whether the vector type is resizable or not + MeasurementVectorType m; + if( MeasurementVectorTraits::IsResizable( m ) ) + { + // then this is a resizable vector type + // + // if the new size is the same as the previou size, just return + if( s == this->m_MeasurementVectorSize ) + { + return; + } + else + { + this->m_MeasurementVectorSize = s; + this->Modified(); + } + } + else + { + // If this is a non-resizable vector type + MeasurementVectorType m3; + MeasurementVectorSizeType defaultLength = MeasurementVectorTraits::GetLength( m3 ); + // and the new length is different from the default one, then throw an exception + if( defaultLength != s ) + { + itkExceptionMacro("Attempting to change the measurement \ + vector size of a non-resizable vector type"); + } + } + } + + /** Get method for the length of the measurement vector */ + itkGetConstMacro( MeasurementVectorSize, MeasurementVectorSizeType ); + +protected: + MembershipFunctionBase() + { + m_MeasurementVectorSize = MeasurementVectorTraits::GetLength( + MeasurementVectorType() ); + } + + + virtual ~MembershipFunctionBase(void) {} + + void PrintSelf(std::ostream& os, Indent indent) const + { + Superclass::PrintSelf(os,indent); + os << indent << "Length of measurement vectors: " + << m_MeasurementVectorSize << std::endl; + } + MeasurementVectorSizeType m_MeasurementVectorSize; + +}; // end of class + +} // end of namespace Statistics +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMembershipSample.h b/Utilities/ITK/Code/Review/Statistics/itkMembershipSample.h new file mode 100644 index 0000000000..c2592c48b6 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMembershipSample.h @@ -0,0 +1,318 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMembershipSample.h,v $ + Language: C++ + Date: $Date: 2009-05-22 12:55:07 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMembershipSample_h +#define __itkMembershipSample_h + +#include "itk_hash_map.h" +#include "itkSample.h" +#include "itkSubsample.h" + +namespace itk { +namespace Statistics { + +/** \class MembershipSample + * \brief Container for storing the instance-identifiers of other sample with + * their associated class labels. + * + * This class does not store any measurement data. In a sense, you can + * think it as an additional information to basic samples (such as Histogram, + * PointSetListSampleAdaptor, and ImageToListAdaptor). The additional + * information is a class label for a measurement vector. Obviously without + * such basic types of sample, this one is meaningless. You can call any + * basic methods that has been defined in the Sample class such as + * GetMeasurementVector and GetFrequency. You can query the class label for + * an instance using an instance-identifier. Another new and important method + * is the GetClassSample method. With a given class label, it returns a + * pointer to the Subsample object that has all the instance-identifiers + * of instances that belong to the class. + * + * This class is templated over the type of the basic sample. To use all + * the method, you should first plug in a basic type sample using the + * SetSample method + * + */ + +template< class TSample > +class ITK_EXPORT MembershipSample : public DataObject +{ +public: + /** Standard class typedefs. */ + typedef MembershipSample Self; + typedef DataObject Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Standard macros */ + itkTypeMacro(MembershipSample, DataObject); + itkNewMacro(Self); + + /** Typedefs for Measurement vector, measurement, Instance Identifier, + * frequency, size, size element value from the template argument TSample */ + typedef TSample SampleType; + typedef typename SampleType::MeasurementVectorType MeasurementVectorType; + typedef typename SampleType::MeasurementType MeasurementType; + typedef typename SampleType::InstanceIdentifier InstanceIdentifier; + typedef typename SampleType::ConstPointer SampleConstPointer; + + typedef typename SampleType::AbsoluteFrequencyType AbsoluteFrequencyType; + typedef typename SampleType::TotalAbsoluteFrequencyType TotalAbsoluteFrequencyType; + + + typedef unsigned long ClassLabelType; + /** vector of unique class labels that will be used for mapping internal + * continuous class label with real class labels */ + typedef std::vector< ClassLabelType > UniqueClassLabelsType; + + /** Typedef for the storage that holds a class label for each instance. + * The relationship between instances and class label is one-to-one */ + typedef itk::hash_map< InstanceIdentifier, ClassLabelType > ClassLabelHolderType; + + /** Typedef for each subsample that stores instance identifers of instances + * that belong to a class */ + typedef Subsample< SampleType > ClassSampleType; + typedef typename ClassSampleType::Pointer ClassSamplePointer; + typedef typename ClassSampleType::ConstPointer ClassSampleConstPointer; + + /** Set/Get the actual sample data */ + itkSetConstObjectMacro( Sample, SampleType ); + itkGetConstObjectMacro( Sample, SampleType ); + + /** Sets the number of classes (class labels) */ + void SetNumberOfClasses( unsigned int numberOfClasses ); + + /** Gets the number of classes (class labels) */ + itkGetConstMacro( NumberOfClasses, unsigned int ); + + /** Adds an instance from the source sample to this container. The + * first argument is the class label for that instance. The second + * argument is the instance identifier from the source identifier that + * is going to be included this container. */ + void AddInstance(const ClassLabelType &classLabel, const InstanceIdentifier &id); + + /** Gets the class label for the instance that has the instance + * identifier, id. */ + unsigned int GetClassLabel(const InstanceIdentifier &id) const; + + /** Gets the Subsample that includes only the instances that belongs + * to the classLabel */ + const ClassSampleType* GetClassSample(const ClassLabelType &classLabel) const; + + /** Gets the class labels that corresponding to the each instance in + * this container. */ + const ClassLabelHolderType GetClassLabelHolder() const; + + /** retunrs the measurement of the instance which is identified + * by the 'id' */ + const MeasurementVectorType & GetMeasurementVector(const InstanceIdentifier &id) const; + + /** returns the measurement element which is the 'n'-th element + * in the 'd' dimension of the measurement vector */ + MeasurementType GetMeasurement(const InstanceIdentifier &id, + const unsigned int &dimension); + + /** returns the frequency of the instance which is identified by the 'id' */ + AbsoluteFrequencyType GetFrequency(const InstanceIdentifier &id) const; + + /** returns the total frequency for the 'd' dimension */ + TotalAbsoluteFrequencyType GetTotalFrequency() const; + + /** Method to graft another sample */ + virtual void Graft( const DataObject *thatObject ); + +// void PrintSelf(std::ostream& os, Indent indent) const; + + class ConstIterator + { + friend class MembershipSample; + public: + + ConstIterator( const Self * sample ) + { + *this = sample->Begin(); + } + + ConstIterator(const ConstIterator& iter) + { + m_Sample = iter.m_Sample; + m_MembershipSample = iter.m_MembershipSample; + m_InstanceIdentifier = iter.m_InstanceIdentifier; + } + + ConstIterator& operator=(const ConstIterator& iter) + { + m_Sample = iter.m_Sample; + m_MembershipSample = iter.m_MembershipSample; + m_InstanceIdentifier = iter.m_InstanceIdentifier; + return *this; + } + + bool operator!=(const ConstIterator& it) + { + return (m_InstanceIdentifier != it.m_InstanceIdentifier); + } + + bool operator==(const ConstIterator& it) + { + return (m_InstanceIdentifier == it.m_InstanceIdentifier); + } + + ConstIterator& operator++() + { + ++m_InstanceIdentifier; + return *this; + } + + AbsoluteFrequencyType GetFrequency() const + { + return m_Sample->GetFrequency(m_InstanceIdentifier); + } + + const MeasurementVectorType & GetMeasurementVector() const + { + return m_Sample->GetMeasurementVector(m_InstanceIdentifier); + } + + InstanceIdentifier GetInstanceIdentifier() const + { + return m_InstanceIdentifier; + } + + unsigned int GetClassLabel() const + { + return m_MembershipSample->GetClassLabel( m_InstanceIdentifier ); + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // Purposely not implemented + ConstIterator(); + + // Only to be called from the MembershipSample + ConstIterator( + const Self* memberSample, InstanceIdentifier iid) + :m_Sample(memberSample->GetSample()), m_MembershipSample( memberSample), m_InstanceIdentifier(iid) + { + + } + + + //typename SampleType::ConstIterator m_Iter; + const TSample* m_Sample; + const MembershipSample* m_MembershipSample; + InstanceIdentifier m_InstanceIdentifier; + }; + + class Iterator: public ConstIterator + { + friend class MembershipSample; + + public: + + Iterator(Self * sample):ConstIterator( sample ) + { + } + + Iterator(const Iterator &iter):ConstIterator( iter ) + { + } + + Iterator& operator =(const Iterator & iter) + { + this->ConstIterator::operator=( iter ); + return *this; + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // To ensure const-correctness these method must not be in the public API. + // The are purposly not implemented, since they should never be called. + Iterator(); + Iterator(const Self * sample); + Iterator(const ConstIterator & it); + ConstIterator& operator=(const ConstIterator& it); + + // Only to be called from the MembershipSample + Iterator(Self * memberSample, + InstanceIdentifier iid) + :ConstIterator( memberSample, iid ) + {} + + private: + }; + + /** This method returns an iterator to the beginning of the + measurement vectors */ + Iterator Begin() + { + Iterator iter(this, 0); + return iter; + } + + /** This method returns an iterator to the beginning of the + measurement vectors */ + Iterator End() + { + Iterator iter(this, m_Sample->Size()); + return iter; + } + + ConstIterator Begin() const + { + ConstIterator iter(this, 0); + return iter; + } + + ConstIterator End() const + { + ConstIterator iter(this, m_Sample->Size()); + return iter; + } + +protected: + MembershipSample(); + virtual ~MembershipSample() {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + MembershipSample(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Gets the internal continuous class label from the class labels that + * are used for AddInstance method. */ + int GetInternalClassLabel(const ClassLabelType classLabel ) const; + + + UniqueClassLabelsType m_UniqueClassLabels; + ClassLabelHolderType m_ClassLabelHolder; + std::vector< ClassSamplePointer > m_ClassSamples; + SampleConstPointer m_Sample; + unsigned int m_NumberOfClasses; + +}; // end of class + + +} // end of namespace Statistics +} // end of namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkMembershipSample.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMembershipSample.txx b/Utilities/ITK/Code/Review/Statistics/itkMembershipSample.txx new file mode 100644 index 0000000000..ef99d47e5c --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMembershipSample.txx @@ -0,0 +1,170 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMembershipSample.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMembershipSample_txx +#define __itkMembershipSample_txx + +namespace itk { +namespace Statistics { + +template< class TSample > +MembershipSample< TSample > +::MembershipSample() +{ + this->m_NumberOfClasses = 0; +} + +template< class TSample > +void +MembershipSample< TSample > +::SetNumberOfClasses(unsigned int numberOfClasses) +{ + m_NumberOfClasses = numberOfClasses; + m_ClassSamples.resize(m_NumberOfClasses); + for ( unsigned int i = 0; i < m_NumberOfClasses; i++ ) + { + m_ClassSamples[i] = ClassSampleType::New(); + (m_ClassSamples[i])->SetSample(this->GetSample()); + } +} + +template< class TSample > +inline void +MembershipSample< TSample > +::AddInstance(const ClassLabelType &classLabel, const InstanceIdentifier &id) +{ + m_ClassLabelHolder[id] = classLabel; + int classIndex = this->GetInternalClassLabel(classLabel); + if ( classIndex == -1 ) + { + m_UniqueClassLabels.push_back(classLabel); + classIndex = m_UniqueClassLabels.size() - 1; + } + + (m_ClassSamples[classIndex])->AddInstance(id); +} + +template< class TSample > +inline unsigned int +MembershipSample< TSample > +::GetClassLabel(const InstanceIdentifier &id) const +{ + return (*(m_ClassLabelHolder.find(id))).second; +} + +template< class TSample > +inline int +MembershipSample< TSample > +::GetInternalClassLabel(const ClassLabelType classLabel) const +{ + for ( unsigned int i = 0; i < m_UniqueClassLabels.size(); i++ ) + { + if ( m_UniqueClassLabels[i] == classLabel ) + { + return i; + } + } + + return -1; +} + +template< class TSample > +const typename MembershipSample< TSample>::ClassLabelHolderType +MembershipSample< TSample > +::GetClassLabelHolder() const +{ + return m_ClassLabelHolder; +} + +template< class TSample > +const typename MembershipSample< TSample >::ClassSampleType* +MembershipSample< TSample > +::GetClassSample(const ClassLabelType &classLabel) const +{ + int classIndex = this->GetInternalClassLabel(classLabel); + return m_ClassSamples[classIndex]; +} + +template< class TSample > +inline const typename MembershipSample< TSample >::MeasurementVectorType & +MembershipSample< TSample > +::GetMeasurementVector(const InstanceIdentifier &id) const +{ + return m_Sample->GetMeasurementVector(id); +} + +template< class TSample > +inline typename MembershipSample< TSample >::MeasurementType +MembershipSample< TSample > +::GetMeasurement(const InstanceIdentifier &id, + const unsigned int &dimension) +{ + return m_Sample->GetMeasurement(id, dimension); +} + +template< class TSample > +inline typename MembershipSample< TSample >::AbsoluteFrequencyType +MembershipSample< TSample > +::GetFrequency(const InstanceIdentifier &id) const +{ + return m_Sample->GetFrequency(id); +} + +template< class TSample > +inline typename MembershipSample< TSample >::TotalAbsoluteFrequencyType +MembershipSample< TSample > +::GetTotalFrequency() const +{ + return m_Sample->GetTotalFrequency(); +} + +template< class TSample > +void +MembershipSample< TSample > +::Graft( const DataObject *thatObject ) +{ + this->Superclass::Graft(thatObject); + + // Most of what follows is really a deep copy, rather than grafting of + // output. Wish it were managed by pointers to bulk data. Sigh ! + + const Self *thatConst = dynamic_cast< const Self * >(thatObject); + if (thatConst) + { + Self *that = const_cast< Self * >(thatConst); + this->m_UniqueClassLabels = that->m_UniqueClassLabels; + this->m_ClassLabelHolder = that->m_ClassLabelHolder; + this->m_ClassSamples = that->m_ClassSamples; + this->m_Sample = that->m_Sample; + this->m_NumberOfClasses = that->m_NumberOfClasses; + } +} + +template< class TSample > +void +MembershipSample< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Sample: " << m_Sample.GetPointer() << std::endl; + os << indent << "NumberOfClasses: " << this->GetNumberOfClasses() << std::endl; +} + + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.cxx b/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.cxx new file mode 100644 index 0000000000..ac6605f7e5 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.cxx @@ -0,0 +1,46 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMinimumDecisionRule2.cxx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkMinimumDecisionRule2.h" + +namespace itk { +namespace Statistics { + +void +MinimumDecisionRule2::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} + +unsigned int +MinimumDecisionRule2::Evaluate(const MembershipVectorType &discriminantScores) const +{ + double min = discriminantScores[0]; + unsigned int minIndex = 0; + unsigned int i; + for (i = 1; i < discriminantScores.size(); i++) + { + if (discriminantScores[i] < min) + { + min = discriminantScores[i]; + minIndex = i; + } + } + return minIndex; +} + +} // end of namespace itk +} // end of namespace Statistics diff --git a/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.h b/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.h new file mode 100644 index 0000000000..96953eca98 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.h @@ -0,0 +1,65 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMinimumDecisionRule2.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMinimumDecisionRule2_h +#define __itkMinimumDecisionRule2_h + +#include "itkDecisionRule.h" + +namespace itk { +namespace Statistics { + +/** \class MinimumDecisionRule2 + * \brief A Decision rule that choose the class of which discriminant + * score is the largest. This class will replace the MinimumDecisionRule + * in Code/Common + */ + +class ITK_EXPORT MinimumDecisionRule2 : public DecisionRule +{ +public: + /** Standard class typedefs */ + typedef MinimumDecisionRule2 Self; + typedef DecisionRule Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro(MinimumDecisionRule2, DecisionRuleBase); + + /** Standard New() method support */ + itkNewMacro(Self); + + typedef Superclass::MembershipVectorType MembershipVectorType; + + + /** The return value of this function is a class label. + * Basically, using its internal logic based on the discriminant + * scores, this function decides best class label and return it. + */ + virtual unsigned int Evaluate( const MembershipVectorType &discriminantScores) const; + + +protected: + MinimumDecisionRule2() {} + virtual ~MinimumDecisionRule2() {} + void PrintSelf(std::ostream& os, Indent indent) const; +}; // end of class + +} // end of namespace itk +} // end of namespace Statistics + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMixtureModelComponentBase.h b/Utilities/ITK/Code/Review/Statistics/itkMixtureModelComponentBase.h new file mode 100644 index 0000000000..7dfbc541a3 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMixtureModelComponentBase.h @@ -0,0 +1,166 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMixtureModelComponentBase.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMixtureModelComponentBase_h +#define __itkMixtureModelComponentBase_h + +#include <vnl/vnl_vector.h> +#include <vnl/vnl_matrix.h> + +#include "itkArray.h" +#include "itkObject.h" +#include "itkMembershipFunctionBase.h" + +namespace itk { +namespace Statistics { + +/** \class MixtureModelComponentBase + * \brief base class for distribution modules that supports analytical way + * to update the distribution parameters + * + * This class expects that its subclasses (distribution components) should + * have analytical expressions for updating its paraters using only + * the measurement vectors and their associated weights. + * + * This class can be considered as a macro class that encapsulates the + * storage for the weights, model (subclasses of MembershipFunctionBase), + * and model parameter estimators (implemenation of analytical expressions). + * + * Subclasses of this class should define their own distribution specific + * membership function. For example, GaussianMixtureModelComponent class + * defines and creates a GaussianDensityFunction object for that matter. + * Subclasses should also cast such membership function object to + * MembershipFunctionBase object. By doing that, users can get pointers + * to membership functions from different distributional model + * + * \sa ExpectationMaximizationMixtureModelEstimator + */ + +template< class TSample > +class ITK_EXPORT MixtureModelComponentBase : + public Object +{ +public: + /**Standard class typedefs. */ + typedef MixtureModelComponentBase Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /**Standard Macros */ + itkTypeMacro(MixtureModelComponentBase, Object); + + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; + + /** typedef for the MembershipFunctionBase */ + typedef MembershipFunctionBase< MeasurementVectorType > + MembershipFunctionType; + + /** typedef of strorage for the weights */ + typedef Array< double > WeightArrayType; + + typedef Array< double > ParametersType; + + /** stores the sample pointer */ + virtual void SetSample(const TSample* sample); + + /** returns the sample pointer */ + const TSample* GetSample() const; + + /** returns the pointer to the membership function object. + * Subclasses of this class are responsible for creating the + * actual membership function objects and cast them to + * MembershipFunctionBase objects */ + MembershipFunctionType* GetMembershipFunction(); + + void SetMinimalParametersChange(double change) + { + m_MinimalParametersChange = change; + } + + double GetMinimalParametersChange() + { + return m_MinimalParametersChange; + } + + virtual void SetParameters(const ParametersType ¶meters); + + virtual ParametersType GetFullParameters() + { + return m_Parameters; + } + + /** sets the parameters modified tag. if one or more of the membership + * funtion's parameters are changed, then flag should be true */ + void AreParametersModified(bool flag); + + /** returns the value of parameter modified tag */ + bool AreParametersModified(); + + /** sets the index-th weight with the "value" */ + void SetWeight(unsigned int index, double value); + + /** returns the index-th weight */ + double GetWeight(unsigned int index) const; + + /** returns the membership score of the "measurements" vector */ + double Evaluate(MeasurementVectorType& measurements); + + /** returns the pointer to the weights array */ + itkGetConstReferenceMacro( Weights, WeightArrayType ); + + virtual void Update(); + +protected: + MixtureModelComponentBase(); + virtual ~MixtureModelComponentBase(); + void PrintSelf(std::ostream& os, Indent indent) const; + + /** stores the pointer to the membership function. + * subclasses use this funtion to store their membership function + * object after dynamic creation */ + void SetMembershipFunction(MembershipFunctionType* function); + + virtual void GenerateData() = 0; + +private: + /** target sample data pointer */ + const TSample* m_Sample; + + double m_MinimalParametersChange; + + ParametersType m_Parameters; + + /** SmartPointer to the memberhip function - usually density function */ + MembershipFunctionType* m_MembershipFunction; + + /** weights array */ + WeightArrayType m_Weights; + + /** indicative flag of membership function's parameter changes */ + bool m_ParametersModified; + +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkMixtureModelComponentBase.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkMixtureModelComponentBase.txx b/Utilities/ITK/Code/Review/Statistics/itkMixtureModelComponentBase.txx new file mode 100644 index 0000000000..de08610693 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkMixtureModelComponentBase.txx @@ -0,0 +1,186 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMixtureModelComponentBase.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMixtureModelComponentBase_txx +#define __itkMixtureModelComponentBase_txx + +#include "itkMixtureModelComponentBase.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +MixtureModelComponentBase< TSample > +::MixtureModelComponentBase() +{ + m_Sample = 0; + m_MembershipFunction = 0; + m_MinimalParametersChange = 1.0e-06; + m_ParametersModified = true; +} + +template< class TSample > +MixtureModelComponentBase< TSample > +::~MixtureModelComponentBase() +{ +} + +template< class TSample > +void +MixtureModelComponentBase< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Sample: "; + if ( m_Sample != 0 ) + { + os << m_Sample << std::endl; + } + else + { + os << "not set." << std::endl; + } + + os << indent << "Membership Function: "; + if ( m_MembershipFunction != 0 ) + { + os << m_MembershipFunction << std::endl; + } + else + { + os << "not instantiated yet." << std::endl; + } + + os << indent << "Weights Array: "; + os << m_Weights << std::endl; + + os << indent << "Parameters are modified: " << m_ParametersModified + << std::endl; +} + +template< class TSample > +void +MixtureModelComponentBase< TSample > +::SetSample(const TSample* sample) +{ + m_Sample = sample; + m_Weights = WeightArrayType(m_Sample->Size()); +} + +template< class TSample > +const TSample* +MixtureModelComponentBase< TSample > +::GetSample() const +{ + return m_Sample; +} + +template< class TSample > +void +MixtureModelComponentBase< TSample > +::SetParameters(const ParametersType ¶meters) +{ + if ( m_Parameters != parameters ) + { + m_Parameters = parameters; + this->AreParametersModified(true); + } +} + +template< class TSample > +bool +MixtureModelComponentBase< TSample > +::AreParametersModified() +{ + return m_ParametersModified; +} + +template< class TSample > +void +MixtureModelComponentBase< TSample > +::AreParametersModified(bool flag) +{ + m_ParametersModified = flag; +} + +template< class TSample > +void +MixtureModelComponentBase< TSample > +::SetMembershipFunction(MembershipFunctionType* function) +{ + m_MembershipFunction = function; +} + +template< class TSample > +typename MixtureModelComponentBase< TSample >::MembershipFunctionType* +MixtureModelComponentBase< TSample > +::GetMembershipFunction() +{ + return m_MembershipFunction; +} + +template< class TSample > +inline double +MixtureModelComponentBase< TSample > +::Evaluate(MeasurementVectorType& measurements) +{ + return m_MembershipFunction->Evaluate(measurements); +} + +template< class TSample > +inline void +MixtureModelComponentBase< TSample > +::SetWeight(unsigned int index, double value) +{ + if( index < m_Weights.size() ) + { + (m_Weights)[index] = value; + } + else + { + itkExceptionMacro("Weight array is not allocated."); + } +} + +template< class TSample > +inline double +MixtureModelComponentBase< TSample > +::GetWeight(unsigned int index) const +{ + if( index < m_Weights.Size() ) + { + return m_Weights[index]; + } + else + { + itkExceptionMacro("Weight array is not allocated."); + } +} + +template< class TSample > +void +MixtureModelComponentBase< TSample > +::Update() +{ + this->GenerateData(); +} + + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkNeighborhoodSampler.h b/Utilities/ITK/Code/Review/Statistics/itkNeighborhoodSampler.h new file mode 100644 index 0000000000..4707ffb0a2 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkNeighborhoodSampler.h @@ -0,0 +1,93 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkNeighborhoodSampler.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkNeighborhoodSampler_h +#define __itkNeighborhoodSampler_h + +#include "itkSampleToSubsampleFilter.h" +#include "itkSimpleDataObjectDecorator.h" + +namespace itk { +namespace Statistics { + +/** \class NeighborhoodSampler + * \brief Generates a Subsample out of a Sample, based on a user-provided + * distance to a MeasurementVector. + * + * This filter will take as input a Sample and produce as output a Subsample + * containing the instances of the sample that are at a distance lower than + * a user-provided threshold from a user-provided measurement vector. + * + * \sa Sample, Subsample + * + * \sa SampleToSubsampleFilter + * + */ + +template< class TSample > +class ITK_EXPORT NeighborhoodSampler : public SampleToSubsampleFilter< TSample > +{ +public: + /** Standard class typedefs. */ + typedef NeighborhoodSampler Self; + typedef SampleToSubsampleFilter< TSample > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Standard macros */ + itkTypeMacro(NeighborhoodSampler, SampleToSubsampleFilter); + itkNewMacro(Self); + + /** Typedefs for Measurement vector, measurement, Instance Identifier, + * frequency, size, size element value from the template argument TSample */ + itkSuperclassTraitMacro( SampleType ) + itkSuperclassTraitMacro( MeasurementVectorType ) + itkSuperclassTraitMacro( MeasurementType ) + itkSuperclassTraitMacro( InstanceIdentifier ) + itkSuperclassTraitMacro( SubsampleType ) + itkSuperclassTraitMacro( OutputType ) + + /** Type of the distance radius. */ + typedef double RadiusType; + + /** Type of DataObjects to use for distance radius input. */ + typedef SimpleDataObjectDecorator< RadiusType > InputRadiusObjectType; + + + /** Method to set the input value of the Radius */ + itkSetDecoratedInputMacro( Radius, RadiusType, 1 ); + +protected: + NeighborhoodSampler(); + virtual ~NeighborhoodSampler(); + void PrintSelf(std::ostream& os, Indent indent) const; + + void GenerateData(); + +private: + NeighborhoodSampler(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkNeighborhoodSampler.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkNeighborhoodSampler.txx b/Utilities/ITK/Code/Review/Statistics/itkNeighborhoodSampler.txx new file mode 100644 index 0000000000..da6b38b4e9 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkNeighborhoodSampler.txx @@ -0,0 +1,80 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkNeighborhoodSampler.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkNeighborhoodSampler_txx +#define __itkNeighborhoodSampler_txx + +#include "itkNeighborhoodSampler.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +NeighborhoodSampler< TSample > +::NeighborhoodSampler() +{ +} + +template< class TSample > +NeighborhoodSampler< TSample > +::~NeighborhoodSampler() +{ +} + +template < class TSample > +void +NeighborhoodSampler< TSample > +::GenerateData() +{ + const SampleType * inputSample = this->GetInput(); + + SubsampleType * outputSubSample = + static_cast<SubsampleType*>(this->ProcessObject::GetOutput(0)); + + outputSubSample->SetSample( inputSample ); + outputSubSample->Clear(); + + const InputRadiusObjectType * radiusObject = this->GetRadiusInput(); + + if( radiusObject == NULL ) + { + itkExceptionMacro("Radius input is missing"); + } + + // FIXME : What should follow here ? + // + // const RadiusType radius = radiusObject->Get(); + // + +} + + +template < class TSample > +void +NeighborhoodSampler< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + this->Superclass::PrintSelf(os,indent); + // m_Radius + os << indent << "Radius: " << this->GetRadiusInput() << std::endl; +} + + +} // end of namespace Statistics +} // end of namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkNormalVariateGenerator.cxx b/Utilities/ITK/Code/Review/Statistics/itkNormalVariateGenerator.cxx new file mode 100644 index 0000000000..d7a03d59ae --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkNormalVariateGenerator.cxx @@ -0,0 +1,361 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkNormalVariateGenerator.cxx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include <vnl/vnl_math.h> +#include <math.h> + +#include "itkNormalVariateGenerator.h" + +namespace itk { +namespace Statistics { + +NormalVariateGenerator::NormalVariateGenerator() +{ + m_Scale = ((double) 30000000.0); + m_Rscale = ((double) (1.0 / m_Scale)); + m_Rcons = ((double) (1.0 / (2.0 * 1024.0 * 1024.0 * 1024.0))); + m_ELEN = 7; /* LEN must be 2 ** ELEN */ + m_LEN = 128; + m_LMASK = (4 * (m_LEN-1)); + m_TLEN = (8*m_LEN); + m_Vec1 = new int[m_TLEN]; + + m_Gausssave = 0; + this->Initialize(0); +} + +NormalVariateGenerator::~NormalVariateGenerator() +{ + delete[] m_Vec1; +} + +void NormalVariateGenerator::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "Scale: " << m_Scale << std::endl; + os << indent << "Rscale: " << m_Rscale << std::endl; + os << indent << "Rcons: " << m_Rcons << std::endl; + os << indent << "ELEN: " << m_ELEN << std::endl; + os << indent << "LEN: " << m_LEN << std::endl; + os << indent << "LMASK: " << m_LMASK << std::endl; + os << indent << "TLEN: " << m_TLEN << std::endl; + + os << indent << "gaussfaze: " << m_Gaussfaze << std::endl; + os << indent << "gausssave: " << m_Gausssave << std::endl; + os << indent << "GScale: " << m_GScale << std::endl; + + os << indent << "vec1: " << m_Vec1 << std::endl; + os << indent << "nslew: " << m_Nslew << std::endl; + os << indent << "irs: " << m_Irs << std::endl; + os << indent << "lseed: " << m_Lseed << std::endl; + os << indent << "chic1: " << m_Chic1 << std::endl; + os << indent << "chic2: " << m_Chic2 << std::endl; + os << indent << "actualRSD: " << m_ActualRSD << std::endl; +} + +void NormalVariateGenerator::Initialize(int randomSeed) +{ + // m_Random Seed was originally getpid() + + double fake; + m_Lseed = randomSeed; + m_Irs = randomSeed; + m_Gaussfaze = 1; + m_Nslew = 0; + m_GScale = m_Rscale; +// At one stage, we need to generate a random variable Z such that +// (TLEN * Z*Z) has a Chi-squared-TLEN density. Now, a var with +// an approximate Chi-sq-K distn can be got as +// 0.5 * (C + A*n)**2 where n has unit Normal distn, +// A = (1 + 1 / (8K)), C*C = 2K - A*A (For large K) +// So we form Z as (sqrt (1 / 2TLEN)) * (C + A*n) +// or: +// Z = (sqrt (1/2TLEN)) * A * (B + n) +// where: +// B = C / A. +// We set m_Chic1 = A * vcl_sqrt(0.5 / TLEN), m_Chic2 = B + + fake = 1.0 + 0.125 / m_TLEN; // This is A + m_Chic2 = vcl_sqrt(2.0 * m_TLEN - fake*fake) / fake; + m_Chic1 = fake * vcl_sqrt(0.5 / m_TLEN); + + m_ActualRSD = 0.0; + return; +} + + +double NormalVariateGenerator::GetVariate() +{ + if (--m_Gaussfaze) + return m_GScale * m_Gausssave[m_Gaussfaze]; + else + return FastNorm(); +} + +/* ----------------------------------------------------- */ + + +double NormalVariateGenerator::FastNorm(void) +{ + int i; + int inc = 0; + int skew; + int stride; + int mask = 0; + int p; + int q; + int r; + int s; + int t; + int *pa = 0; + int *pb = 0; + int *pc = 0; + int *pd = 0; + int *pe; + int *p0 = 0; + int mtype; + int stype; + double ts; + double tr; + double tx; + double ty; + double tz; + + /* See if time to make a new set of 'original' deviates */ + /* or at least to correct for a drift in sum-of-squares */ + if (! (m_Nslew & 0xFF)) goto renormalize; + + startpass: + /* Count passes */ + m_Nslew ++; + /* Reset index into Saved values */ + m_Gaussfaze = m_TLEN - 1; /* We will steal the last one */ + /* Update pseudo-random and use to choose type of rotation */ + m_Lseed = 69069 * m_Lseed + 33331; + m_Irs = (m_Irs <= 0) ? ((m_Irs << 1) ^ 333556017):(m_Irs << 1); + t = m_Irs + m_Lseed; + if (t < 0) t = ~t; + /* This gives us 31 random bits in t */ + /* We need ELEN to fix initial index into LEN, ELEN-1 to fix an odd + stride, 2 to fix matrix type and maybe 1 for scantype, making + 2*ELEN + 2 in all, and leaving 29 - 2*ELEN unused + */ + t = t >> (29 - 2*m_ELEN); /* Discard unwanted digits */ + skew = (m_LEN-1) & t; t = t >> m_ELEN; + skew = 4 * skew; /* To give a word index to group of 4 */ + stride = (m_LEN/2 -1 ) & t; t = t >> (m_ELEN-1); + stride = 8 * stride + 4; /* To give an odd num of 4-groups */ + mtype = t & 3; + /* Leaves a bit for stype, but not currently used */ + + /* Use last bits of m_Nslew to determine scanning pattern */ + stype = m_Nslew & 3; + switch (stype) + { + case 0: /* From consecutive in top to scattered in bot */ + inc = 1; + mask = m_LMASK; + pa = m_Vec1; pb = pa + m_LEN; pc = pb + m_LEN; pd = pc + m_LEN; + p0 = m_Vec1 + 4 * m_LEN; + goto scanset; + case 1: /* From consec in bot to scatt in top */ + inc = 1; + mask = m_LMASK; + pa = m_Vec1 + 4 * m_LEN; pb = pa + m_LEN; pc = pb + m_LEN; pd = pc + m_LEN; + p0 = m_Vec1; + goto scanset; + case 2: /* From consec in even to scatt in odd */ + inc = 2; + mask = 2*m_LMASK; skew *= 2; stride *= 2; + pa = m_Vec1 + 1; pb = pa + 2*m_LEN; pc = pb + 2*m_LEN; pd = pc + 2*m_LEN; + p0 = m_Vec1; + goto scanset; + case 3: /* From consec in odd to scatt in even */ + inc = 2; + mask = 2*m_LMASK; skew *= 2; stride *= 2; + pa = m_Vec1; pb = pa + 2*m_LEN; pc = pb + 2*m_LEN; pd = pc + 2*m_LEN; + p0 = m_Vec1 + 1; + goto scanset; + } /* End of scan pattern cases */ + +scanset: + m_Gausssave = m_Vec1; + /* Set loop count */ + i = m_LEN; + + /* Use mtype to select matrix */ + switch (mtype) + { + case 0: goto matrix0; + case 1: goto matrix1; + case 2: goto matrix2; + case 3: goto matrix3; + } + +matrix0: + pa += (inc * (m_LEN-1)); +mpass0: + skew = (skew + stride) & mask; + pe = p0 + skew; + p = -*pa; q = -*pb; r = *pc; s = *pd; + t = (p + q + r + s) >> 1; + p = t - p; q = t - q; r = t - r; s = t - s; + /* Have new values in p,q,r,s. Place and save replaced vals */ + t = -*pe; *pe = p; pe += inc; + p = *pe; *pe = q; pe += inc; + q = -*pe; *pe = r; pe += inc; + r = *pe; *pe = s; + /* Have vals in p,q,r,t */ + s = (p + q + r + t) >> 1; + *pa = s - p; pa -= inc; + *pb = s - q; pb += inc; + *pc = s - r; pc += inc; + *pd = s - t; pd += inc; + if (--i) goto mpass0; + goto endpass; + + matrix1: + pb += (inc * (m_LEN-1)); + mpass1: + skew = (skew + stride) & mask; + pe = p0 + skew; + p = -*pa; q = *pb; r = *pc; s = -*pd; + t = (p + q + r + s) >> 1; + p = t - p; q = t - q; r = t - r; s = t - s; + /* Have new values in p,q,r,s. Place and save replaced vals */ + t = *pe; *pe = p; pe += inc; + p = -*pe; *pe = q; pe += inc; + q = -*pe; *pe = r; pe += inc; + r = *pe; *pe = s; + /* Have vals in p,q,r,t */ + s = (p + q + r + t) >> 1; + *pa = s - p; pa += inc; + *pb = s - t; pb -= inc; + *pc = s - q; pc += inc; + *pd = s - r; pd += inc; + if (--i) goto mpass1; + goto endpass; + + matrix2: + pc += (inc * (m_LEN-1)); + mpass2: + skew = (skew + stride) & mask; + pe = p0 + skew; + p = *pa; q = -*pb; r = *pc; s = -*pd; + t = (p + q + r + s) >> 1; + p = t - p; q = t - q; r = t - r; s = t - s; + /* Have new values in p,q,r,s. Place and save replaced vals */ + t = *pe; *pe = p; pe += inc; + p = *pe; *pe = q; pe += inc; + q = -*pe; *pe = r; pe += inc; + r = -*pe; *pe = s; + /* Have vals in p,q,r,t */ + s = (p + q + r + t) >> 1; + *pa = s - r; pa += inc; + *pb = s - p; pb += inc; + *pc = s - q; pc -= inc; + *pd = s - t; pd += inc; + if (--i) goto mpass2; + goto endpass; + + matrix3: + pd += (inc * (m_LEN-1)); + mpass3: + skew = (skew + stride) & mask; + pe = p0 + skew; + p = *pa; q = *pb; r = -*pc; s = -*pd; + t = (p + q + r + s) >> 1; + p = t - p; q = t - q; r = t - r; s = t - s; + /* Have new values in p,q,r,s. Place and save replaced vals */ + t = -*pe; *pe = p; pe += inc; + p = *pe; *pe = q; pe += inc; + q = *pe; *pe = r; pe += inc; + r = -*pe; *pe = s; + /* Have vals in p,q,r,t */ + s = (p + q + r + t) >> 1; + *pa = s - q; pa += inc; + *pb = s - r; pb += inc; + *pc = s - t; pc += inc; + *pd = s - p; pd -= inc; + if (--i) goto mpass3; + goto endpass; + + endpass: + /* Choose a value for m_GScale which will make the sum-of-squares have + the variance of Chi-Sq (TLEN), i.e., 2*TLEN. Choose a value from + Chi-Sq (TLEN) using the method descibed in initnorm. + The Normal variate is obtained from m_Gausssave[TLEN-1], which is + not used by the caller. + */ + ts = m_Chic1 * (m_Chic2 + m_GScale * m_Vec1 [m_TLEN-1]); + /* m_TLEN * ts * ts has ChiSq (m_TLEN) distribution */ + m_GScale = m_Rscale * ts * m_ActualRSD; + return (m_GScale * m_Vec1[0]); + + renormalize: + if (m_Nslew & 0xFFFF) goto recalcsumsq; + /* Here, replace the whole pool with conventional Normal variates */ + ts = 0.0; + p = 0; + nextpair: + m_Lseed = 69069 * m_Lseed + 33331; + m_Irs = (m_Irs <= 0) ? ((m_Irs << 1) ^ 333556017):(m_Irs << 1); + r = m_Irs + m_Lseed; + tx = m_Rcons * r; + m_Lseed = 69069 * m_Lseed + 33331; + m_Irs = (m_Irs <= 0) ? ((m_Irs << 1) ^ 333556017):(m_Irs << 1); + r = m_Irs + m_Lseed; + ty = m_Rcons * r; + tr = tx * tx + ty * ty; + if ((tr > 1.0) || (tr < 0.1)) goto nextpair; + m_Lseed = 69069 * m_Lseed + 33331; + m_Irs = (m_Irs <= 0) ? ((m_Irs << 1) ^ 333556017):(m_Irs << 1); + r = m_Irs + m_Lseed; + if (r < 0) r = ~r; + tz = -2.0 * vcl_log((r + 0.5) * m_Rcons); /* Sum of squares */ + ts += tz; + tz = vcl_sqrt(tz / tr ); + m_Vec1 [p++] = (int) (m_Scale * tx * tz); + m_Vec1 [p++] = (int) (m_Scale * ty * tz); + if (p < m_TLEN) goto nextpair; + /* Horrid, but good enough */ + /* Calc correction factor to make sum of squares = TLEN */ + ts = m_TLEN / ts; /* Should be close to 1.0 */ + tr = vcl_sqrt(ts); + for (p = 0; p < m_TLEN; p++) + { + tx = m_Vec1 [p] * tr; + m_Vec1 [p] = (int) ((tx < 0.0) ? (tx - 0.5) : (tx + 0.5)); + } + + recalcsumsq: + /* Calculate actual sum of squares for correction */ + ts = 0.0; + for (p = 0; p < m_TLEN; p++) + { + tx = m_Vec1[p]; + ts += (tx * tx); + } + /* Now ts should be Scale*Scale*TLEN or thereabouts */ + ts = vcl_sqrt(ts / (m_Scale * m_Scale * m_TLEN)); + m_ActualRSD = 1.0 / ts; /* Reciprocal of actual Standard Devtn */ + goto startpass; + +} + +} // end of name space Statistics +} // end of name space itk diff --git a/Utilities/ITK/Code/Review/Statistics/itkNormalVariateGenerator.h b/Utilities/ITK/Code/Review/Statistics/itkNormalVariateGenerator.h new file mode 100644 index 0000000000..29e5c103ec --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkNormalVariateGenerator.h @@ -0,0 +1,148 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkNormalVariateGenerator.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkNormalVariateGenerator_h +#define __itkNormalVariateGenerator_h + +#include "itkObjectFactory.h" +#include "itkRandomVariateGeneratorBase.h" + +namespace itk { +namespace Statistics { + +/** \class NormalVariateGenerator + * \brief Normal random variate generator + * + * This generation method was initially developed and implemented by + * Martin Styner, University of North Carolina at Chapel Hill, + * and his colleagues. + * + * You should run Initialize() function before call GetNormalVariate() + * function. + * + * The followings are original comments. + * + * Revision date 31 May 1996 + * This is a revised version of the algorithm decribed in + * + * ACM Transactions on Mathematical Software, Vol 22, No 1 + * March 1996, pp 119-127. + * + * It is somewhat faster, and uses less memory as the vector of variates is + * updated in-situ. It has passed all the same statistical tests as decribed + * in the TOMS article, plus others. Seems OK so far. + * + * Works well with total pool of 1024 variates, and does not need + * two vectors of this size, so does less damage to cache. + * Has been tested for frequency of tail values which + * should occur once in a million. OK. Other usual tests OK. + * About 13 % faster than TOMS version. + * + * FAST GENERATOR OF PSEUDO-RANDOM UNIT NORMAL VARIATES + * + * C.S.Wallace, Monash University, 1994 + * + * To use this code, files needing to call the generator should #include the + * file "FastNorm.h" and be linked with the maths library (-lm) + * FastNorm.h contains declaration of the initialization routine + * 'initnorm()', definition of a macro 'FastGauss' used to generate variates, + * and three variables used in the macro. + * Read below for calling conventions. + * + * THIS CODE ASSUMES TWO'S-COMPLEMENT 32-BIT INTEGER ARITHMATIC. IT ALSO + * ASSUMES THE 'C' COMPILER COMPILES THE LEFT-SHIFT OPERATOR "<<" AS A LOGICAL + * SHIFT, DISCARDING THE SIGN DIGIT AND SHIFTING IN ZEROS ON THE RIGHT, SO + * " X << 1" IS EQUIVALENT TO " X+X ". IT ALSO ASSUMES THE RIGHT-SHIFT + * OPERATOR ">>" IS SIGN-PRESERVING, SO ( -2 >> 1) = -1, ( -1>>1) = -1. + + + * + * A fast generator of pseudo-random variates from the unit Normal + * distribution. It keeps a pool of about 1000 variates, and generates new + * ones by picking 4 from the pool, rotating the 4-vector with these as its + * components, and replacing the old variates with the components of the + * rotated vector. + * + * + * The program should initialize the generator by calling + * initnorm(seed) + * with seed a int integer seed value. Different seed values will give + * different sequences of Normals. + * Then, wherever the program needs a new Normal variate, it should + * use the macro FastGauss, e.g. in statements like: + * x = FastGauss; (Sets x to a random Normal value) + * + * + * \ingroup Statistics + */ +class ITK_EXPORT NormalVariateGenerator : + public RandomVariateGeneratorBase +{ +public: + /** Standard class typedefs. */ + typedef NormalVariateGenerator Self; + typedef RandomVariateGeneratorBase Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(NormalVariateGenerator, + RandomVariateGeneratorBase ); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** generate random number table */ + void Initialize(int randomSeed); + + /** get a variate using FastNorm function */ + double GetVariate(); + +protected: + NormalVariateGenerator(); + virtual ~NormalVariateGenerator(); + virtual void PrintSelf(std::ostream& os, Indent indent) const; + + /** get a variate */ + double FastNorm (void); + +private: + double m_Scale; + double m_Rscale; + double m_Rcons; + int m_ELEN; + int m_LEN; + int m_LMASK; + int m_TLEN; + + int m_Gaussfaze; + int * m_Gausssave; + + double m_GScale; + + int * m_Vec1; + int m_Nslew; + int m_Irs; + int m_Lseed; + double m_Chic1; + double m_Chic2; + double m_ActualRSD; + +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.h b/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.h new file mode 100644 index 0000000000..6bf36e6902 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.h @@ -0,0 +1,287 @@ +/*========================================================================= + +Program: Insight Segmentation & Registration Toolkit +Module: $RCSfile: itkPointSetToListSampleAdaptor.h,v $ +Language: C++ +Date: $Date: 2009-05-22 12:55:07 $ +Version: $Revision: 1.3 $ + +Copyright (c) Insight Software Consortium. All rights reserved. +See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkPointSetToListSampleAdaptor_h +#define __itkPointSetToListSampleAdaptor_h + +#include <typeinfo> + +#include "itkPointSet.h" +#include "itkListSample.h" +#include "itkSmartPointer.h" + +namespace itk { +namespace Statistics { + +/** \class PointSetToListSampleAdaptor + * \brief This class provides ListSample interface to ITK PointSet + * + * After calling SetPointSet(PointSet*) method to plug-in + * the PointSet object, users can use Sample interfaces to access + * PointSet data. This adaptor assumes that the PointsContainer is + * actual storage for measurment vectors. In other words, PointSet's + * dimension equals to the measurement vectors size. This class totally ignores + * PointsDataContainer. + * + * \sa Sample, ListSample, PointSet + */ + +template < class TPointSet > +class ITK_EXPORT PointSetToListSampleAdaptor : + public ListSample< typename TPointSet::PointType > +{ +public: + /** Standard class typedefs */ + typedef PointSetToListSampleAdaptor Self; + typedef ListSample< typename TPointSet::PointType > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(PointSetToListSampleAdaptor, ListSample); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** the number of components in a measurement vector */ + itkStaticConstMacro(MeasurementVectorSize, unsigned int, + TPointSet::PointDimension); + + /** PointSet typedefs */ + typedef TPointSet PointSetType; + typedef typename TPointSet::Pointer PointSetPointer; + typedef typename TPointSet::ConstPointer PointSetConstPointer; + typedef typename TPointSet::PointsContainer PointsContainer; + typedef typename TPointSet::PointsContainerPointer PointsContainerPointer; + typedef typename TPointSet::PointsContainerConstPointer PointsContainerConstPointer; + typedef typename TPointSet::PointsContainerIterator PointsContainerIteratorType; + typedef typename TPointSet::PointsContainerConstIterator PointsContainerConstIteratorType; + typedef typename TPointSet::PointType PointType; + + + /** Superclass typedefs for Measurement vector, measurement, + * Instance Identifier, frequency, size, size element value */ + itkSuperclassTraitMacro( MeasurementType ) + itkSuperclassTraitMacro( MeasurementVectorType ) + itkSuperclassTraitMacro( AbsoluteFrequencyType ) + itkSuperclassTraitMacro( TotalAbsoluteFrequencyType ) + itkSuperclassTraitMacro( MeasurementVectorSizeType ) + itkSuperclassTraitMacro( InstanceIdentifier ) + + typedef MeasurementVectorType ValueType; + + /** Method to set the point set */ + void SetPointSet(const TPointSet* pointSet); + + /** Method to get the point set */ + const TPointSet* GetPointSet(); + + /** returns the number of measurement vectors in this container */ + InstanceIdentifier Size() const; + + /** returns the measurement vector that is specified by the instance + * identifier argument. */ + const MeasurementVectorType & GetMeasurementVector( InstanceIdentifier id ) const; + + /** returns 1 as other subclasses of ListSampleBase does */ + AbsoluteFrequencyType GetFrequency( InstanceIdentifier id ) const; + + /** returns the size of this container */ + TotalAbsoluteFrequencyType GetTotalFrequency() const; + + /** \class ListSample::ConstIterator */ + class ConstIterator + { + friend class PointSetToListSampleAdaptor; + public: + + ConstIterator( const PointSetToListSampleAdaptor * adaptor ) + { + *this = adaptor->Begin(); + } + + ConstIterator(const ConstIterator &iter) + { + m_Iter = iter.m_Iter; + m_InstanceIdentifier = iter.m_InstanceIdentifier; + } + + ConstIterator& operator=( const ConstIterator & iter ) + { + m_Iter = iter.m_Iter; + m_InstanceIdentifier = iter.m_InstanceIdentifier; + return *this; + } + + AbsoluteFrequencyType GetFrequency() const + { + return 1; + } + + const MeasurementVectorType & GetMeasurementVector() const + { + return (const MeasurementVectorType&) m_Iter.Value(); + } + + InstanceIdentifier GetInstanceIdentifier() const + { + return m_InstanceIdentifier; + } + + ConstIterator& operator++() + { + ++m_Iter; + ++m_InstanceIdentifier; + return *this; + } + + bool operator!=(const ConstIterator &it) + { + return (m_Iter != it.m_Iter); + } + + bool operator==(const ConstIterator &it) + { + return (m_Iter == it.m_Iter); + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // This method should only be available to the ListSample class + ConstIterator( + PointsContainerConstIteratorType iter, + InstanceIdentifier iid) + { + m_Iter = iter; + m_InstanceIdentifier = iid; + } + + // This method is purposely not implemented + ConstIterator(); + + private: + PointsContainerConstIteratorType m_Iter; + InstanceIdentifier m_InstanceIdentifier; + }; + + /** \class PointSetToListSampleAdaptor::Iterator */ + class Iterator : public ConstIterator + { + + friend class PointSetToListSampleAdaptor; + + public: + + Iterator(Self * adaptor):ConstIterator(adaptor) + { + } + + Iterator(const Iterator &iter):ConstIterator( iter ) + { + } + + Iterator& operator =(const Iterator & iter) + { + this->ConstIterator::operator=( iter ); + return *this; + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // To ensure const-correctness these method must not be in the public API. + // The are purposly not implemented, since they should never be called. + Iterator(); + Iterator(const Self * adaptor); + Iterator( PointsContainerConstIteratorType iter, InstanceIdentifier iid); + Iterator(const ConstIterator & it); + ConstIterator& operator=(const ConstIterator& it); + Iterator( + PointsContainerIteratorType iter, + InstanceIdentifier iid):ConstIterator( iter, iid ) + { + } + + private: + }; + + + /** returns an iterator that points to the beginning of the container */ + Iterator Begin() + { + PointsContainerPointer nonConstPointsDataContainer = + const_cast< PointsContainer * > (m_PointsContainer.GetPointer()); + Iterator iter(nonConstPointsDataContainer->Begin(), 0); + return iter; + } + + /** returns an iterator that points to the end of the container */ + Iterator End() + { + PointsContainerPointer nonConstPointsDataContainer = + const_cast< PointsContainer * > (m_PointsContainer.GetPointer()); + + Iterator iter(nonConstPointsDataContainer->End(), m_PointsContainer->Size()); + return iter; + } + + /** returns an iterator that points to the beginning of the container */ + ConstIterator Begin() const + { + ConstIterator iter(m_PointsContainer->Begin(), 0); + return iter; + } + + /** returns an iterator that points to the end of the container */ + ConstIterator End() const + { + ConstIterator iter(m_PointsContainer->End(), m_PointsContainer->Size()); + return iter; + } + + +protected: + PointSetToListSampleAdaptor(); + + virtual ~PointSetToListSampleAdaptor() {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + PointSetToListSampleAdaptor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** the PointSet data source pointer */ + PointSetConstPointer m_PointSet; + + /** the points container which will be actually used for storing + * measurement vectors */ + PointsContainerConstPointer m_PointsContainer; + + /** temporary points for conversions */ + mutable PointType m_TempPoint; + +}; // end of class PointSetToListSampleAdaptor + +} // end of namespace Statistics +} // end of namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkPointSetToListSampleAdaptor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.txx b/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.txx new file mode 100644 index 0000000000..b35b20cc66 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.txx @@ -0,0 +1,131 @@ +/*========================================================================= + +Program: Insight Segmentation & Registration Toolkit +Module: $RCSfile: itkPointSetToListSampleAdaptor.txx,v $ +Language: C++ +Date: $Date: 2009-05-08 16:55:05 $ +Version: $Revision: 1.2 $ + +Copyright (c) Insight Software Consortium. All rights reserved. +See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkPointSetToListSampleAdaptor_txx +#define __itkPointSetToListSampleAdaptor_txx + +#include "itkPointSetToListSampleAdaptor.h" + +namespace itk { +namespace Statistics { + +template < class TPointSet > +PointSetToListSampleAdaptor< TPointSet > +::PointSetToListSampleAdaptor() +{ + m_PointSet = 0; +} + +template < class TPointSet > +void +PointSetToListSampleAdaptor< TPointSet > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "PointSet: "; + if ( m_PointSet.IsNotNull() ) + { + os << m_PointSet << std::endl; + } + else + { + os << "not set." << std::endl; + } +} + +template < class TPointSet > +void +PointSetToListSampleAdaptor< TPointSet > +::SetPointSet( const TPointSet* pointSet) +{ + m_PointSet = pointSet; + m_PointsContainer = pointSet->GetPoints(); + + this->Modified(); +} + +template < class TPointSet > +const TPointSet* +PointSetToListSampleAdaptor< TPointSet > +::GetPointSet() +{ + if( m_PointSet.IsNull() ) + { + itkExceptionMacro("Point set has not been set yet"); + } + + return m_PointSet.GetPointer(); +} + +/** returns the number of measurement vectors in this container*/ +template < class TPointSet > +typename PointSetToListSampleAdaptor< TPointSet >::InstanceIdentifier +PointSetToListSampleAdaptor< TPointSet > +::Size() const +{ + if( m_PointSet.IsNull() ) + { + itkExceptionMacro("Point set has not been set yet"); + } + + return m_PointsContainer->Size(); +} + +template < class TPointSet > +inline const typename PointSetToListSampleAdaptor< TPointSet >::MeasurementVectorType & +PointSetToListSampleAdaptor< TPointSet > +::GetMeasurementVector( InstanceIdentifier id ) const +{ + if( m_PointSet.IsNull() ) + { + itkExceptionMacro("Point set has not been set yet"); + } + + m_PointSet->GetPoint(id, &m_TempPoint); + return (MeasurementVectorType&) m_TempPoint; +} + +template < class TPointSet > +inline typename PointSetToListSampleAdaptor< TPointSet >::AbsoluteFrequencyType +PointSetToListSampleAdaptor< TPointSet > +::GetFrequency( InstanceIdentifier ) const +{ + if( m_PointSet.IsNull() ) + { + itkExceptionMacro("Point set has not been set yet"); + } + + return 1; +} + +template < class TPointSet > +typename PointSetToListSampleAdaptor< TPointSet >::TotalAbsoluteFrequencyType +PointSetToListSampleAdaptor< TPointSet > +::GetTotalFrequency() const +{ + if( m_PointSet.IsNull() ) + { + itkExceptionMacro("Point set has not been set yet"); + } + + return this->Size(); +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkProbabilityDistribution.h b/Utilities/ITK/Code/Review/Statistics/itkProbabilityDistribution.h new file mode 100644 index 0000000000..19427d70ea --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkProbabilityDistribution.h @@ -0,0 +1,171 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkProbabilityDistribution.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkProbabilityDistribution_h +#define __itkProbabilityDistribution_h + +#include "itkObject.h" +#include "itkObjectFactory.h" +#include "itkArray.h" + +namespace itk { +namespace Statistics { + +/** \class ProbabilityDistribution + * \brief ProbabilityDistribution class defines common interface for + * statistical distributions (pdfs, cdfs, etc.). + * + * ProbabilityDistribution defines a common interface for parameteric + * and non-parametric distributions. ProbabilityDistribution provides + * access to the probability density function (pdf), the cumulative + * distribution function (cdf), and the inverse cumulative + * distribution function. + * + * ProbabilityDistribution also defines an abstract interface for + * setting parameters of distribution (mean/variance for a Gaussian, + * degrees of freedom for Student-t, etc.). + * + * Note that nonparametric subclasses of ProbabilityDistribution are + * possible. For instance, a nonparametric implementation may use a + * histogram or kernel density function to model the distribution. + * + * The EvaluatePDF(), EvaluateCDF, EvaluateInverseCDF() methods are + * all virtual, allowing algorithms to be written with an abstract + * interface to a distribution (with said distribution provided to the + * algorithm at run-time). Static methods, not requiring an instance + * of the distribution, are also allowed. The static methods allow + * for optimized access to distributions when the distribution is + * known a priori to the algorithm. + * + * ProbabilityDistributions are univariate. Multivariate versions may + * be provided under a separate superclass (since the parameters to the + * pdf and cdf would have to be vectors not scalars). Perhaps this + * class will be named MultivariateProbabilityDistribution. + * + * ProbabilityDistributions can be used for standard statistical + * tests: Z-scores, t-tests, chi-squared tests, F-tests, etc. + * + * \note This work is part of the National Alliance for Medical Image + * Computing (NAMIC), funded by the National Institutes of Health + * through the NIH Roadmap for Medical Research, Grant U54 EB005149. + * Information on the National Centers for Biomedical Computing + * can be obtained from http://nihroadmap.nih.gov/bioinformatics. + */ +class ITK_EXPORT ProbabilityDistribution : + public Object +{ +public: + /** Standard class typedefs */ + typedef ProbabilityDistribution Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Standard macros */ + itkTypeMacro(ProbabilityDistribution, Object); + + /** Type of the parameter vector. */ + typedef Array< double > ParametersType; + + /** Return the number of parameters that describe the + * distribution. For nonparametric distributions, this will be a + * function of the number of samples. */ + virtual unsigned long GetNumberOfParameters() const = 0; + + /** Get the parameters of the distribution. See concrete subclasses + * for the order of parameters. Subclasses may provide convenience + * methods for setting parameters, i.e. SetDegreesOfFreedom(), etc. */ + itkGetConstReferenceMacro(Parameters, ParametersType); + + /** Set the parameters of the distribution. See concrete subclasses + * for the order of the parameters. Subclasses may provide convenience + * methods for setting parameters, i.e. SetDegreesOfFreedom(), etc. */ + virtual void SetParameters(const ParametersType& params) + { + if ((params.GetSize() != m_Parameters.GetSize()) + || (params != m_Parameters)) + { + m_Parameters = params; + this->Modified(); + } + } + + /** Evaluate the probability density function (pdf). The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluatePDF(double x) const = 0; + + /** Evaluate the probability density function (pdf). The parameters + * for the distribution are passed as a parameters vector. See + * concrete subclasses for the ordering of parameters. */ + virtual double EvaluatePDF(double x, const ParametersType&) const = 0; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * of the distribution are assigned via SetParameters(). See + * concrete subclasses for the ordering of parameters. */ + virtual double EvaluateCDF(double x) const = 0; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * for the distribution are passed as a parameters vector. See + * concrete subclasses for the ordering of parameters. */ + virtual double EvaluateCDF(double x, const ParametersType&) const = 0; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * of the distribution are assigned via SetParameters(). See + * concrete subclasses for the ordering of parameters. */ + virtual double EvaluateInverseCDF(double p) const = 0; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * for the distribution are passed as a parameters vector. See + * concrete subclasses for the ordering of parameters. */ + virtual double EvaluateInverseCDF(double p, const ParametersType&) const = 0; + + /** Does this distribution have a mean? */ + virtual bool HasMean() const = 0; + + /** Does this distribution have a variance? */ + virtual bool HasVariance() const = 0; + + /** Get the mean of the distribution. If the mean does not exist, + * then quiet_NaN may is returned. */ + virtual double GetMean() const = 0; + + /** Get the variance of the distribution. If the variance does not + * exist, then quiet_NaN is returned. */ + virtual double GetVariance() const = 0; + +protected: + ProbabilityDistribution(void) {} + virtual ~ProbabilityDistribution(void) {} + void PrintSelf(std::ostream& os, Indent indent) const + { + Superclass::PrintSelf(os,indent); + os << indent << "Parameters: " << m_Parameters << std::endl; + } + + ParametersType m_Parameters; + +private: + ProbabilityDistribution(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end of namespace Statistics +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkRandomVariateGeneratorBase.h b/Utilities/ITK/Code/Review/Statistics/itkRandomVariateGeneratorBase.h new file mode 100644 index 0000000000..cbf6b97d24 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkRandomVariateGeneratorBase.h @@ -0,0 +1,55 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRandomVariateGeneratorBase.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRandomVariateGeneratorBase_h +#define __itkRandomVariateGeneratorBase_h + +#include "itkObject.h" + +namespace itk { +namespace Statistics { + +/** \class RandomVariateGeneratorBase + * \brief this class defines common interfaces for random variate generators + * + * \ingroup Statistics + */ +class ITK_EXPORT RandomVariateGeneratorBase : public Object +{ +public: + /** Standard class typedefs. */ + typedef RandomVariateGeneratorBase Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(RandomVariateGeneratorBase, Object ); + + /** get a variate using FastNorm function */ + virtual double GetVariate() = 0; + +protected: + RandomVariateGeneratorBase() {} + virtual ~RandomVariateGeneratorBase() {} + +private: +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkSample.h b/Utilities/ITK/Code/Review/Statistics/itkSample.h new file mode 100644 index 0000000000..cc2337c2a2 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSample.h @@ -0,0 +1,199 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSample.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSample_h +#define __itkSample_h + +#include "itkMacro.h" +#include "itkPoint.h" +#include "itkSize.h" +#include "itkDataObject.h" +#include "itkFixedArray.h" +#include "itkMeasurementVectorTraits.h" +#include "itkNumericTraits.h" +#include <vector> // for the size_type declaration + + +namespace itk { +namespace Statistics { + +/** \class Sample + * \brief A collection of measurements for statistical analysis + * + * Sample represents a set of measurements for statistical + * analysis. Sample is templated over a measurement vector. The + * measurement vector encapsulates the set of values associated with a + * single measurement. For instance, a measurement vector may contain + * an image intensity of a pixel and the gradient magnitude at that pixel. + * + * Data within a sample can be accessed via an + * InstanceIdentifier. InstanceIdentifiers have different forms and + * meanings depending on the type of sample. For ListSamples, the + * InstanceIdentifier is an index into the corresponding list. In this + * case, the InstanceIndentifier corresponds to a particular + * measurement stored in the Sample. For Histograms, an + * InstanceIdentifier corresponds to a particular bin in the + * N-dimensional histogram. In other words, the InstanceIdentifier in + * a histogram does not correspond to a specific measurement used to + * build the histogram but to the "bin" in which a number of original + * measurements were "accumulated". + * + * <b>Recent API changes:</b> + * The static const macro to get the length of a measurement vector, + * 'MeasurementVectorSize' has been removed to allow the length of a measurement + * vector to be specified at run time. Please use the function + * GetMeasurementVectorSize() instead. + * + */ + +template < class TMeasurementVector > +class ITK_EXPORT Sample : public DataObject +{ +public: + /** Standard class typedefs */ + typedef Sample Self; + typedef DataObject Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self > ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro(Sample, DataObject); + + /** MeasurementVector typedef support */ + typedef TMeasurementVector MeasurementVectorType; + + /** ValueType of a measurement (ValueType of a component of the + * MeasurementVector */ + typedef typename MeasurementVectorTraitsTypes< + MeasurementVectorType >::ValueType MeasurementType; + + /** Frequency value type */ + typedef MeasurementVectorTraits::AbsoluteFrequencyType AbsoluteFrequencyType; + + /** Total frequency type */ + typedef NumericTraits<AbsoluteFrequencyType>::AccumulateType TotalAbsoluteFrequencyType; + + /** InstanceIdentifier typedef. This identifier is a unique + * sequential id for each measurement vector in a Sample subclass. */ + typedef typename MeasurementVectorTraits::InstanceIdentifier InstanceIdentifier; + + /** Typedef for the length of each measurement vector */ + typedef unsigned int MeasurementVectorSizeType; + + /** Get the size of the sample (number of measurements) */ + virtual InstanceIdentifier Size() const = 0; + + /** Get the measurement associated with a particular + * InstanceIdentifier. */ + virtual const MeasurementVectorType & + GetMeasurementVector( InstanceIdentifier id) const = 0; + + /** Get the frequency of a measurement specified by instance + * identifier. */ + virtual AbsoluteFrequencyType GetFrequency( InstanceIdentifier id ) const = 0; + + /** Get the total frequency of the sample. */ + virtual TotalAbsoluteFrequencyType GetTotalFrequency() const = 0; + + + /** Set method for the length of the measurement vector */ + virtual void SetMeasurementVectorSize( MeasurementVectorSizeType s ) + { + // Test whether the vector type is resizable or not + MeasurementVectorType m; + if( MeasurementVectorTraits::IsResizable( m ) ) + { + // then this is a resizable vector type + // + // if the new size is the same as the previou size, just return + if( s == this->m_MeasurementVectorSize ) + { + return; + } + else + { + // If the new size is different from the current size, then + // only change the measurement vector size if the container is empty. + if( this->Size() ) + { + itkExceptionMacro("Attempting to change the measurement \ + vector size of a non-empty Sample"); + } + else + { + this->m_MeasurementVectorSize = s; + this->Modified(); + } + } + } + else + { + // If this is a non-resizable vector type + MeasurementVectorType m3; + MeasurementVectorSizeType defaultLength = MeasurementVectorTraits::GetLength( m3 ); + // and the new length is different from the default one, then throw an exception + if( defaultLength != s ) + { + itkExceptionMacro("Attempting to change the measurement \ + vector size of a non-resizable vector type"); + } + } + } + + /** Get method for the length of the measurement vector */ + itkGetConstMacro( MeasurementVectorSize, MeasurementVectorSizeType ); + + /** Method to graft another sample */ + virtual void Graft( const DataObject *thatObject ) + { + this->Superclass::Graft(thatObject); + + const Self *thatConst = dynamic_cast< const Self * >(thatObject); + if (thatConst) + { + this->SetMeasurementVectorSize(thatConst->GetMeasurementVectorSize()); + } + } + +protected: + Sample() + { + m_MeasurementVectorSize = MeasurementVectorTraits::GetLength( + MeasurementVectorType() ); + } + + virtual ~Sample() {} + + void PrintSelf(std::ostream& os, Indent indent) const + { + Superclass::PrintSelf(os,indent); + os << indent << "Length of measurement vectors in the sample: " << + m_MeasurementVectorSize << std::endl; + } + + + +private: + Sample(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + MeasurementVectorSizeType m_MeasurementVectorSize; +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkSampleClassifierFilter.h b/Utilities/ITK/Code/Review/Statistics/itkSampleClassifierFilter.h new file mode 100644 index 0000000000..954ac0de37 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSampleClassifierFilter.h @@ -0,0 +1,163 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSampleClassifierFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSampleClassifierFilter_h +#define __itkSampleClassifierFilter_h + +#include <vector> + +#include "itkMembershipSample.h" +#include "itkMembershipFunctionBase.h" +#include "itkDecisionRule.h" +#include "itkProcessObject.h" +#include "itkSimpleDataObjectDecorator.h" + +namespace itk { +namespace Statistics { + +/** \class SampleClassifierFilter + * + * \brief Sample classification class + * + * This filter takes as input a Sample and produces as output a + * classification in the form of a MembershipSample object. + * + */ + +template< class TSample > +class ITK_EXPORT SampleClassifierFilter : + public ProcessObject +{ +public: + /** Standard class typedef */ + typedef SampleClassifierFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Standard macros */ + itkTypeMacro(SampleClassifierFilter, ProcessObject); + itkNewMacro(Self); + + /** Type of the input Sample */ + typedef TSample SampleType; + + /** typedefs Output type */ + typedef MembershipSample< SampleType > MembershipSampleType; + typedef typename MembershipSampleType::Pointer MembershipSampleObjectPointer; + + /** typedefs from SampleType object */ + typedef typename SampleType::MeasurementType MeasurementType; + typedef typename SampleType::MeasurementVectorType MeasurementVectorType; + + /** typedef for the MembershipFunction */ + typedef MembershipFunctionBase< MeasurementVectorType > MembershipFunctionType; + typedef typename MembershipFunctionType::ConstPointer MembershipFunctionPointer; + typedef std::vector< MembershipFunctionPointer > MembershipFunctionVectorType; + typedef SimpleDataObjectDecorator< + MembershipFunctionVectorType > MembershipFunctionVectorObjectType; + typedef typename + MembershipFunctionVectorObjectType::Pointer MembershipFunctionVectorObjectPointer; + + /** typedef for membership functions weight proprtion */ + typedef Array< double > MembershipFunctionsWeightsArrayType; + + typedef SimpleDataObjectDecorator< + MembershipFunctionsWeightsArrayType > MembershipFunctionsWeightsArrayObjectType; + typedef typename + MembershipFunctionsWeightsArrayObjectType::Pointer MembershipFunctionsWeightsArrayPointer; + + typedef unsigned long ClassLabelType; + typedef std::vector< ClassLabelType > ClassLabelVectorType; + typedef SimpleDataObjectDecorator< + ClassLabelVectorType > ClassLabelVectorObjectType; + typedef ClassLabelVectorObjectType::Pointer ClassLabelVectorObjectPointer; + + + /** type of the decision rule */ + typedef DecisionRule DecisionRuleType; + typedef DecisionRuleType::ConstPointer DecisionRulePointer; + + /** Sets the input sample that will be classified by this filter. */ + void SetInput(const SampleType * sample); + const SampleType * GetInput() const; + + /** Returns the classification result */ + const MembershipSampleType * GetOutput() const; + + /** Number of classes. This must match the number of labels and membership + * functions provided by the user, otherwise an exception will be thrown at + */ + itkSetMacro( NumberOfClasses, unsigned int ); + itkGetConstMacro( NumberOfClasses, unsigned int ); + + /** Set/Get the decision rule. */ + itkSetConstObjectMacro( DecisionRule, DecisionRuleType ); + itkGetConstObjectMacro( DecisionRule, DecisionRuleType ); + + /** Sets input vector of class labels. The length of this vector must match + * the number of classes, otherwise an exception will be thrown at run time. + * */ + void SetClassLabels(const ClassLabelVectorObjectType * classLabels ); + + /** Sets input vector of membership functions. The length of this vector must match + * the number of classes, otherwise an exception will be thrown at run time. + * */ + void SetMembershipFunctions(const MembershipFunctionVectorObjectType * membershipFunctions ); + + /** Sets array of weights for the membership functions */ + void SetMembershipFunctionsWeightsArray(const MembershipFunctionsWeightsArrayObjectType * weightsArray ); + + +protected: + SampleClassifierFilter(); + virtual ~SampleClassifierFilter() {} + void PrintSelf(std::ostream& os, Indent indent) const; + + SampleClassifierFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + + /** Starts the classification process */ + void GenerateData(); + + /** Make a DataObject of the correct type to used as the specified + * output. This method + * is automatically called when DataObject::DisconnectPipeline() is + * called. + * \sa ProcessObject + */ + virtual DataObjectPointer MakeOutput(unsigned int idx); + +private: + + unsigned int m_NumberOfClasses; + + /** Decision Rule */ + DecisionRulePointer m_DecisionRule; + +}; // end of class + + +} // end of namespace Statistics +} // end of namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkSampleClassifierFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkSampleClassifierFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkSampleClassifierFilter.txx new file mode 100644 index 0000000000..b99c6868e6 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSampleClassifierFilter.txx @@ -0,0 +1,217 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSampleClassifierFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSampleClassifierFilter_txx +#define __itkSampleClassifierFilter_txx + +#include "itkSampleClassifierFilter.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +SampleClassifierFilter< TSample > +::SampleClassifierFilter() +{ + this->m_NumberOfClasses = 0; + + this->SetNumberOfRequiredInputs( 3 ); + this->SetNumberOfRequiredOutputs( 1 ); + + this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); + + /** Initialize decision rule */ + m_DecisionRule = NULL; +} + +template< class TSample > +void +SampleClassifierFilter< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "NumberofClasses: " + << this->GetNumberOfClasses() << std::endl; + os << indent << "DecisionRule: " + << this->GetDecisionRule() << std::endl; +} + +template< class TSample > +void +SampleClassifierFilter< TSample > +::SetInput( const TSample* sample ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(0, + const_cast< SampleType * >( sample ) ); +} + +template< class TSample > +const TSample * +SampleClassifierFilter< TSample > +::GetInput( ) const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const SampleType * > + (this->ProcessObject::GetInput(0) ); +} + + +template< class TSample > +void +SampleClassifierFilter< TSample > +::SetClassLabels( const ClassLabelVectorObjectType * classLabels ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(1, + const_cast< ClassLabelVectorObjectType * >( classLabels ) ); +} + +template< class TSample > +void +SampleClassifierFilter< TSample > +::SetMembershipFunctions( const MembershipFunctionVectorObjectType * membershipFunctions ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(2, + const_cast< MembershipFunctionVectorObjectType * >( membershipFunctions ) ); +} + +template< class TSample > +void +SampleClassifierFilter< TSample > +::SetMembershipFunctionsWeightsArray( const +MembershipFunctionsWeightsArrayObjectType * weightsArray ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(3, + const_cast< + MembershipFunctionsWeightsArrayObjectType * >( weightsArray ) ); +} + + +template< class TSample > +typename SampleClassifierFilter< TSample >::DataObjectPointer +SampleClassifierFilter< TSample > +::MakeOutput(unsigned int) +{ + return static_cast<DataObject*>( MembershipSampleType::New().GetPointer() ); +} + +template< class TSample > +void +SampleClassifierFilter< TSample > +::GenerateData() +{ + const ClassLabelVectorObjectType * classLabelsDecorated = + static_cast< const ClassLabelVectorObjectType * >( this->ProcessObject::GetInput( 1 ) ); + + const MembershipFunctionVectorObjectType * membershipFunctionsDecorated = + static_cast< const MembershipFunctionVectorObjectType * >( this->ProcessObject::GetInput( 2 ) ); + + const MembershipFunctionsWeightsArrayObjectType * + membershipFunctionsWeightsArrayDecorated = + static_cast< const MembershipFunctionsWeightsArrayObjectType * >( this->ProcessObject::GetInput( 3 ) ); + + const ClassLabelVectorType & classLabels = classLabelsDecorated->Get(); + + const MembershipFunctionVectorType & membershipFunctions = membershipFunctionsDecorated->Get(); + + // Check number of Labels and MembershipSamples against the number of classes */ + if( membershipFunctions.size() != this->m_NumberOfClasses ) + { + itkExceptionMacro("Number of Membership functions does not match the number of classes"); + } + + if( classLabels.size() != this->m_NumberOfClasses ) + { + itkExceptionMacro("Number of class labels does not match the number of classes"); + } + + if( m_DecisionRule.IsNull()) + { + itkExceptionMacro("Decision rule is not set"); + } + + MembershipFunctionsWeightsArrayType membershipFunctionsWeightsArray; + if( membershipFunctionsWeightsArrayDecorated == NULL ) + { + // no weights array is set and hence all membership functions will have equal + // weight + membershipFunctionsWeightsArray.SetSize( this->m_NumberOfClasses ); + membershipFunctionsWeightsArray.Fill(1.0); + } + else + { + membershipFunctionsWeightsArray = membershipFunctionsWeightsArrayDecorated->Get(); + } + + if ( membershipFunctionsWeightsArray.Size() != this->m_NumberOfClasses +) + { + itkExceptionMacro("Membership functions weight array size does not match the\ + number of classes "); + } + + const SampleType * sample = + static_cast< const SampleType * >( this->ProcessObject::GetInput( 0 ) ); + + std::vector< double > discriminantScores; + discriminantScores.resize( this->m_NumberOfClasses ); + + MembershipSampleType * output = dynamic_cast< MembershipSampleType * >( + this->ProcessObject::GetOutput(0)); + + output->SetSample( this->GetInput() ); + output->SetNumberOfClasses( this->m_NumberOfClasses ); + + typename TSample::ConstIterator iter = sample->Begin(); + typename TSample::ConstIterator end = sample->End(); + + while (iter != end) + { + typename TSample::MeasurementVectorType measurements; + measurements = iter.GetMeasurementVector(); + for (unsigned int i = 0; i < this->m_NumberOfClasses; i++) + { + discriminantScores[i] = membershipFunctionsWeightsArray[i] * + membershipFunctions[i]->Evaluate(measurements); + } + + unsigned int classIndex; + classIndex = m_DecisionRule->Evaluate(discriminantScores); + + output->AddInstance(classLabels[classIndex], iter.GetInstanceIdentifier()); + ++iter; + } +} + +template< class TSample > +const typename SampleClassifierFilter< TSample >::MembershipSampleType * +SampleClassifierFilter< TSample > +::GetOutput() const +{ + return static_cast< const MembershipSampleType * >(this->ProcessObject::GetOutput(0)); +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkSampleToHistogramFilter.h b/Utilities/ITK/Code/Review/Statistics/itkSampleToHistogramFilter.h new file mode 100644 index 0000000000..281417a222 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSampleToHistogramFilter.h @@ -0,0 +1,149 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSampleToHistogramFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSampleToHistogramFilter_h +#define __itkSampleToHistogramFilter_h + +#include "itkMacro.h" +#include "itkProcessObject.h" +#include "itkMeasurementVectorTraits.h" +#include "itkSimpleDataObjectDecorator.h" + + +namespace itk { +namespace Statistics { + +/** \class SampleToHistogramFilter + * \brief Computes the Histogram corresponding to a Sample. + * + * This filter produces as output the histogram corresponding to + * the values of a Sample. + * + * \sa Sample, Histogram + * + */ + +template < class TSample, class THistogram > +class ITK_EXPORT SampleToHistogramFilter : public ProcessObject +{ +public: + /** Standard class typedefs */ + typedef SampleToHistogramFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self > ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro(SampleToHistogramFilter, ProcessObject); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** MeasurementVector typedef support */ + typedef TSample SampleType; + typedef THistogram HistogramType; + typedef typename SampleType::MeasurementVectorType MeasurementVectorType; + typedef typename MeasurementVectorType::ValueType MeasurementType; + typedef typename HistogramType::SizeType HistogramSizeType; + typedef typename HistogramType::MeasurementType HistogramMeasurementType; + typedef typename HistogramType::MeasurementVectorType HistogramMeasurementVectorType; + + + /** Type for the data object output */ + itkSuperclassTraitMacro( DataObjectPointer ) + + /** Set/Get the input sample */ + virtual void SetInput( const SampleType * sample ); + virtual const SampleType * GetInput() const; + + /** Get the output Histogram */ + const HistogramType * GetOutput() const; + + /** Type of DataObjects to use for Size inputs */ + typedef SimpleDataObjectDecorator< + HistogramSizeType > InputHistogramSizeObjectType; + + /** Type of DataObjects to use for Marginal Scale inputs */ + typedef SimpleDataObjectDecorator< + HistogramMeasurementType > InputHistogramMeasurementObjectType; + + /** Type of DataObjects to use for Minimum and Maximums values of the + * histogram bins. */ + typedef SimpleDataObjectDecorator< + HistogramMeasurementVectorType > InputHistogramMeasurementVectorObjectType; + + /** Type of DataObjects to use for AutoMinimumMaximum input */ + typedef SimpleDataObjectDecorator< bool > InputBooleanObjectType; + + /** Methods for setting and getting the histogram size. The histogram size + * is encapsulated inside a decorator class. For this reason, it is possible + * to set and get the decorator class, but it is only possible to set the + * histogram size by value. This macro declares the methods + * SetHistogramSize(), SetHistogramSizeInput(), GetHistogramSizeInput(). + */ + itkSetDecoratedInputMacro( HistogramSize, HistogramSizeType, 1 ); + + /** Methods for setting and getting the Marginal scale value. The marginal + * scale is used when the type of the measurement vector componets are of + * integer type. */ + itkSetDecoratedInputMacro( MarginalScale, HistogramMeasurementType, 2 ); + + /** Methods for setting and getting the Minimum and Maximum values of the + * histogram bins. */ + itkSetDecoratedInputMacro( HistogramBinMinimum, HistogramMeasurementVectorType, 3 ); + itkSetDecoratedInputMacro( HistogramBinMaximum, HistogramMeasurementVectorType, 4 ); + + /** Methods for setting and getting the boolean flag that defines whether the + * minimum and maximum of the histogram are going to be computed + * automatically from the values of the sample */ + itkSetDecoratedInputMacro( AutoMinimumMaximum, bool, 5 ); + + /** Method that facilitates the use of this filter in the internal + * pipeline of another filter. */ + virtual void GraftOutput(DataObject *output); + +protected: + SampleToHistogramFilter(); + virtual ~SampleToHistogramFilter(); + + void PrintSelf(std::ostream& os, Indent indent) const; + + /** Make a DataObject of the correct type to used as the specified + * output. This method + * is automatically called when DataObject::DisconnectPipeline() is + * called. + * \sa ProcessObject + */ + virtual DataObjectPointer MakeOutput(unsigned int idx); + + // Where the histogram is actually computed + virtual void GenerateData(); + +private: + SampleToHistogramFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkSampleToHistogramFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkSampleToHistogramFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkSampleToHistogramFilter.txx new file mode 100644 index 0000000000..faa97a36b5 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSampleToHistogramFilter.txx @@ -0,0 +1,325 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSampleToHistogramFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSampleToHistogramFilter_txx +#define __itkSampleToHistogramFilter_txx + +#include "itkSampleToHistogramFilter.h" +#include "itkStatisticsAlgorithm.h" + +namespace itk { +namespace Statistics { + +template < class TSample, class THistogram > +SampleToHistogramFilter< TSample, THistogram > +::SampleToHistogramFilter() +{ + this->ProcessObject::SetNumberOfRequiredInputs( 1 ); + this->ProcessObject::SetNumberOfRequiredOutputs(1); + + this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); + + const unsigned int minimumNumberOfComponents = 1; + + // Set some default inputs + HistogramSizeType histogramSize( minimumNumberOfComponents ); + histogramSize.Fill(0); + this->SetHistogramSize( histogramSize ); + + this->SetMarginalScale( 100 ); + + this->SetAutoMinimumMaximum( true ); +} + +template < class TSample, class THistogram > +SampleToHistogramFilter< TSample, THistogram > +::~SampleToHistogramFilter() +{ +} + +template < class TSample, class THistogram > +void +SampleToHistogramFilter< TSample, THistogram > +::SetInput( const SampleType * sample ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(0, + const_cast< SampleType * >( sample ) ); +} + +template < class TSample, class THistogram > +const typename +SampleToHistogramFilter< TSample, THistogram >::SampleType * +SampleToHistogramFilter< TSample, THistogram > +::GetInput() const +{ + const SampleType * input = + static_cast< const SampleType * >( this->ProcessObject::GetInput( 0 ) ); + return input; +} + + +template < class TSample, class THistogram > +const typename +SampleToHistogramFilter< TSample, THistogram >::HistogramType * +SampleToHistogramFilter< TSample, THistogram > +::GetOutput() const +{ + const HistogramType * output = + static_cast<const HistogramType*>(this->ProcessObject::GetOutput(0)); + + return output; +} + +template < class TSample, class THistogram > +void +SampleToHistogramFilter< TSample, THistogram > +::GraftOutput(DataObject *graft) +{ + DataObject * output = + const_cast< HistogramType * >( this->GetOutput() ); + + // Call Histogram to copy meta-information, and the container + output->Graft( graft ); +} + + +template < class TSample, class THistogram > +typename SampleToHistogramFilter< TSample, THistogram >::DataObjectPointer +SampleToHistogramFilter< TSample, THistogram > +::MakeOutput(unsigned int) +{ + return static_cast<DataObject*>(HistogramType::New().GetPointer()); +} + + +template < class TSample, class THistogram > +void +SampleToHistogramFilter< TSample, THistogram > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + // m_AutoMinimumMaximum + os << indent << "AutoMinimumMaximum: " + << this->GetAutoMinimumMaximumInput() << std::endl; + // m_MarginalScale + os << indent << "MarginalScale: " + << this->GetMarginalScaleInput() << std::endl; + // m_HistogramBinMinimum + os << indent << "HistogramBinMinimum: " + << this->GetHistogramBinMinimumInput() << std::endl; + // m_HistogramBinMaximum + os << indent << "HistogramBinMaximum: " + << this->GetHistogramBinMaximumInput() << std::endl; + // m_HistogramSize + os << indent << "HistogramSize: " + << this->GetHistogramSizeInput() << std::endl; +} + + +template < class TSample, class THistogram > +void +SampleToHistogramFilter< TSample, THistogram > +::GenerateData() +{ + const SampleType * inputSample = this->GetInput(); + + const InputHistogramMeasurementVectorObjectType * binMinimumObject = + this->GetHistogramBinMinimumInput(); + + const InputHistogramMeasurementVectorObjectType * binMaximumObject = + this->GetHistogramBinMaximumInput(); + + const InputHistogramMeasurementObjectType * marginalScaleObject = + this->GetMarginalScaleInput(); + + const InputBooleanObjectType * autoMinimumMaximum = + this->GetAutoMinimumMaximumInput(); + + const InputHistogramSizeObjectType * histogramSizeObject = + this->GetHistogramSizeInput(); + + if( histogramSizeObject == NULL ) + { + itkExceptionMacro("Histogram Size input is missing"); + } + + if( marginalScaleObject == NULL ) + { + itkExceptionMacro("Marginal scale input is missing"); + } + + HistogramSizeType histogramSize = histogramSizeObject->Get(); + + HistogramMeasurementType marginalScale = marginalScaleObject->Get(); + + HistogramType * outputHistogram = + static_cast<HistogramType*>(this->ProcessObject::GetOutput(0)); + + const typename SampleType::InstanceIdentifier measurementVectorSize = + inputSample->GetMeasurementVectorSize(); + + if( measurementVectorSize == 0 ) + { + itkExceptionMacro("Input sample MeasurementVectorSize is zero"); + } + + if( histogramSize.Size() != measurementVectorSize ) + { + itkExceptionMacro("Histogram number of components: " + << histogramSize.Size() + << " doesn't match Measurement Vector Size: " + << measurementVectorSize); + } + + outputHistogram->SetMeasurementVectorSize( measurementVectorSize ); + + typename SampleType::MeasurementVectorType lower; + typename SampleType::MeasurementVectorType upper; + + MeasurementVectorTraits::SetLength( lower, measurementVectorSize ); + MeasurementVectorTraits::SetLength( upper, measurementVectorSize ); + + HistogramMeasurementVectorType h_upper; + HistogramMeasurementVectorType h_lower; + + MeasurementVectorTraits::SetLength( h_lower, measurementVectorSize ); + MeasurementVectorTraits::SetLength( h_upper, measurementVectorSize ); + + const HistogramMeasurementType maximumPossibleValue = + itk::NumericTraits< HistogramMeasurementType >::max(); + + if( autoMinimumMaximum && autoMinimumMaximum->Get() ) + { + if( inputSample->Size() ) + { + Algorithm::FindSampleBound( + inputSample, inputSample->Begin(), inputSample->End(), lower, upper); + + for( unsigned int i = 0; i < measurementVectorSize; i++ ) + { + if( !NumericTraits< HistogramMeasurementType >::is_integer ) + { + const double margin = + ( static_cast< HistogramMeasurementType >( upper[i] - lower[i] ) / + static_cast< HistogramMeasurementType >( histogramSize[i] ) ) / + static_cast< HistogramMeasurementType >( marginalScale ); + + // Now we check if the upper[i] value can be increased by + // the margin value without saturating the capacity of the + // HistogramMeasurementType + if( ( maximumPossibleValue - upper[i] ) > margin ) + { + h_upper[i] = static_cast< HistogramMeasurementType > (upper[i] + margin); + } + else + { + // an overflow would occur if we add 'margin' to the upper + // therefore we just compromise in setting h_upper = upper. + h_upper[i] = static_cast< HistogramMeasurementType >( upper[i] ); + // Histogram measurement type would force the clipping the max value. + // Therefore we must call the following to include the max value: + outputHistogram->SetClipBinsAtEnds(false); + // The above function is okay since here we are within the autoMinMax + // computation and clearly the user intended to include min and max. + } + } + else + { + h_upper[i] = (static_cast< HistogramMeasurementType >( upper[i] ) ) + + NumericTraits< HistogramMeasurementType >::One; + + if( h_upper[i] <= upper[i] ) + { + // an overflow has occurred therefore set upper to upper + h_upper[i] = static_cast< HistogramMeasurementType >( upper[i] ); + // Histogram measurement type would force the clipping the max value. + // Therefore we must call the following to include the max value: + outputHistogram->SetClipBinsAtEnds(false); + // The above function is okay since here we are within the autoMinMax + // computation and clearly the user intended to include min and max. + } + } + h_lower[i] = static_cast< HistogramMeasurementType >( lower[i] ); + } + } + else + { + for( unsigned int i = 0; i < measurementVectorSize; i++ ) + { + h_lower[i] = static_cast< HistogramMeasurementType >( lower[i] ); + h_upper[i] = static_cast< HistogramMeasurementType >( upper[i] ); + } + } + } + else + { + if( binMaximumObject == NULL ) + { + itkExceptionMacro("Histogram Bin Maximum input is missing"); + } + + if( binMinimumObject == NULL ) + { + itkExceptionMacro("Histogram Bin Minimum input is missing"); + } + + h_upper = binMaximumObject->Get(); + h_lower = binMinimumObject->Get(); + } + + // initialize the Histogram object using the sizes and + // the upper and lower bound from the FindSampleBound function + outputHistogram->Initialize( histogramSize, h_lower, h_upper ); + + typename SampleType::ConstIterator iter = inputSample->Begin(); + typename SampleType::ConstIterator last = inputSample->End(); + + typename SampleType::MeasurementVectorType lvector; + + typename HistogramType::IndexType index( measurementVectorSize); + typename HistogramType::MeasurementVectorType hvector( measurementVectorSize ); + + unsigned int i; + + while (iter != last) + { + lvector = iter.GetMeasurementVector(); + for ( i = 0; i < inputSample->GetMeasurementVectorSize(); i++) + { + hvector[i] = static_cast< HistogramMeasurementType >( lvector[i] ); + } + + outputHistogram->GetIndex( hvector, index ); + if( !outputHistogram->IsIndexOutOfBounds( index ) ) + { + // if the measurement vector is out of bound then + // the GetIndex method has returned an index set to the max size of + // the invalid dimension - even if the hvector is less than the minimum + // bin value. + // If the index isn't valid, we don't increase the frequency. + // See the comments in Histogram->GetIndex() for more info. + outputHistogram->IncreaseFrequency( index, 1 ); + } + ++iter; + } + +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkSampleToSubsampleFilter.h b/Utilities/ITK/Code/Review/Statistics/itkSampleToSubsampleFilter.h new file mode 100644 index 0000000000..a9a2e364b1 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSampleToSubsampleFilter.h @@ -0,0 +1,101 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSampleToSubsampleFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSampleToSubsampleFilter_h +#define __itkSampleToSubsampleFilter_h + +#include "itkSample.h" +#include "itkSubsample.h" +#include "itkProcessObject.h" + +namespace itk { +namespace Statistics { + +/** \class SampleToSubsampleFilter + * \brief Base class of filters intended to select subsamples from samples. + * + * This filter will take as input a Sample and produce as output a Subsample + * that derives from the original sample, and that refers to it. + * + * This is an Abstract class that can not be instantiated. There are multiple + * filters that derive from this class and provide specific implementations of + * subsampling methods. + * + * \sa Sample, Subsample + * + * \sa NeighborhoodSampler + * + */ + +template< class TSample > +class ITK_EXPORT SampleToSubsampleFilter : public ProcessObject +{ +public: + /** Standard class typedefs. */ + typedef SampleToSubsampleFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Standard macros */ + itkTypeMacro(SampleToSubsampleFilter, ProcessObject); + + /** Typedefs for Measurement vector, measurement, Instance Identifier, + * frequency, size, size element value from the template argument TSample */ + typedef TSample SampleType; + typedef typename SampleType::MeasurementVectorType MeasurementVectorType; + typedef typename SampleType::MeasurementType MeasurementType; + typedef typename SampleType::InstanceIdentifier InstanceIdentifier; + + /** Declare the output type */ + typedef Subsample< SampleType > SubsampleType; + typedef SubsampleType OutputType; + + /** Set/Get the input sample */ + virtual void SetInput( const SampleType * sample ); + virtual const SampleType * GetInput() const; + + /** Get the output subsample */ + const OutputType * GetOutput() const; + + +protected: + SampleToSubsampleFilter(); + virtual ~SampleToSubsampleFilter(); + void PrintSelf(std::ostream& os, Indent indent) const; + + /** Make a DataObject of the correct type to used as the specified + * output. This method + * is automatically called when DataObject::DisconnectPipeline() is + * called. + * \sa ProcessObject + */ + virtual DataObjectPointer MakeOutput(unsigned int idx); + +private: + SampleToSubsampleFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkSampleToSubsampleFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkSampleToSubsampleFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkSampleToSubsampleFilter.txx new file mode 100644 index 0000000000..157b2d396f --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSampleToSubsampleFilter.txx @@ -0,0 +1,97 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSampleToSubsampleFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSampleToSubsampleFilter_txx +#define __itkSampleToSubsampleFilter_txx + +#include "itkSampleToSubsampleFilter.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +SampleToSubsampleFilter< TSample > +::SampleToSubsampleFilter() +{ + this->ProcessObject::SetNumberOfRequiredInputs( 1 ); + this->ProcessObject::SetNumberOfRequiredOutputs(1); + + this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); +} + +template< class TSample > +SampleToSubsampleFilter< TSample > +::~SampleToSubsampleFilter() +{ +} + +template < class TSample > +void +SampleToSubsampleFilter< TSample > +::SetInput( const SampleType * sample ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(0, + const_cast< SampleType * >( sample ) ); +} + +template < class TSample > +const typename +SampleToSubsampleFilter< TSample >::SampleType * +SampleToSubsampleFilter< TSample > +::GetInput() const +{ + const SampleType * input = + static_cast< const SampleType * >( this->ProcessObject::GetInput( 0 ) ); + return input; +} + + +template < class TSample > +typename SampleToSubsampleFilter< TSample >::DataObjectPointer +SampleToSubsampleFilter< TSample > +::MakeOutput(unsigned int) +{ + return static_cast<DataObject*>(SubsampleType::New().GetPointer()); +} + + +template < class TSample > +const typename SampleToSubsampleFilter< TSample >::OutputType * +SampleToSubsampleFilter< TSample > +::GetOutput() const +{ + const SubsampleType * output = + static_cast<const SubsampleType*>(this->ProcessObject::GetOutput(0)); + + return output; +} + + +template < class TSample > +void +SampleToSubsampleFilter< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + this->Superclass::PrintSelf(os,indent); +} + + +} // end of namespace Statistics +} // end of namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceListSampleFilter.h b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceListSampleFilter.h new file mode 100644 index 0000000000..6430031898 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceListSampleFilter.h @@ -0,0 +1,131 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarImageToCooccurrenceListSampleFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarImageToCooccurrenceListSampleFilter_h +#define __itkScalarImageToCooccurrenceListSampleFilter_h + +#include <typeinfo> + +#include "itkImage.h" +#include "itkPixelTraits.h" +#include "itkImageToListSampleFilter.h" +#include "itkSmartPointer.h" +#include "itkImageRegionIterator.h" +#include "itkShapedNeighborhoodIterator.h" +#include "itkNeighborhoodIterator.h" +#include "itkNeighborhoodAlgorithm.h" +#include "itkConstantBoundaryCondition.h" +#include "itkListSample.h" +#include "itkFixedArray.h" +#include "itkMacro.h" +#include "itkProcessObject.h" + +#include <vector> +#include <algorithm> +#include <iostream> + +namespace itk { +namespace Statistics { + +/** \class ScalarImageToCooccurrenceListSampleFilter + * \brief Converts pixel data into a list of pairs in order to compute a cooccurrence Histogram. + * + * This class is intended to be used in combination with the ListToHistogramFilter class. + * + * \author Glenn Pierce + * + * \ingroup Statistics + */ + +template < class TImage > +class ITK_EXPORT ScalarImageToCooccurrenceListSampleFilter + : public ProcessObject +{ +public: + typedef TImage ImageType; + + typedef FixedArray< typename TImage::PixelType, 2 > MeasurementVectorType; + + typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType; + typedef typename SampleType::MeasurementVectorSizeType MeasurementVectorSizeType; + + /** Standard class typedefs */ + typedef ScalarImageToCooccurrenceListSampleFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Neighborhood iterator type. */ + typedef itk::ShapedNeighborhoodIterator< + TImage , + ConstantBoundaryCondition<TImage> + > ShapedNeighborhoodIteratorType; + + /** Offset type used for Neighborhoods */ + typedef typename ShapedNeighborhoodIteratorType::OffsetType OffsetType; + typedef std::vector<OffsetType> OffsetTable; + + void UseNeighbor(const OffsetType & offset); + + /** Method to set/get the image */ + void SetInput( const ImageType* image ); + const ImageType* GetInput() const; + + /** method to get the List sample */ + const SampleType * GetOutput() const; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ScalarImageToCooccurrenceListSampleFilter, ProcessObject); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** the number of components in a measurement vector */ + itkStaticConstMacro(MeasurementVectorSize, unsigned int, 2); + + /** Image dimension. */ + itkStaticConstMacro(ImageDimension, unsigned int, + TImage::ImageDimension); + + +protected: + ScalarImageToCooccurrenceListSampleFilter(); + virtual ~ScalarImageToCooccurrenceListSampleFilter() {} + void PrintSelf(std::ostream& os, Indent indent) const; + + typedef DataObject::Pointer DataObjectPointer; + virtual DataObjectPointer MakeOutput(unsigned int idx); + + /** This method causes the filter to generate its output. */ + virtual void GenerateData(); + + +private: + ScalarImageToCooccurrenceListSampleFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OffsetTable m_OffsetTable; +}; // end of class ScalarImageToListSampleFilter + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScalarImageToCooccurrenceListSampleFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceListSampleFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceListSampleFilter.txx new file mode 100644 index 0000000000..6d33ecddd8 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceListSampleFilter.txx @@ -0,0 +1,191 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarImageToCooccurrenceListSampleFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScalarImageToCooccurrenceListSampleFilter_txx +#define __itkScalarImageToCooccurrenceListSampleFilter_txx + +namespace itk { +namespace Statistics{ + +template < class TImage > +ScalarImageToCooccurrenceListSampleFilter< TImage > +::ScalarImageToCooccurrenceListSampleFilter() +{ + + this->SetNumberOfRequiredInputs(1); + this->ProcessObject::SetNumberOfRequiredOutputs(1); + + this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); +} + +template < class TImage > +void +ScalarImageToCooccurrenceListSampleFilter< TImage > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} + +template< class TImage > +void +ScalarImageToCooccurrenceListSampleFilter< TImage > +::SetInput(const ImageType* image) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(0, + const_cast< ImageType* >( image ) ); +} + +template< class TImage > +const TImage* +ScalarImageToCooccurrenceListSampleFilter< TImage > +::GetInput() const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const ImageType * > + (this->ProcessObject::GetInput(0) ); +} + +template< class TImage > +const typename ScalarImageToCooccurrenceListSampleFilter< TImage >::SampleType * +ScalarImageToCooccurrenceListSampleFilter< TImage > +::GetOutput() const +{ + const SampleType * output = + static_cast< const SampleType * >( this->ProcessObject::GetOutput(0)); + return output; +} + +template < class TImage > +typename ScalarImageToCooccurrenceListSampleFilter< TImage>::DataObjectPointer +ScalarImageToCooccurrenceListSampleFilter< TImage > +::MakeOutput(unsigned int) +{ + return static_cast<DataObject*>(SampleType::New().GetPointer()); +} + +template < class TImage > +void +ScalarImageToCooccurrenceListSampleFilter< TImage > +::GenerateData() +{ + typename ShapedNeighborhoodIteratorType::RadiusType radius; + radius.Fill(1); + + itk::ConstantBoundaryCondition<TImage> boundaryCondition; + // 0 is valid so I chose -1. Is this valid for all images ? + boundaryCondition.SetConstant( -1 ); + + typedef itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< + ImageType > FaceCalculatorType; + + FaceCalculatorType faceCalculator; + typename FaceCalculatorType::FaceListType faceList; + typename FaceCalculatorType::FaceListType::iterator fit; + + typedef typename ShapedNeighborhoodIteratorType::ConstIterator ShapeNeighborhoodIterator; + + typedef typename ImageType::PixelType PixelType; + + typedef typename OffsetTable::iterator OffsetIterator; + + typename SampleType::MeasurementVectorType coords; + + const ImageType *input = this->GetInput(); + + SampleType * output = + static_cast<SampleType*>(this->ProcessObject::GetOutput(0)); + + // constant for a coocurrence matrix. + const unsigned int measurementVectorSize = 2; + + output->SetMeasurementVectorSize( measurementVectorSize ); + + faceList = faceCalculator( input, + input->GetRequestedRegion(), + radius ); + + OffsetType center_offset; + center_offset.Fill( 0 ); + + for ( fit=faceList.begin(); fit != faceList.end(); ++fit) + { + + ShapedNeighborhoodIteratorType it(radius, input, *fit ); + it.OverrideBoundaryCondition(&boundaryCondition); + + OffsetIterator iter = m_OffsetTable.begin(); + while( iter != m_OffsetTable.end() ) + { + it.ActivateOffset(*iter); + iter++; + } + + for ( it.GoToBegin(); !it.IsAtEnd(); ++it ) + { + + const PixelType center_pixel_intensity = it.GetPixel( center_offset ); + + ShapeNeighborhoodIterator ci = it.Begin(); + while ( ci != it.End() ) + { + const PixelType pixel_intensity = ci.Get(); + + // We have the intensity values for the center pixel and one of it's neighbours. + // We can now place these in the SampleList + coords[0] = center_pixel_intensity; + coords[1] = pixel_intensity; + + output->PushBack(coords); + //std::cout << "Pushing: " << coords[0] << "\t" << coords[1] << std::endl; + ci++; + } + } + } +} + + +template < class TImage > +void +ScalarImageToCooccurrenceListSampleFilter< TImage > +::UseNeighbor(const OffsetType & offset) +{ + // Don't add the center pixel + bool isTheCenterPixel = true; + for(unsigned int i=0; i<ImageDimension; i++) + { + if( offset[i] != 0 ) + { + isTheCenterPixel = false; + break; + } + } + + if( !isTheCenterPixel ) + { + m_OffsetTable.push_back( offset ); + } +} + + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceMatrixFilter.h b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceMatrixFilter.h new file mode 100644 index 0000000000..4d255602d8 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceMatrixFilter.h @@ -0,0 +1,211 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarImageToCooccurrenceMatrixFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScalarImageToCooccurrenceMatrixFilter_h +#define __itkScalarImageToCooccurrenceMatrixFilter_h + +#include "itkImage.h" +#include "itkHistogram.h" +#include "itkDenseFrequencyContainer2.h" +#include "itkVectorContainer.h" +#include "itkObject.h" +#include "itkNumericTraits.h" +#include "itkMacro.h" + +namespace itk { +namespace Statistics { + +/** \class ScalarImageToCooccurrenceMatrixFilter + * \brief This class computes a co-occurence matrix (histogram) from + * a given image and a mask image if provided. Coocurrence matrces are + * used for image texture description. + * + * This filters creates a grey-level co-occurence matrix from a N-D scalar + * image. This is the first step in texture description a la Haralick. (See + * Haralick, R.M., K. Shanmugam and I. Dinstein. 1973. Textural Features for + * Image Classification. IEEE Transactions on Systems, Man and Cybernetics. + * SMC-3(6):610-620. See also Haralick, R.M. 1979. Statistical and Structural + * Approaches to Texture. Proceedings of the IEEE, 67:786-804.) + * + * The basic idea is as follows: + * Given an image and an offset (e.g. (1, -1) for a 2-d image), grey-level + * co-occurences are pairs of intensity values for a specific pixel and the + * pixel at that offset from the specified pixel. These co-occurences can provide + * information about the visual texture of an image region -- for example, an + * eight-bit image of alternating pixel-wide white and black vertical lines + * would have a large number of (0, 255) and (255, 0) co-occurences for offset + * (1, 0). + * + * The offset (or offsets) along which the co-occurences are calculated can be + * set by the user. Traditionally, only one offset is used per histogram, and + * offset components in the range [-1, 1] are used. For rotation-invariant features, + * averages of features computed over several histograms with different offsets + * are generally used, instead of computing features from one histogram created + * with several offsets. Additionally, instead of using offsets of two or more + * pixels in any direction, multy-resulution techniques (e.g. image pyramids) + * are generally used to deal with texture at different spatial resolutions. + * + * This class calculates a 2-d histogram of all the co-occurence pairs in the + * given image's requested region, for a given set of offsets. That is, if a given + * offset falls outside of the requested region at a particular point, that + * co-occurrence pair will not be added to the matrix. + * + * The number of histogram bins on each axis can be set (defaults to 256). Also, + * by default the histogram min and max corresponds to the largest and smallest + * possible pixel value of that pixel type. To customize the histogram bounds + * for a given image, the max and min pixel values that will be placed in the + * histogram can be set manually. NB: The min and max are INCLUSIVE. + * + * Further, the type of histogram frequency container used is an optional template + * parameter. By default, a dense container is used, but for images with little + * texture or in cases where the user wants more histogram bins, a sparse container + * can be used for the histogram instead. + * + * WARNING: This probably won't work for pixels of double or long-double type + * unless you set the histogram min and max manually. This is because the largest + * histogram bin by default has max value of the largest possible pixel value + * plus 1. For double and long-double types, whose "RealType" as defined by the + * NumericTraits class is the same, and thus cannot hold any larger values, + * this would cause a float overflow. + * + * \sa MaskedScalarImageToCooccurrenceMatrixFilter + * \sa HistogramToTextureFeaturesFilter + * \sa ScalarImageTextureCalculator + * + * \author Zachary Pincus and Glenn Pierce + * + */ + +template< class TImageType, + class THistogramFrequencyContainer = DenseFrequencyContainer2 > +class ITK_EXPORT ScalarImageToCooccurrenceMatrixFilter : public ProcessObject +{ +public: + /** Standard typedefs */ + typedef ScalarImageToCooccurrenceMatrixFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ScalarImageToCooccurrenceMatrixFilter, ProcessObject); + + /** standard New() method support */ + itkNewMacro(Self); + + typedef TImageType ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::RegionType RegionType; + typedef typename ImageType::SizeType RadiusType; + typedef typename ImageType::OffsetType OffsetType; + typedef VectorContainer<unsigned char, OffsetType> OffsetVector; + typedef typename OffsetVector::Pointer OffsetVectorPointer; + typedef typename OffsetVector::ConstPointer OffsetVectorConstPointer; + + typedef typename NumericTraits<PixelType>::RealType MeasurementType; + + typedef Histogram< MeasurementType, THistogramFrequencyContainer > + HistogramType; + typedef typename HistogramType::Pointer HistogramPointer; + typedef typename HistogramType::ConstPointer HistogramConstPointer; + typedef typename HistogramType::MeasurementVectorType MeasurementVectorType; + + + itkStaticConstMacro(DefaultBinsPerAxis, unsigned int, 256); + + /** Set the offset or offsets over which the co-occurrence pairs will be computed. + Calling either of these methods clears the previous offsets. */ + itkSetConstObjectMacro( Offsets, OffsetVector ); + itkGetConstObjectMacro( Offsets, OffsetVector ); + void SetOffset( const OffsetType offset ); + + /** Set number of histogram bins along each axis */ + itkSetMacro( NumberOfBinsPerAxis, unsigned int ); + itkGetConstMacro( NumberOfBinsPerAxis, unsigned int ); + + /** Set the min and max (inclusive) pixel value that will be placed in the histogram */ + void SetPixelValueMinMax( PixelType min, PixelType max ); + itkGetConstMacro(Min, PixelType); + itkGetConstMacro(Max, PixelType); + + /** Set the calculator to normalize the histogram (divide all bins by the + total frequency). Normalization is off by default. */ + itkSetMacro(Normalize, bool); + itkGetConstMacro(Normalize, bool); + itkBooleanMacro(Normalize); + + /** Method to set/get the image */ + void SetInput( const ImageType* image ); + const ImageType* GetInput() const; + + /** Method to set/get the mask image */ + void SetMaskImage( const ImageType* image ); + const ImageType* GetMaskImage() const; + + /** method to get the Histogram */ + const HistogramType * GetOutput() const; + + /** Set the pixel value of the mask that should be considered "inside" the + object. Defaults to one. */ + itkSetMacro( InsidePixelValue, PixelType ); + itkGetConstMacro( InsidePixelValue, PixelType ); + + +protected: + ScalarImageToCooccurrenceMatrixFilter(); + virtual ~ScalarImageToCooccurrenceMatrixFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + virtual void FillHistogram( RadiusType radius, RegionType region ); + virtual void FillHistogramWithMask( RadiusType radius, RegionType region, const ImageType * maskImage ); + + + /** Standard itk::ProcessObject subclass method. */ + typedef DataObject::Pointer DataObjectPointer; + virtual DataObjectPointer MakeOutput(unsigned int idx); + + /** This method causes the filter to generate its output. */ + virtual void GenerateData(); + +private: + ScalarImageToCooccurrenceMatrixFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + void NormalizeHistogram( void ); + + OffsetVectorConstPointer m_Offsets; + PixelType m_Min; + PixelType m_Max; + + unsigned int m_NumberOfBinsPerAxis; + MeasurementVectorType m_LowerBound; + MeasurementVectorType m_UpperBound; + bool m_Normalize; + + PixelType m_InsidePixelValue; + +}; + + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScalarImageToCooccurrenceMatrixFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceMatrixFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceMatrixFilter.txx new file mode 100644 index 0000000000..0a76914288 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToCooccurrenceMatrixFilter.txx @@ -0,0 +1,413 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarImageToCooccurrenceMatrixFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScalarImageToCooccurrenceMatrixFilter_txx +#define __itkScalarImageToCooccurrenceMatrixFilter_txx + +#include "itkScalarImageToCooccurrenceMatrixFilter.h" + +#include "itkConstNeighborhoodIterator.h" +#include "vnl/vnl_math.h" + +namespace itk { +namespace Statistics { + +template< class TImageType, class THistogramFrequencyContainer > +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer >:: +ScalarImageToCooccurrenceMatrixFilter() +{ + + this->SetNumberOfRequiredInputs(1); + this->SetNumberOfRequiredOutputs(1); + + this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); + + // constant for a coocurrence matrix. + const unsigned int measurementVectorSize = 2; + + HistogramType * output = const_cast< HistogramType * >( this->GetOutput() ); + + output->SetMeasurementVectorSize( measurementVectorSize ); + + //initialize parameters + this->m_LowerBound.SetSize( measurementVectorSize ); + this->m_UpperBound.SetSize( measurementVectorSize ); + + this->m_LowerBound.Fill(NumericTraits<PixelType>::NonpositiveMin()); + this->m_UpperBound.Fill(NumericTraits<PixelType>::max() + 1); + + this->m_Min = NumericTraits<PixelType>::NonpositiveMin(); + this->m_Max = NumericTraits<PixelType>::max(); + + //mask inside pixel value + this->m_InsidePixelValue = NumericTraits<PixelType>::One; + + this->m_NumberOfBinsPerAxis = DefaultBinsPerAxis; + this->m_Normalize = false; +} + +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer > +::SetOffset( const OffsetType offset ) +{ + OffsetVectorPointer offsetVector = OffsetVector::New(); + offsetVector->push_back(offset); + this->SetOffsets(offsetVector); +} + +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer > +::SetInput(const ImageType* image) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(0, + const_cast< ImageType* >( image ) ); +} +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer > +::SetMaskImage(const ImageType* image) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(1, + const_cast< ImageType* >( image ) ); +} + + +template< class TImageType, class THistogramFrequencyContainer > +const TImageType* +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer > +::GetInput() const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const ImageType * > + (this->ProcessObject::GetInput(0) ); +} + +template< class TImageType, class THistogramFrequencyContainer > +const TImageType* +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer > +::GetMaskImage() const +{ + if (this->GetNumberOfInputs() < 2) + { + return 0; + } + + return static_cast<const ImageType * > + (this->ProcessObject::GetInput(1) ); +} + +template< class TImageType, class THistogramFrequencyContainer > +const typename ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer >::HistogramType * +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer > +::GetOutput() const +{ + const HistogramType * output = + static_cast< const HistogramType * >( this->ProcessObject::GetOutput(0)); + return output; +} + +template< class TImageType, class THistogramFrequencyContainer > +typename ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer >::DataObjectPointer +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer > +::MakeOutput(unsigned int itkNotUsed(idx)) +{ + typename HistogramType::Pointer output = HistogramType::New(); + return static_cast< DataObject * >( output ); +} + + +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer >:: +GenerateData( void ) +{ + HistogramType * output = + static_cast< HistogramType * >( this->ProcessObject::GetOutput(0) ); + + const ImageType *input = this->GetInput(); + // At this point input must be non-NULL because the ProcessObject + // checks the number of required input to be non-NULL pointers before + // calling this GenerateData() method. + + // First, create an appropriate histogram with the right number of bins + // and mins and maxes correct for the image type. + typename HistogramType::SizeType size( output->GetMeasurementVectorSize() ); + size.Fill(m_NumberOfBinsPerAxis); + output->Initialize(size, m_LowerBound, m_UpperBound); + + // Next, find the minimum radius that encloses all the offsets. + unsigned int minRadius = 0; + typename OffsetVector::ConstIterator offsets; + for(offsets = m_Offsets->Begin(); offsets != m_Offsets->End(); offsets++) + { + for(unsigned int i = 0; i < offsets.Value().GetOffsetDimension(); i++) + { + unsigned int distance = vnl_math_abs(offsets.Value()[i]); + if(distance > minRadius) + { + minRadius = distance; + } + } + } + + RadiusType radius; + radius.Fill(minRadius); + + const ImageType *maskImage = NULL; + + // Check if a mask image has been provided + // + if (this->GetNumberOfInputs() > 1) + { + maskImage = this->GetMaskImage(); + } + + // Now fill in the histogram + if ( maskImage != NULL ) + { + this->FillHistogramWithMask(radius, input->GetRequestedRegion(), maskImage ); + } + else + { + this->FillHistogram(radius, input->GetRequestedRegion()); + } + + // Normalizse the histogram if requested + if(m_Normalize) + { + this->NormalizeHistogram(); + } + +} + +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer >:: +FillHistogram(RadiusType radius, RegionType region) +{ + // Iterate over all of those pixels and offsets, adding each + // co-occurrence pair to the histogram + + const ImageType *input = this->GetInput(); + + HistogramType * output = + static_cast< HistogramType * >( this->ProcessObject::GetOutput(0) ); + + + typedef ConstNeighborhoodIterator<ImageType> NeighborhoodIteratorType; + NeighborhoodIteratorType neighborIt; + neighborIt = NeighborhoodIteratorType(radius, input, region); + + MeasurementVectorType cooccur( output->GetMeasurementVectorSize() ); + + for (neighborIt.GoToBegin(); !neighborIt.IsAtEnd(); ++neighborIt) + { + const PixelType centerPixelIntensity = neighborIt.GetCenterPixel(); + if (centerPixelIntensity < m_Min || + centerPixelIntensity > m_Max) + { + continue; // don't put a pixel in the histogram if the value + // is out-of-bounds. + } + + typename OffsetVector::ConstIterator offsets; + for(offsets = m_Offsets->Begin(); offsets != m_Offsets->End(); offsets++) + { + bool pixelInBounds; + const PixelType pixelIntensity = + neighborIt.GetPixel(offsets.Value(), pixelInBounds); + + if (!pixelInBounds) + { + continue; // don't put a pixel in the histogram if it's out-of-bounds. + } + + if (pixelIntensity < m_Min || + pixelIntensity > m_Max) + { + continue; // don't put a pixel in the histogram if the value + // is out-of-bounds. + } + + // Now make both possible co-occurrence combinations and increment the + // histogram with them. + + cooccur[0] = centerPixelIntensity; + cooccur[1] = pixelIntensity; + output->IncreaseFrequency(cooccur, 1); + + cooccur[1] = centerPixelIntensity; + cooccur[0] = pixelIntensity; + output->IncreaseFrequency(cooccur, 1); + } + } +} + +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer >:: +FillHistogramWithMask(RadiusType radius, RegionType region, const ImageType * maskImage ) +{ + + // Iterate over all of those pixels and offsets, adding each + // co-occurrence pair to the histogram + + const ImageType *input = this->GetInput(); + + HistogramType * output = + static_cast< HistogramType * >( this->ProcessObject::GetOutput(0) ); + + // Iterate over all of those pixels and offsets, adding each + // co-occurrence pair to the histogram + typedef ConstNeighborhoodIterator<ImageType> NeighborhoodIteratorType; + NeighborhoodIteratorType neighborIt, maskNeighborIt; + neighborIt = NeighborhoodIteratorType(radius, input, region); + maskNeighborIt = NeighborhoodIteratorType(radius, maskImage, region); + + MeasurementVectorType cooccur( output->GetMeasurementVectorSize() ); + + for (neighborIt.GoToBegin(), maskNeighborIt.GoToBegin(); + !neighborIt.IsAtEnd(); ++neighborIt, ++maskNeighborIt) + { + + if (maskNeighborIt.GetCenterPixel() != m_InsidePixelValue) + { + continue; // Go to the next loop if we're not in the mask + } + + const PixelType centerPixelIntensity = neighborIt.GetCenterPixel(); + + if (centerPixelIntensity < this->GetMin() || + centerPixelIntensity > this->GetMax()) + { + continue; // don't put a pixel in the histogram if the value + // is out-of-bounds. + } + + typename OffsetVector::ConstIterator offsets; + for(offsets = this->GetOffsets()->Begin(); offsets != this->GetOffsets()->End(); offsets++) + { + + if (maskNeighborIt.GetPixel(offsets.Value()) != m_InsidePixelValue) + { + continue; // Go to the next loop if we're not in the mask + } + + bool pixelInBounds; + const PixelType pixelIntensity = + neighborIt.GetPixel(offsets.Value(), pixelInBounds); + + if (!pixelInBounds) + { + continue; // don't put a pixel in the histogram if it's out-of-bounds. + } + + if (pixelIntensity < this->GetMin() || + pixelIntensity > this->GetMax()) + { + continue; // don't put a pixel in the histogram if the value + // is out-of-bounds. + } + + // Now make both possible co-occurrence combinations and increment the + // histogram with them. + + cooccur[0] = centerPixelIntensity; + cooccur[1] = pixelIntensity; + output->IncreaseFrequency(cooccur, 1); + + cooccur[1] = centerPixelIntensity; + cooccur[0] = pixelIntensity; + output->IncreaseFrequency(cooccur, 1); + } + } +} + +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer >:: +NormalizeHistogram( void ) +{ + HistogramType * output = + static_cast< HistogramType * >( this->ProcessObject::GetOutput(0) ); + + typename HistogramType::AbsoluteFrequencyType totalFrequency = + output->GetTotalFrequency(); + + typename HistogramType::Iterator hit = output->Begin(); + while( hit != output->End() ) + { + hit.SetFrequency(hit.GetFrequency() / totalFrequency); + ++hit; + } +} + +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer >:: +SetPixelValueMinMax( PixelType min, PixelType max ) +{ + itkDebugMacro("setting Min to " << min << "and Max to " << max); + m_Min = min; + m_Max = max; + m_LowerBound.Fill(min); + m_UpperBound.Fill(max + 1); + this->Modified(); +} + +template< class TImageType, class THistogramFrequencyContainer > +void +ScalarImageToCooccurrenceMatrixFilter< TImageType, +THistogramFrequencyContainer >:: +PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "Offsets: " << this->GetOffsets() << std::endl; + os << indent << "Min: " << this->GetMin() << std::endl; + os << indent << "Max: " << this->GetMax() << std::endl; + os << indent << "NumberOfBinsPerAxis: " << this->GetNumberOfBinsPerAxis() << std::endl; + os << indent << "Normalize: " << this->GetNormalize() << std::endl; + os << indent << "InsidePixelValue: " << this->GetInsidePixelValue() << std::endl; +} + +} // end of namespace Statistics +} // end of namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.h b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.h new file mode 100644 index 0000000000..1ae2745894 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.h @@ -0,0 +1,133 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarImageToHistogramGenerator.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScalarImageToHistogramGenerator_h +#define __itkScalarImageToHistogramGenerator_h + + +#ifdef ITK_USE_REVIEW_STATISTICS +#include "itkImageToListSampleAdaptor.h" +#include "itkSampleToHistogramFilter.h" +#include "itkHistogram.h" +#else +#include "itkScalarImageToListAdaptor.h" +#include "itkListSampleToHistogramGenerator.h" +#endif + +#include "itkObject.h" + +namespace itk { +namespace Statistics { + +/** \class ScalarImageToHistogramGenerator + * + * \brief TODO + */ +template< class TImageType > +class ScalarImageToHistogramGenerator : public Object +{ +public: + /** Standard typedefs */ + typedef ScalarImageToHistogramGenerator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ScalarImageToHistogramGenerator, Object); + + /** standard New() method support */ + itkNewMacro(Self); + + typedef TImageType ImageType; +#ifdef ITK_USE_REVIEW_STATISTICS + typedef itk::Statistics::ImageToListSampleAdaptor< +#else + typedef itk::Statistics::ScalarImageToListAdaptor< +#endif + ImageType + > AdaptorType; + typedef typename AdaptorType::Pointer AdaptorPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename NumericTraits< PixelType >::RealType RealPixelType; + +#ifdef ITK_USE_REVIEW_STATISTICS + typedef itk::Statistics::Histogram< double > HistogramType; + typedef itk::Statistics::SampleToHistogramFilter< AdaptorType, HistogramType > GeneratorType; +#else + typedef itk::Statistics::ListSampleToHistogramGenerator< + AdaptorType, + RealPixelType, + DenseFrequencyContainer + > GeneratorType; + typedef typename GeneratorType::HistogramType HistogramType; +#endif + + typedef typename GeneratorType::Pointer GeneratorPointer; + + typedef typename HistogramType::Pointer HistogramPointer; + typedef typename HistogramType::ConstPointer HistogramConstPointer; + +public: + + /** Triggers the Computation of the histogram */ + void Compute( void ); + + /** Connects the input image for which the histogram is going to be computed */ + void SetInput( const ImageType * ); + + /** Return the histogram. o + \warning This output is only valid after the Compute() method has been invoked + \sa Compute */ + const HistogramType * GetOutput() const; + + /** Set number of histogram bins */ + void SetNumberOfBins( unsigned int numberOfBins ); + + /** Set marginal scale value to be passed to the histogram generator */ + void SetMarginalScale( double marginalScale ); + + /** Set the minimum value from which the bins will be computed */ + void SetHistogramMin( RealPixelType minimumValue ); + + /** Set the maximum value from which the bins will be computed */ + void SetHistogramMax( RealPixelType maximumValue ); + +protected: + ScalarImageToHistogramGenerator(); + virtual ~ScalarImageToHistogramGenerator() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + +private: + + AdaptorPointer m_ImageToListAdaptor; + + GeneratorPointer m_HistogramGenerator; + + ScalarImageToHistogramGenerator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScalarImageToHistogramGenerator.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.txx b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.txx new file mode 100644 index 0000000000..90137bcb60 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.txx @@ -0,0 +1,126 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarImageToHistogramGenerator.txx,v $ + Language: C++ + Date: $Date: 2009-05-05 19:44:33 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScalarImageToHistogramGenerator_txx +#define __itkScalarImageToHistogramGenerator_txx + +#include "itkScalarImageToHistogramGenerator.h" + + +namespace itk { +namespace Statistics { + + +template < class TImage > +ScalarImageToHistogramGenerator< TImage > +::ScalarImageToHistogramGenerator() +{ + m_ImageToListAdaptor = AdaptorType::New(); + m_HistogramGenerator = GeneratorType::New(); +#ifdef ITK_USE_REVIEW_STATISTICS + m_HistogramGenerator->SetInput( m_ImageToListAdaptor ); +#else + m_HistogramGenerator->SetListSample( m_ImageToListAdaptor ); +#endif +} + +template < class TImage > +void +ScalarImageToHistogramGenerator< TImage > +::SetInput( const ImageType * image ) +{ + m_ImageToListAdaptor->SetImage( image ); +} + + +template < class TImage > +const typename ScalarImageToHistogramGenerator< TImage >::HistogramType * +ScalarImageToHistogramGenerator< TImage > +::GetOutput() const +{ + return m_HistogramGenerator->GetOutput(); +} + +template < class TImage > +void +ScalarImageToHistogramGenerator< TImage > +::Compute() +{ + m_HistogramGenerator->Update(); +} + +template < class TImage > +void +ScalarImageToHistogramGenerator< TImage > +::SetNumberOfBins( unsigned int numberOfBins ) +{ + typename HistogramType::SizeType size; +#ifdef ITK_USE_REVIEW_STATISTICS + size.SetSize(1); + size.Fill( numberOfBins ); + m_HistogramGenerator->SetHistogramSize( size ); +#else + size.Fill( numberOfBins ); + m_HistogramGenerator->SetNumberOfBins( size ); +#endif +} + + +template < class TImage > +void +ScalarImageToHistogramGenerator< TImage > +::SetHistogramMin( RealPixelType minimumValue ) +{ + typedef typename GeneratorType::MeasurementVectorType MeasurementVectorType; + MeasurementVectorType minVector; + minVector[0] = minimumValue; + m_HistogramGenerator->SetHistogramMin( minVector ); +} + + +template < class TImage > +void +ScalarImageToHistogramGenerator< TImage > +::SetHistogramMax( RealPixelType maximumValue ) +{ + typedef typename GeneratorType::MeasurementVectorType MeasurementVectorType; + MeasurementVectorType maxVector; + maxVector[0] = maximumValue; + m_HistogramGenerator->SetHistogramMax( maxVector ); +} + +template < class TImage > +void +ScalarImageToHistogramGenerator< TImage > +::SetMarginalScale( double marginalScale ) +{ + m_HistogramGenerator->SetMarginalScale( marginalScale ); +} + +template < class TImage > +void +ScalarImageToHistogramGenerator< TImage > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << "ImageToListSample adaptor = " << m_ImageToListAdaptor << std::endl; + os << "HistogramGenerator = " << m_HistogramGenerator << std::endl; +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.h b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.h new file mode 100644 index 0000000000..d872a66e8d --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.h @@ -0,0 +1,230 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarImageToTextureFeaturesFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-08 16:55:05 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScalarImageToTextureFeaturesFilter_h +#define __itkScalarImageToTextureFeaturesFilter_h + +#include "itkImage.h" +#include "itkProcessObject.h" +#include "itkVectorContainer.h" +#include "itkMacro.h" +#include "itkDataObjectDecorator.h" + +#include "itkHistogramToTextureFeaturesFilter.h" +#include "itkScalarImageToCooccurrenceMatrixFilter.h" +#include "itkDenseFrequencyContainer2.h" + +namespace itk { +namespace Statistics { + +/** \class ScalarImageToTextureFeaturesFilter + * \brief This class computes texture descriptions from an image. + * + * This class computes features that summarize the texture of a given image. + * The texture features are compute a la Haralick, and have proven to be useful + * in image classification for biological and medical imaging. + * This class computes the texture features of an image (optionally in a masked + * masked region), averaged across several spatial directions so that they are + * invariant to rotation. + * + * By default, texure features are computed for each spatial + * direction and then averaged afterward, so it is possible to access the standard + * deviations of the texture features. These values give a clue as to texture + * anisotropy. However, doing this is much more work, because it involved computing + * one GLCM for each offset given. To compute a single GLCM using the first offset , + * call FastCalculationsOn(). If this is called, then the texture standard deviations + * will not be computed (and will be set to zero), but texture computation will + * be much faster. + * + * This class is templated over the input image type. + * + * Template Parameters: + * The image type, and the type of histogram frequency container. If you are using + * a large number of bins per axis, a sparse frequency container may be advisable. + * The default is to use a dense frequency container. + * + * Inputs and parameters: + * -# An image + * -# A mask defining the region over which texture features will be + * calculated. (Optional) + * -# The pixel value that defines the "inside" of the mask. (Optional, defaults + * to 1 if a mask is set.) + * -# The set of features to be calculated. These features are defined + * in the GreyLevelCooccurrenceMatrixTextureCoefficientsCalculator class. (Optional, + * defaults to {Energy, Entropy, InverseDifferenceMoment, Inertia, ClusterShade, + * ClusterProminence}, as in Conners, Trivedi and Harlow.) + * -# The number of intensity bins. (Optional, defaults to 256.) + * -# The set of directions (offsets) to average across. (Optional, defaults to + * {(-1, 0), (-1, -1), (0, -1), (1, -1)} for 2D images and scales analogously for ND + * images.) + * -# The pixel intensity range over which the features will be calculated. + * (Optional, defaults to the full dynamic range of the pixel type.) + * + * In general, the default parameter values should be sufficient. + * + * Outputs: + * (1) The average value of each feature. + * (2) The standard deviation in the values of each feature. + * + * Web references: + * http://www.cssip.uq.edu.au/meastex/www/algs/algs/algs.html + * http://www.ucalgary.ca/~mhallbey/texture/texture_tutorial.html + * + * Print references: + * Haralick, R.M., K. Shanmugam and I. Dinstein. 1973. Textural Features for + * Image Classification. IEEE Transactions on Systems, Man and Cybernetics. + * SMC-3(6):610-620. + * + * Haralick, R.M. 1979. Statistical and Structural Approaches to Texture. + * Proceedings of the IEEE, 67:786-804. + * + * R.W. Conners and C.A. Harlow. A Theoretical Comaprison of Texture Algorithms. + * IEEE Transactions on Pattern Analysis and Machine Intelligence, 2:204-222, 1980. + * + * R.W. Conners, M.M. Trivedi, and C.A. Harlow. Segmentation of a High-Resolution + * Urban Scene using Texture Operators. Computer Vision, Graphics and Image + * Processing, 25:273-310, 1984. + * + * \sa ScalarImageToCooccurrenceMatrixFilter + * \sa HistogramToTextureFeaturesFilter + * + * Author: Zachary Pincus + */ + +template< class TImageType, + class THistogramFrequencyContainer = DenseFrequencyContainer2 > +class ITK_EXPORT ScalarImageToTextureFeaturesFilter : public ProcessObject +{ +public: + /** Standard typedefs */ + typedef ScalarImageToTextureFeaturesFilter Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ScalarImageToTextureFeaturesFilter, Object); + + /** standard New() method support */ + itkNewMacro(Self); + + typedef THistogramFrequencyContainer FrequencyContainerType; + typedef TImageType ImageType; + typedef typename ImageType::Pointer ImagePointer; + + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::OffsetType OffsetType; + typedef VectorContainer<unsigned char, OffsetType> OffsetVector; + typedef typename OffsetVector::Pointer OffsetVectorPointer; + typedef typename OffsetVector::ConstPointer OffsetVectorConstPointer; + + typedef ScalarImageToCooccurrenceMatrixFilter< + ImageType, FrequencyContainerType > CooccurrenceMatrixFilterType; + + typedef typename CooccurrenceMatrixFilterType::HistogramType + HistogramType; + + typedef HistogramToTextureFeaturesFilter< HistogramType > + TextureFeaturesFilterType; + + typedef typename TextureFeaturesFilterType::TextureFeatureName TextureFeatureName; + typedef VectorContainer<unsigned char, TextureFeatureName> FeatureNameVector; + + typedef typename FeatureNameVector::Pointer FeatureNameVectorPointer; + typedef typename FeatureNameVector::ConstPointer FeatureNameVectorConstPointer; + typedef VectorContainer<unsigned char, double> FeatureValueVector; + typedef typename FeatureValueVector::Pointer FeatureValueVectorPointer; + + /** Smart Pointer type to a DataObject. */ + typedef DataObject::Pointer DataObjectPointer; + + /** Type of DataObjects used for scalar outputs */ + typedef DataObjectDecorator<FeatureValueVector> + FeatureValueVectorDataObjectType; + + const FeatureValueVectorDataObjectType * GetFeatureMeansOutput() const; + const FeatureValueVectorDataObjectType * GetFeatureStandardDeviationsOutput() const; + + /** Connects the input image for which the features are going to be computed */ + void SetInput( const ImageType * ); + const ImageType* GetInput() const; + + /** Return the feature means and deviations. */ + itkGetConstReferenceObjectMacro(FeatureMeans, FeatureValueVector); + itkGetConstReferenceObjectMacro(FeatureStandardDeviations, FeatureValueVector); + + /** Set the desired feature set. Optional, for default value see above. */ + itkSetConstObjectMacro(RequestedFeatures, FeatureNameVector); + itkGetConstObjectMacro(RequestedFeatures, FeatureNameVector); + + /** Set the offsets over which the co-occurrence pairs will be computed. + Optional; for default value see above. */ + itkSetConstObjectMacro(Offsets, OffsetVector); + itkGetConstObjectMacro(Offsets, OffsetVector); + + /** Set number of histogram bins along each axis. + Optional; for default value see above. */ + void SetNumberOfBinsPerAxis( unsigned int ); + + /** Set the min and max (inclusive) pixel value that will be used for + feature calculations. Optional; for default value see above. */ + void SetPixelValueMinMax( PixelType min, PixelType max ); + + /** Connects the mask image for which the histogram is going to be computed. + Optional; for default value see above. */ + void SetMaskImage(const ImageType * ); + const ImageType* GetMaskImage() const; + + /** Set the pixel value of the mask that should be considered "inside" the + object. Optional; for default value see above. */ + void SetInsidePixelValue(PixelType InsidePixelValue); + + itkGetConstMacro(FastCalculations, bool); + itkSetMacro(FastCalculations, bool); + itkBooleanMacro(FastCalculations); + +protected: + ScalarImageToTextureFeaturesFilter(); + virtual ~ScalarImageToTextureFeaturesFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + void FastCompute(); + void FullCompute(); + + /** This method causes the filter to generate its output. */ + virtual void GenerateData(); + + /** Make a DataObject to be used for output output. */ + virtual DataObjectPointer MakeOutput( unsigned int ); + +private: + typename CooccurrenceMatrixFilterType::Pointer m_GLCMGenerator; + + FeatureValueVectorPointer m_FeatureMeans; + FeatureValueVectorPointer m_FeatureStandardDeviations; + FeatureNameVectorConstPointer m_RequestedFeatures; + OffsetVectorConstPointer m_Offsets; + bool m_FastCalculations; +}; + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScalarImageToTextureFeaturesFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.txx new file mode 100644 index 0000000000..bc88d6f4e8 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.txx @@ -0,0 +1,357 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarImageToTextureFeaturesFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-08 16:55:05 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScalarImageToTextureFeaturesFilter_txx +#define __itkScalarImageToTextureFeaturesFilter_txx + +#include "itkScalarImageToTextureFeaturesFilter.h" +#include "itkNeighborhood.h" +#include "vnl/vnl_math.h" + +namespace itk { +namespace Statistics { + +template< class TImage, class THistogramFrequencyContainer > +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +ScalarImageToTextureFeaturesFilter() +{ + this->SetNumberOfRequiredInputs(1); + this->SetNumberOfRequiredOutputs(1); + + for (int i=0; i < 2; ++i) + { + this->ProcessObject::SetNthOutput( i, this->MakeOutput( i ) ); + } + + m_GLCMGenerator = CooccurrenceMatrixFilterType::New(); + m_FeatureMeans = FeatureValueVector::New(); + m_FeatureStandardDeviations = FeatureValueVector::New(); + + // Set the requested features to the default value: + // {Energy, Entropy, InverseDifferenceMoment, Inertia, ClusterShade, ClusterProminence} + FeatureNameVectorPointer requestedFeatures = FeatureNameVector::New(); + // can't directly set m_RequestedFeatures since it is const! + requestedFeatures->push_back(TextureFeaturesFilterType::Energy); + requestedFeatures->push_back(TextureFeaturesFilterType::Entropy); + requestedFeatures->push_back(TextureFeaturesFilterType::InverseDifferenceMoment); + requestedFeatures->push_back(TextureFeaturesFilterType::Inertia); + requestedFeatures->push_back(TextureFeaturesFilterType::ClusterShade); + requestedFeatures->push_back(TextureFeaturesFilterType::ClusterProminence); + this->SetRequestedFeatures(requestedFeatures); + + // Set the offset directions to their defaults: half of all the possible + // directions 1 pixel away. (The other half is included by symmetry.) + // We use a neighborhood iterator to calculate the appropriate offsets. + typedef Neighborhood<ITK_TYPENAME ImageType::PixelType, ::itk::GetImageDimension< + ImageType >::ImageDimension > NeighborhoodType; + NeighborhoodType hood; + hood.SetRadius(1); + + // select all "previous" neighbors that are face+edge+vertex + // connected to the current pixel. do not include the center pixel. + unsigned int centerIndex = hood.GetCenterNeighborhoodIndex(); + OffsetType offset; + OffsetVectorPointer offsets = OffsetVector::New(); + for (unsigned int d=0; d < centerIndex; d++) + { + offset = hood.GetOffset(d); + std::cout << "Add the offset: " << offset << std::endl; + offsets->push_back(offset); + } + this->SetOffsets(offsets); + m_FastCalculations = false; +} + +template< class TImage, class THistogramFrequencyContainer > +typename +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer > ::DataObjectPointer +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer > +::MakeOutput( unsigned int itkNotUsed( idx ) ) +{ + return static_cast<DataObject*>(FeatureValueVectorDataObjectType::New().GetPointer()); +} + + +template< class TImage, class THistogramFrequencyContainer > +void +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +GenerateData(void) +{ + if (m_FastCalculations) + { + this->FastCompute(); + } + else + { + this->FullCompute(); + } +} + +template< class TImage, class THistogramFrequencyContainer > +void +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +FullCompute(void) +{ + int numOffsets = m_Offsets->size(); + int numFeatures = m_RequestedFeatures->size(); + double **features; + + features = new double *[numOffsets]; + for (int i = 0; i < numOffsets; i++) + { + features[i] = new double [numFeatures]; + } + + // For each offset, calculate each feature + typename OffsetVector::ConstIterator offsetIt; + int offsetNum, featureNum; + + for(offsetIt = m_Offsets->Begin(), offsetNum = 0; + offsetIt != m_Offsets->End(); offsetIt++, offsetNum++) + { + m_GLCMGenerator->SetOffset(offsetIt.Value()); + m_GLCMGenerator->Update(); + typename TextureFeaturesFilterType::Pointer glcmCalc = TextureFeaturesFilterType::New(); + glcmCalc->SetInput(m_GLCMGenerator->GetOutput()); + glcmCalc->Update(); + + typename FeatureNameVector::ConstIterator fnameIt; + for(fnameIt = m_RequestedFeatures->Begin(), featureNum = 0; + fnameIt != m_RequestedFeatures->End(); fnameIt++, featureNum++) + { + features[offsetNum][featureNum] = glcmCalc->GetFeature(fnameIt.Value()); + } + } + + // Now get the mean and deviaton of each feature across the offsets. + m_FeatureMeans->clear(); + m_FeatureStandardDeviations->clear(); + double *tempFeatureMeans = new double [numFeatures]; + double *tempFeatureDevs = new double [numFeatures]; + + /*Compute incremental mean and SD, a la Knuth, "The Art of Computer + Programming, Volume 2: Seminumerical Algorithms", section 4.2.2. + Compute mean and standard deviation using the recurrence relation: + M(1) = x(1), M(k) = M(k-1) + (x(k) - M(k-1) ) / k + S(1) = 0, S(k) = S(k-1) + (x(k) - M(k-1)) * (x(k) - M(k)) + for 2 <= k <= n, then + sigma = vcl_sqrt(S(n) / n) (or divide by n-1 for sample SD instead of + population SD). + */ + + // Set up the initial conditions (k = 1) + for (featureNum = 0; featureNum < numFeatures; featureNum++) + { + tempFeatureMeans[featureNum] = features[0][featureNum]; + tempFeatureDevs[featureNum] = 0; + } + // Run through the recurrence (k = 2 ... N) + for (offsetNum = 1; offsetNum < numOffsets; offsetNum++) + { + int k = offsetNum + 1; + for (featureNum = 0; featureNum < numFeatures; featureNum++) + { + double M_k_minus_1 = tempFeatureMeans[featureNum]; + double S_k_minus_1 = tempFeatureDevs[featureNum]; + double x_k = features[offsetNum][featureNum]; + + double M_k = M_k_minus_1 + (x_k - M_k_minus_1) / k; + double S_k = S_k_minus_1 + (x_k - M_k_minus_1) * (x_k - M_k); + + tempFeatureMeans[featureNum] = M_k; + tempFeatureDevs[featureNum] = S_k; + } + } + for (featureNum = 0; featureNum < numFeatures; featureNum++) + { + tempFeatureDevs[featureNum] = vcl_sqrt(tempFeatureDevs[featureNum] / numOffsets); + + m_FeatureMeans->push_back(tempFeatureMeans[featureNum]); + m_FeatureStandardDeviations->push_back(tempFeatureDevs[featureNum]); + } + + FeatureValueVectorDataObjectType* meanOutputObject= + static_cast<FeatureValueVectorDataObjectType*>(this->ProcessObject::GetOutput(0)); + meanOutputObject->Set( m_FeatureMeans ); + + FeatureValueVectorDataObjectType* standardDeviationOutputObject= + static_cast<FeatureValueVectorDataObjectType*>(this->ProcessObject::GetOutput(1)); + standardDeviationOutputObject->Set( m_FeatureStandardDeviations ); + + delete [] tempFeatureMeans; + delete [] tempFeatureDevs; + for(int i=0; i < numOffsets; i++) + { + delete [] features[i]; + } + delete[] features; +} + +template< class TImage, class THistogramFrequencyContainer > +void +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +FastCompute(void) +{ + // Compute the feature for the first offset + typename OffsetVector::ConstIterator offsetIt = m_Offsets->Begin(); + m_GLCMGenerator->SetOffset(offsetIt.Value()); + + m_GLCMGenerator->Update(); + typename TextureFeaturesFilterType::Pointer glcmCalc = TextureFeaturesFilterType::New(); + glcmCalc->SetInput(m_GLCMGenerator->GetOutput()); + glcmCalc->Update(); + + m_FeatureMeans->clear(); + m_FeatureStandardDeviations->clear(); + typename FeatureNameVector::ConstIterator fnameIt; + for(fnameIt = m_RequestedFeatures->Begin(); + fnameIt != m_RequestedFeatures->End(); fnameIt++) + { + m_FeatureMeans->push_back(glcmCalc->GetFeature(fnameIt.Value())); + m_FeatureStandardDeviations->push_back(0.0); + } + + FeatureValueVectorDataObjectType* meanOutputObject= + static_cast<FeatureValueVectorDataObjectType*>(this->ProcessObject::GetOutput(0)); + meanOutputObject->Set( m_FeatureMeans ); + + FeatureValueVectorDataObjectType* standardDeviationOutputObject= + static_cast<FeatureValueVectorDataObjectType*>(this->ProcessObject::GetOutput(1)); + standardDeviationOutputObject->Set( m_FeatureStandardDeviations ); + +} + + +template< class TImage, class THistogramFrequencyContainer > +void +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +SetInput( const ImageType * image ) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(0, + const_cast< ImageType* >( image ) ); + + m_GLCMGenerator->SetInput(image); +} + +template< class TImage, class THistogramFrequencyContainer > +void +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +SetNumberOfBinsPerAxis( unsigned int numberOfBins ) +{ + itkDebugMacro("setting NumberOfBinsPerAxis to " << numberOfBins); + m_GLCMGenerator->SetNumberOfBinsPerAxis(numberOfBins); + this->Modified(); +} + +template< class TImage, class THistogramFrequencyContainer > +void +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +SetPixelValueMinMax( PixelType min, PixelType max ) +{ + itkDebugMacro("setting Min to " << min << "and Max to " << max); + m_GLCMGenerator->SetPixelValueMinMax(min, max); + this->Modified(); +} + +template< class TImage, class THistogramFrequencyContainer > +void +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +SetMaskImage( const ImageType* image) +{ + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput(1, + const_cast< ImageType* >( image ) ); + + m_GLCMGenerator->SetMaskImage(image); +} + +template< class TImage, class THistogramFrequencyContainer > +const TImage * +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer > +::GetInput() const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const ImageType * > + (this->ProcessObject::GetInput(0) ); +} + +template< class TImage, class THistogramFrequencyContainer > +const typename +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >::FeatureValueVectorDataObjectType* +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >::GetFeatureMeansOutput() const +{ + return static_cast< const FeatureValueVectorDataObjectType*>(this->ProcessObject::GetOutput(0)); +} + +template< class TImage, class THistogramFrequencyContainer > +const typename +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >::FeatureValueVectorDataObjectType* +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer > +::GetFeatureStandardDeviationsOutput() const +{ + return static_cast< const FeatureValueVectorDataObjectType*>(this->ProcessObject::GetOutput(1)); +} + +template< class TImage, class THistogramFrequencyContainer > +const TImage * +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer > +::GetMaskImage() const +{ + if (this->GetNumberOfInputs() < 2) + { + return 0; + } + + return static_cast<const ImageType * > + (this->ProcessObject::GetInput(1) ); +} + + + +template< class TImage, class THistogramFrequencyContainer > +void +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +SetInsidePixelValue(PixelType insidePixelValue) +{ + itkDebugMacro("setting InsidePixelValue to " << insidePixelValue); + m_GLCMGenerator->SetInsidePixelValue(insidePixelValue); + this->Modified(); +} + +template< class TImage, class THistogramFrequencyContainer > +void +ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >:: +PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + os << indent << "RequestedFeatures: " << this->GetRequestedFeatures() << std::endl; + os << indent << "FeatureStandardDeviations: " << this->GetFeatureStandardDeviations() << std::endl; + os << indent << "FastCalculations: " << this->GetFastCalculations() << std::endl; + os << indent << "Offsets: " << this->GetOffsets() << std::endl; + os << indent << "FeatureMeans: " << this->GetFeatureMeans() << std::endl; +} + +} // end of namespace Statistics + +} // end of namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkSparseFrequencyContainer2.cxx b/Utilities/ITK/Code/Review/Statistics/itkSparseFrequencyContainer2.cxx new file mode 100644 index 0000000000..5bc747acc9 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSparseFrequencyContainer2.cxx @@ -0,0 +1,97 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSparseFrequencyContainer2.cxx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkSparseFrequencyContainer2.h" + +namespace itk{ +namespace Statistics{ + +SparseFrequencyContainer2 +::SparseFrequencyContainer2() +{ + m_TotalFrequency = NumericTraits< TotalAbsoluteFrequencyType >::Zero; +} + +void +SparseFrequencyContainer2 +::Initialize(unsigned long) +{ + this->SetToZero(); +} + +void +SparseFrequencyContainer2 +::SetToZero() +{ + typedef FrequencyContainerType::iterator IteratorType; + IteratorType iter = m_FrequencyContainer.begin(); + IteratorType end = m_FrequencyContainer.end(); + while ( iter != end ) + { + iter->second = NumericTraits< AbsoluteFrequencyType >::Zero; + ++iter; + } + m_TotalFrequency = NumericTraits< TotalAbsoluteFrequencyType >::Zero; +} + +bool +SparseFrequencyContainer2 +::SetFrequency(const InstanceIdentifier id, const AbsoluteFrequencyType value) +{ + // No need to test for bounds because in a map container the + // element is allocated if the key doesn't exist yet + AbsoluteFrequencyType frequency = this->GetFrequency(id); + m_FrequencyContainer[id] = value; + m_TotalFrequency += (value - frequency); + return true; +} + +SparseFrequencyContainer2::AbsoluteFrequencyType +SparseFrequencyContainer2 +::GetFrequency(const InstanceIdentifier id) const +{ + FrequencyContainerType::const_iterator iter = m_FrequencyContainer.find(id); + if ( iter != m_FrequencyContainer.end() ) + { + return iter->second; + } + else + { + return 0; + } +} + +bool +SparseFrequencyContainer2 +::IncreaseFrequency(const InstanceIdentifier id, const AbsoluteFrequencyType value) +{ + // No need to test for bounds because in a map container the + // element is allocated if the key doesn't exist yet + AbsoluteFrequencyType frequency = this->GetFrequency(id); + m_FrequencyContainer[id] = frequency + value; + m_TotalFrequency += value; + return true; +} + +void +SparseFrequencyContainer2 +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} + +} // end of namespace Statistics +} // end of namespace itk diff --git a/Utilities/ITK/Code/Review/Statistics/itkSparseFrequencyContainer2.h b/Utilities/ITK/Code/Review/Statistics/itkSparseFrequencyContainer2.h new file mode 100644 index 0000000000..d39f95b200 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSparseFrequencyContainer2.h @@ -0,0 +1,112 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSparseFrequencyContainer2.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSparseFrequencyContainer2_h +#define __itkSparseFrequencyContainer2_h + +#include <map> +#include "itkObjectFactory.h" +#include "itkObject.h" +#include "itkNumericTraits.h" +#include "itkMeasurementVectorTraits.h" + +namespace itk { +namespace Statistics { + +/** \class SparseFrequencyContainer2 + * \brief his class is a container for an histogram. + * + * This class uses an map to store histogram. If your histogram is dense + * use DenseHistogram. You should access each bin by + * (InstanceIdentifier)index or measurement vector. + */ + +class ITK_EXPORT SparseFrequencyContainer2 : public Object +{ +public: + /** Standard class typedefs. */ + typedef SparseFrequencyContainer2 Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Standard macros */ + itkTypeMacro(SparseFrequencyContainer2, Object); + itkNewMacro(Self); + + /** instance idenfitifer alias */ + typedef MeasurementVectorTraits::InstanceIdentifier InstanceIdentifier; + + /** Absolute frequency type alias */ + typedef MeasurementVectorTraits::AbsoluteFrequencyType AbsoluteFrequencyType; + + /** Absolute Total frequency type */ + typedef MeasurementVectorTraits::TotalAbsoluteFrequencyType TotalAbsoluteFrequencyType; + + /** Relative frequency type alias */ + typedef MeasurementVectorTraits::RelativeFrequencyType RelativeFrequencyType; + + /** Relative Relative frequency type */ + typedef MeasurementVectorTraits::TotalRelativeFrequencyType TotalRelativeFrequencyType; + + /** Histogram typedef support */ + typedef std::map< InstanceIdentifier, AbsoluteFrequencyType > FrequencyContainerType; + typedef FrequencyContainerType::const_iterator + FrequencyContainerConstIterator; + + /** prepares the frequency container */ + void Initialize(unsigned long length); + + /** Calls the SetToZero method of superclass to initialize all the bins to Zero. + * This should be done before starting to call the IncreaseFrequency method. */ + void SetToZero(); + + /** Method to set the frequency of histogram using instance identifier. It + * returns false when the Id is out of bounds */ + bool SetFrequency(const InstanceIdentifier id, const AbsoluteFrequencyType value); + + /** Method to increase the frequency by one. This function is convinent + * to create a histogram. It returns false when the id is out of bounds. */ + bool IncreaseFrequency(const InstanceIdentifier id, + const AbsoluteFrequencyType value); + + /** Method to get the frequency of a bin from the histogram. It will return + * zero when the Id is out of bounds. */ + AbsoluteFrequencyType GetFrequency(const InstanceIdentifier id) const; + + TotalAbsoluteFrequencyType GetTotalFrequency() + { + return m_TotalFrequency; + } + +protected: + SparseFrequencyContainer2(); + virtual ~SparseFrequencyContainer2() {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + SparseFrequencyContainer2(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + // Container of histogram + FrequencyContainerType m_FrequencyContainer; + TotalAbsoluteFrequencyType m_TotalFrequency; +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkStandardDeviationPerComponentSampleFilter.h b/Utilities/ITK/Code/Review/Statistics/itkStandardDeviationPerComponentSampleFilter.h new file mode 100644 index 0000000000..c515b24b75 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkStandardDeviationPerComponentSampleFilter.h @@ -0,0 +1,116 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStandardDeviationPerComponentSampleFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkStandardDeviationPerComponentSampleFilter_h +#define __itkStandardDeviationPerComponentSampleFilter_h + +#include "itkProcessObject.h" + +#include "itkArray.h" +#include "itkVariableSizeMatrix.h" +#include "itkSimpleDataObjectDecorator.h" +#include "itkNumericTraitsFixedArrayPixel.h" + +namespace itk { +namespace Statistics { + +/** \class StandardDeviationPerComponentSampleFilter + * \brief Calculates the covariance matrix of the target sample data. + * + * The filter calculates first the sample mean and use it in the covariance + * calculation. The covariance is computed as follows + * Let \f$\Sigma\f$ denotes covariance matrix for the sample, then: + * When \f$x_{i}\f$ is \f$i\f$th component of a measurement vector + * \f$\vec x\f$, \f$\mu_{i}\f$ is the \f$i\f$th componet of the \f$\vec\mu\f$, + * and the \f$\sigma_{ij}\f$ is the \f$ij\f$th componet \f$\Sigma\f$, + * \f$\sigma_{ij} = (x_{i} - \mu_{i})(x_{j} - \mu_{j})\f$ + * + * Without the plugged in mean vector, this calculator will perform + * the single pass mean and covariance calculation algorithm. + * + */ + +template< class TSample > +class ITK_EXPORT StandardDeviationPerComponentSampleFilter : + public ProcessObject +{ +public: + /** Standard class typedefs. */ + typedef StandardDeviationPerComponentSampleFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef TSample SampleType; + + /** Standard Macros */ + itkTypeMacro(StandardDeviationPerComponentSampleFilter, ProcessObject); + itkNewMacro(Self); + + /** Length of a measurement vector */ + typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; + + /** Measurement vector type */ + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename NumericTraits< MeasurementVectorType >::RealType MeasurementVectorRealType; + + /** Method to set/get the sample */ + void SetInput( const SampleType * sample ); + const SampleType * GetInput() const; + + /** MeasurementVector is not a DataObject, we need to decorate it to push it down + * a ProcessObject's pipeline */ + typedef SimpleDataObjectDecorator< MeasurementVectorRealType > MeasurementVectorRealDecoratedType; + + typedef MeasurementVectorRealDecoratedType OutputType; + + /** Return the standard deviation vector */ + const MeasurementVectorRealType GetStandardDeviationPerComponent() const; + const MeasurementVectorRealDecoratedType* GetStandardDeviationPerComponentOutput() const; + + /** Return the mean vector */ + const MeasurementVectorRealType GetMeanPerComponent() const; + const MeasurementVectorRealDecoratedType* GetMeanPerComponentOutput() const; + +protected: + StandardDeviationPerComponentSampleFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + StandardDeviationPerComponentSampleFilter(); + virtual ~StandardDeviationPerComponentSampleFilter(); + void PrintSelf(std::ostream& os, Indent indent) const; + + /** DataObject pointer */ + typedef DataObject::Pointer DataObjectPointer; + + virtual DataObjectPointer MakeOutput(unsigned int idx); + + void GenerateData(); + + MeasurementVectorSizeType GetMeasurementVectorSize() const; + +private: + +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkStandardDeviationPerComponentSampleFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkStandardDeviationPerComponentSampleFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkStandardDeviationPerComponentSampleFilter.txx new file mode 100644 index 0000000000..12abcbad2a --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkStandardDeviationPerComponentSampleFilter.txx @@ -0,0 +1,243 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStandardDeviationPerComponentSampleFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:43:58 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStandardDeviationPerComponentSampleFilter_txx +#define __itkStandardDeviationPerComponentSampleFilter_txx + +#include "itkStandardDeviationPerComponentSampleFilter.h" +#include "itkMeasurementVectorTraits.h" +#include "vnl/vnl_math.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +StandardDeviationPerComponentSampleFilter< TSample > +::StandardDeviationPerComponentSampleFilter() +{ + this->ProcessObject::SetNumberOfRequiredInputs(1); + this->ProcessObject::SetNumberOfRequiredOutputs(2); + + this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); + this->ProcessObject::SetNthOutput( 1, this->MakeOutput(1) ); +} + +template< class TSample > +StandardDeviationPerComponentSampleFilter< TSample > +::~StandardDeviationPerComponentSampleFilter() +{ +} + +template< class TSample > +void +StandardDeviationPerComponentSampleFilter< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} + +template< class TSample > +void +StandardDeviationPerComponentSampleFilter< TSample > +::SetInput( const SampleType * sample ) +{ + this->ProcessObject::SetNthInput(0, const_cast< SampleType* >( sample ) ); +} + +template< class TSample > +const TSample * +StandardDeviationPerComponentSampleFilter< TSample > +::GetInput( ) const +{ + if (this->GetNumberOfInputs() < 1) + { + return 0; + } + + return static_cast<const SampleType * > + (this->ProcessObject::GetInput(0) ); +} + +template< class TSample > +typename StandardDeviationPerComponentSampleFilter< TSample>::DataObjectPointer +StandardDeviationPerComponentSampleFilter< TSample > +::MakeOutput(unsigned int index ) +{ + if ( index == 0 ) + { + typedef typename MeasurementVectorTraitsTypes< MeasurementVectorType >::ValueType ValueType; + MeasurementVectorType standardDeviation; + MeasurementVectorTraits::SetLength( standardDeviation, this->GetMeasurementVectorSize() ); + standardDeviation.Fill( NumericTraits< ValueType >::Zero ); + typename MeasurementVectorRealDecoratedType::Pointer decoratedStandardDeviation = MeasurementVectorRealDecoratedType::New(); + decoratedStandardDeviation->Set( standardDeviation ); + return static_cast< DataObject * >( decoratedStandardDeviation.GetPointer() ); + } + + if ( index == 1 ) + { + typedef typename MeasurementVectorTraitsTypes< MeasurementVectorType >::ValueType ValueType; + MeasurementVectorType mean; + MeasurementVectorTraits::SetLength( mean, this->GetMeasurementVectorSize() ); + mean.Fill( NumericTraits< ValueType >::Zero ); + typename MeasurementVectorRealDecoratedType::Pointer decoratedStandardDeviation = MeasurementVectorRealDecoratedType::New(); + decoratedStandardDeviation->Set( mean ); + return static_cast< DataObject * >( decoratedStandardDeviation.GetPointer() ); + } + + itkExceptionMacro("Trying to create output of index " << index << " larger than the number of output"); +} + +template< class TSample > +typename StandardDeviationPerComponentSampleFilter< TSample >::MeasurementVectorSizeType +StandardDeviationPerComponentSampleFilter< TSample > +::GetMeasurementVectorSize() const +{ + const SampleType *input = this->GetInput(); + + if( input ) + { + return input->GetMeasurementVectorSize(); + } + + // Test if the Vector type knows its length + MeasurementVectorType vector; + MeasurementVectorSizeType measurementVectorSize = MeasurementVectorTraits::GetLength( vector ); + + if( measurementVectorSize ) + { + return measurementVectorSize; + } + + measurementVectorSize = 1; // Otherwise set it to an innocuous value + + return measurementVectorSize; +} + +template< class TSample > +inline void +StandardDeviationPerComponentSampleFilter< TSample > +::GenerateData() +{ + const SampleType *input = this->GetInput(); + + MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); + + MeasurementVectorRealDecoratedType * decoratedStandardDeviationOutput = + static_cast< MeasurementVectorRealDecoratedType * >( + this->ProcessObject::GetOutput(0)); + + MeasurementVectorRealDecoratedType * decoratedMean = + static_cast< MeasurementVectorRealDecoratedType * >( + this->ProcessObject::GetOutput(1)); + + + MeasurementVectorRealType sum; + MeasurementVectorRealType sumOfSquares; + MeasurementVectorRealType mean; + MeasurementVectorRealType standardDeviation; + + MeasurementVectorTraits::SetLength( sum, measurementVectorSize ); + MeasurementVectorTraits::SetLength( mean, measurementVectorSize ); + MeasurementVectorTraits::SetLength( sumOfSquares, measurementVectorSize ); + MeasurementVectorTraits::SetLength( standardDeviation, measurementVectorSize ); + + sum.Fill(0.0); + mean.Fill(0.0); + sumOfSquares.Fill(0.0); + standardDeviation.Fill(0.0); + + typename TSample::AbsoluteFrequencyType frequency; + + typedef typename TSample::TotalAbsoluteFrequencyType TotalAbsoluteFrequencyType; + TotalAbsoluteFrequencyType totalFrequency = + itk::NumericTraits< TotalAbsoluteFrequencyType >::Zero; + + typename TSample::ConstIterator iter = input->Begin(); + typename TSample::ConstIterator end = input->End(); + + MeasurementVectorType diff; + MeasurementVectorType measurements; + + MeasurementVectorTraits::SetLength( diff, measurementVectorSize ); + MeasurementVectorTraits::SetLength( measurements, measurementVectorSize ); + + //Compute the mean first + while (iter != end) + { + frequency = iter.GetFrequency(); + totalFrequency += frequency; + measurements = iter.GetMeasurementVector(); + + for( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + double value = measurements[i]; + sum[i] += frequency * value; + sumOfSquares[i] += frequency * value * value; + } + ++iter; + } + + for( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + const double meanValue = sum[i] / totalFrequency; + mean[i] = meanValue; + const double variance = + ( sumOfSquares[i] - meanValue * meanValue * totalFrequency ) / ( totalFrequency - 1.0 ); + standardDeviation[i] = vcl_sqrt( variance ); + } + + decoratedStandardDeviationOutput->Set( standardDeviation ); + decoratedMean->Set( mean ); +} + +template< class TSample > +const typename StandardDeviationPerComponentSampleFilter< TSample>::MeasurementVectorRealDecoratedType * +StandardDeviationPerComponentSampleFilter< TSample > +::GetStandardDeviationPerComponentOutput() const +{ + return static_cast<const MeasurementVectorRealDecoratedType *>(this->ProcessObject::GetOutput(0)); +} + +template< class TSample > +const typename StandardDeviationPerComponentSampleFilter< TSample>::MeasurementVectorRealType +StandardDeviationPerComponentSampleFilter< TSample > +::GetStandardDeviationPerComponent() const +{ + return this->GetStandardDeviationPerComponentOutput()->Get(); +} + +template< class TSample > +const typename StandardDeviationPerComponentSampleFilter< TSample>::MeasurementVectorRealDecoratedType * +StandardDeviationPerComponentSampleFilter< TSample > +::GetMeanPerComponentOutput() const +{ + return static_cast<const MeasurementVectorRealDecoratedType *>(this->ProcessObject::GetOutput(1)); +} + +template< class TSample > +const typename StandardDeviationPerComponentSampleFilter< TSample>::MeasurementVectorRealType +StandardDeviationPerComponentSampleFilter< TSample > +::GetMeanPerComponent() const +{ + return this->GetMeanPerComponentOutput()->Get(); +} + + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkStatisticsAlgorithm.h b/Utilities/ITK/Code/Review/Statistics/itkStatisticsAlgorithm.h new file mode 100644 index 0000000000..51aae7d75a --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkStatisticsAlgorithm.h @@ -0,0 +1,149 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsAlgorithm.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsAlgorithm_h +#define __itkStatisticsAlgorithm_h + +#include "itkSample.h" +#include "itkSubsample.h" + +namespace itk { +namespace Statistics { +namespace Algorithm { + +#if !defined(_MSC_VER) + +template< class TSize > +TSize FloorLog(TSize size); + +template< class TValue > +TValue MedianOfThree(const TValue a, const TValue b, const TValue c); + +template< class TSample > +void FindSampleBound(const TSample* sample, + typename TSample::ConstIterator begin, + typename TSample::ConstIterator end, + typename TSample::MeasurementVectorType &min, + typename TSample::MeasurementVectorType &max); + +template< class TSubsample > +void FindSampleBoundAndMean(const TSubsample* sample, + int beginIndex, + int endIndex, + typename TSubsample::MeasurementVectorType &min, + typename TSubsample::MeasurementVectorType &max, + typename TSubsample::MeasurementVectorType &mean); + +/** The Partition algorithm performs partial sorting in a sample. Given a + * partitionValue, the algorithm moves to the beginning of the sample all + * MeasurementVectors whose component activeDimension is smaller than the + * partitionValue. In this way, the sample is partially sorted in two groups. + * First the group with activeDimension component smaller than the + * partitionValue, then the group of MeasurementVectors with activeDimension + * component larger than the partitionValue. The Partition algorithm takes as + * input a sample, and a range in that sample defined by [beginIndex,endIndex]. + * Only the activeDimension components of the MeasurementVectors in the sample + * will be considered by the algorithm. The Algorithm return an index in the + * range of [beginIndex,endIndex] pointing to the element with activeDimension + * component closest to the partitionValue. */ +template< class TSubsample > +int Partition(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex, + const typename TSubsample::MeasurementType partitionValue); + +/** QuickSelect is an algorithm for finding the k-th largest element of a list. + * In this case, only of the components of the measurement vectors is + * considered. This component is defined by the argument activeDimension. The + * search is rectricted to the range between the index begin and end, also + * passed as arguments. In this version, a guess value for the median index is + * provided in the argument medianGuess. The algoritm returns the value of the + * activeDimension component in the MeasurementVector located in the kth position. + * http://en.wikipedia.org/wiki/Selection_algorithm */ +template< class TSubsample > +typename TSubsample::MeasurementType +QuickSelect(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex, + int kth, + typename TSubsample::MeasurementType medianGuess); + +/** QuickSelect is an algorithm for finding the k-th largest element of a list. + * In this case, only of the components of the measurement vectors is + * considered. This component is defined by the argument activeDimension. The + * search is rectricted to the range between the index begin and end, also + * passed as arguments. + * http://en.wikipedia.org/wiki/Selection_algorithm. */ +template< class TSubsample > +typename TSubsample::MeasurementType +QuickSelect(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex, + int kth); + +/** NthElement is an algorithm for finding the n-th largest element of a list. + * In this case, only of the components of the measurement vectors is + * considered. This component is defined by the argument activeDimension. The + * search is rectricted to the range between the index begin and end, also + * passed as arguments. This algorithm was based on the procedure used in the STL + * nth_element method.*/ +template< class TSubsample > +typename TSubsample::MeasurementType +NthElement(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex, + int nth); + +template< class TSubsample > +void InsertSort(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex); + +template< class TSubsample > +void DownHeap(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex, int node); + +template< class TSubsample > +void HeapSort(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex); + + +template< class TSubsample > +void IntrospectiveSortLoop(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, + int endIndex, + int depthLimit, + int sizeThreshold); + +template< class TSubsample > +void IntrospectiveSort(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex, + int sizeThreshold); + +#endif // #if defined(_MSC_VER) +} // end of namespace Algorithm +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkStatisticsAlgorithm.txx" +#endif + +#endif // #ifndef __itkStatisticsAlgorithm_h diff --git a/Utilities/ITK/Code/Review/Statistics/itkStatisticsAlgorithm.txx b/Utilities/ITK/Code/Review/Statistics/itkStatisticsAlgorithm.txx new file mode 100644 index 0000000000..2d78960be8 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkStatisticsAlgorithm.txx @@ -0,0 +1,708 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsAlgorithm.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsAlgorithm_txx +#define __itkStatisticsAlgorithm_txx + +#include "itkStatisticsAlgorithm.h" +#include "itkNumericTraits.h" + +namespace itk { +namespace Statistics { +namespace Algorithm { + +template< class TSize > +inline TSize FloorLog(TSize size) +{ + TSize k; + + for (k = 0; size != 1; size >>= 1) + { + ++k; + } + + return k; +} + +/** The endIndex should points one point after the last elements if multiple + * partitionValue exist in the sample the return index will points the middle + * of such values. Implemented following the description of the partition + * algorithm in the QuickSelect entry of the Wikipedia. + * http://en.wikipedia.org/wiki/Selection_algorithm. */ +template< class TSubsample > +inline int Partition(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex, + const typename TSubsample::MeasurementType partitionValue) +{ + typedef typename TSubsample::MeasurementType MeasurementType; + + int moveToFrontIndex = beginIndex; + int moveToBackIndex = endIndex-1; + + // + // Move to the back all entries whose activeDimension component is equal to + // the partitionValue. + // + while( moveToFrontIndex < moveToBackIndex ) + { + // + // Find the first element (from the back) that is in the wrong side of the partition. + // + while( moveToBackIndex >= beginIndex ) + { + if( sample->GetMeasurementVectorByIndex(moveToBackIndex)[activeDimension] != partitionValue ) + { + break; + } + moveToBackIndex--; + } + + // + // Find the first element (from the front) that is in the wrong side of the partition. + // + while( moveToFrontIndex < endIndex ) + { + if( sample->GetMeasurementVectorByIndex(moveToFrontIndex)[activeDimension] == partitionValue ) + { + break; + } + moveToFrontIndex++; + } + + if( moveToFrontIndex < moveToBackIndex ) + { + // + // Swap them to place them in the correct side of the partition + // + sample->Swap( moveToBackIndex, moveToFrontIndex ); + } + } + + + // + // Now, ignore the section at the end with all the values equal to the partition value, + // and start swapping entries that are in the wrong side of the partition. + // + moveToFrontIndex = beginIndex; + moveToBackIndex = endIndex-1; + while( moveToFrontIndex < moveToBackIndex ) + { + // + // Find the first element (from the back) that is in the wrong side of the partition. + // + while( moveToBackIndex >= beginIndex ) + { + if( sample->GetMeasurementVectorByIndex(moveToBackIndex)[activeDimension] < partitionValue ) + { + break; + } + moveToBackIndex--; + } + + // + // Find the first element (from the front) that is in the wrong side of the partition. + // + while( moveToFrontIndex < endIndex ) + { + if( sample->GetMeasurementVectorByIndex(moveToFrontIndex)[activeDimension] > partitionValue ) + { + break; + } + moveToFrontIndex++; + } + + + if( moveToFrontIndex < moveToBackIndex ) + { + // + // Swap them to place them in the correct side of the partition + // + sample->Swap( moveToBackIndex, moveToFrontIndex ); + } + } + + + // + // Take all the entries with activeDimension component equal to + // partitionValue, that were placed at the end of the list, and move them to + // the interface between smaller and larger values. + // + int beginOfSectionEqualToPartition = moveToFrontIndex; + moveToBackIndex = endIndex-1; + while( moveToFrontIndex < moveToBackIndex ) + { + // + // Find the first element (from the back) that is in the wrong side of the partition. + // + while( moveToBackIndex >= beginIndex ) + { + if( sample->GetMeasurementVectorByIndex(moveToBackIndex)[activeDimension] == partitionValue ) + { + break; + } + moveToBackIndex--; + } + + + // + // Find the first element (from the front) that is in the wrong side of the partition. + // + while( moveToFrontIndex < endIndex ) + { + if( sample->GetMeasurementVectorByIndex(moveToFrontIndex)[activeDimension] != partitionValue ) + { + break; + } + moveToFrontIndex++; + } + + if( moveToFrontIndex < moveToBackIndex ) + { + // + // Swap them to place them in the correct side of the partition + // + sample->Swap( moveToBackIndex, moveToFrontIndex ); + } + } + int endOfSectionEqualToPartition = moveToFrontIndex-1; + + int storeIndex = ( beginOfSectionEqualToPartition + endOfSectionEqualToPartition ) / 2; + + const MeasurementType pivotValue = sample->GetMeasurementVectorByIndex( storeIndex )[activeDimension]; + if( pivotValue != partitionValue ) + { + // The partition was done using a value that is not present in the sample. + // Therefore we must now find the largest value of the left section and + // swap it to the boundary between smaller and larger than the + // partitionValue. + for(int kk=beginIndex; kk<storeIndex; kk++) + { + MeasurementType nodeValue = sample->GetMeasurementVectorByIndex( kk )[activeDimension]; + MeasurementType boundaryValue = sample->GetMeasurementVectorByIndex( storeIndex )[activeDimension]; + if( nodeValue > boundaryValue ) + { + sample->Swap(kk, storeIndex); + } + } + + } + + return storeIndex; +} + + +template< class TValue > +inline TValue MedianOfThree(const TValue a, + const TValue b, + const TValue c) +{ + if (a < b) { + if (b < c) { + return b; + } + else if (a < c) { + return c; + } + else { + return a; + } + } + else if (a < c) { + return a; + } + else if (b < c) { + return c; + } + else { + return b; + } +} + +template< class TSample > +inline void FindSampleBound(const TSample* sample, + typename TSample::ConstIterator begin, + typename TSample::ConstIterator end, + typename TSample::MeasurementVectorType &min, + typename TSample::MeasurementVectorType &max) +{ + typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; + + const MeasurementVectorSizeType Dimension = sample->GetMeasurementVectorSize(); + if( Dimension == 0 ) + { + itkGenericExceptionMacro( + << "Length of a sample's measurement vector hasn't been set."); + } + // Sanity check + MeasurementVectorTraits::Assert( max, Dimension, + "Length mismatch StatisticsAlgorithm::FindSampleBound"); + MeasurementVectorTraits::Assert( min, Dimension, + "Length mismatch StatisticsAlgorithm::FindSampleBound"); + + if( sample->Size() == 0 ) + { + itkGenericExceptionMacro( + << "Attempting to compute bounds of a sample list containing no\ + measurement vectors" ); + } + + unsigned int dimension; + typename TSample::MeasurementVectorType temp; + + min = max = temp = begin.GetMeasurementVector(); + while (true) + { + for (dimension= 0; dimension < Dimension; dimension++) + { + if ( temp[dimension] < min[dimension]) + { + min[dimension] = temp[dimension]; + } + else if (temp[dimension] > max[dimension]) + { + max[dimension] = temp[dimension]; + } + } + ++begin; + if (begin == end) + { + break; + } + temp = begin.GetMeasurementVector(); + } // end of while +} + +/** The endIndex should points one point after the last elements. */ +template< class TSubsample > +inline void +FindSampleBoundAndMean(const TSubsample* sample, + int beginIndex, + int endIndex, + typename TSubsample::MeasurementVectorType &min, + typename TSubsample::MeasurementVectorType &max, + typename TSubsample::MeasurementVectorType &mean) +{ + typedef typename TSubsample::MeasurementType MeasurementType; + typedef typename TSubsample::MeasurementVectorType MeasurementVectorType; + + typedef typename TSubsample::MeasurementVectorSizeType MeasurementVectorSizeType; + const MeasurementVectorSizeType Dimension = sample->GetMeasurementVectorSize(); + if( Dimension == 0 ) + { + itkGenericExceptionMacro( + << "Length of a sample's measurement vector hasn't been set."); + } + + Array< double > sum( Dimension ); + + MeasurementVectorSizeType dimension; + MeasurementVectorType temp; + MeasurementVectorTraits::SetLength( temp, Dimension ); + MeasurementVectorTraits::SetLength( mean, Dimension ); + + min = max = temp = sample->GetMeasurementVectorByIndex(beginIndex); + double frequencySum = sample->GetFrequencyByIndex(beginIndex); + sum.Fill(0.0); + + while (true) + { + for (dimension= 0; dimension < Dimension; dimension++) + { + if ( temp[dimension] < min[dimension]) + { + min[dimension] = temp[dimension]; + } + else if (temp[dimension] > max[dimension]) + { + max[dimension] = temp[dimension]; + } + sum[dimension] += temp[dimension]; + } + ++beginIndex; + if (beginIndex == endIndex) + { + break; + } + temp = sample->GetMeasurementVectorByIndex(beginIndex); + frequencySum += sample->GetFrequencyByIndex(beginIndex); + } // end of while + + for (unsigned int i = 0; i < Dimension; i++) + { + mean[i] = (MeasurementType)(sum[i] / frequencySum); + } +} + +/** The endIndex should point one point after the last elements. Note that kth + * is an index in a different scale than [beginIndex,endIndex]. For example, + * it is possible to feed this function with beginIndex=15, endIndex=23, and + * kth=3, since we can ask for the element 3rd in the range [15,23]. */ + +template< class TSubsample > +inline typename TSubsample::MeasurementType +QuickSelect(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, + int endIndex, + int kth, + typename TSubsample::MeasurementType medianGuess) +{ + typedef typename TSubsample::MeasurementType MeasurementType; + + int begin = beginIndex; + int end = endIndex - 1; + int kthIndex = kth + beginIndex; + + MeasurementType tempMedian; + + // + // Select a pivot value + // + if (medianGuess != NumericTraits< MeasurementType >::NonpositiveMin()) + { + tempMedian = medianGuess; + } + else + { + const int length = end - begin; + const int middle = begin + length / 2; + const MeasurementType v1 = sample->GetMeasurementVectorByIndex(begin)[activeDimension]; + const MeasurementType v2 = sample->GetMeasurementVectorByIndex(end)[activeDimension]; + const MeasurementType v3 = sample->GetMeasurementVectorByIndex(middle)[activeDimension]; + tempMedian = MedianOfThree< MeasurementType >( v1, v2, v3 ); + } + + while( true ) + { + // Partition expects the end argument to be one past-the-end of the array. + // The index pivotNewIndex returned by Partition is in the range [begin,end]. + int pivotNewIndex = + Partition< TSubsample >(sample, activeDimension, begin, end+1, tempMedian); + + if( kthIndex == pivotNewIndex ) + { + break; + } + + if( kthIndex < pivotNewIndex ) + { + end = pivotNewIndex - 1; + } + else + { + begin = pivotNewIndex + 1; + } + + if( begin > end ) + { + break; + } + + const int length = end - begin; + const MeasurementType v1 = sample->GetMeasurementVectorByIndex(begin)[activeDimension]; + const MeasurementType v2 = sample->GetMeasurementVectorByIndex(end)[activeDimension]; + + // current partition has only 1 or 2 elements + if( length < 2 ) + { + if( v2 < v1 ) + { + sample->Swap(begin, end); + } + break; + } + + const int middle = begin + length / 2; + const MeasurementType v3 = sample->GetMeasurementVectorByIndex(middle)[activeDimension]; + tempMedian = MedianOfThree< MeasurementType >( v1, v2, v3 ); + } + + + return sample->GetMeasurementVectorByIndex(kthIndex)[activeDimension]; +} + + +template< class TSubsample > +inline typename TSubsample::MeasurementType +QuickSelect(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, + int endIndex, + int kth) +{ + typedef typename TSubsample::MeasurementType MeasurementType; + MeasurementType medianGuess = NumericTraits< MeasurementType >::NonpositiveMin(); + return QuickSelect< TSubsample >(sample, activeDimension, + beginIndex, endIndex, kth, medianGuess); +} + + +template< class TSubsample > +inline typename TSubsample::MeasurementType +NthElement(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, + int endIndex, + int nth) +{ + typedef typename TSubsample::MeasurementType MeasurementType; + + const int nthIndex = beginIndex + nth; + + int beginElement = beginIndex; + int endElement = endIndex; + + while( endElement - beginElement > 3) + { + const int begin = beginElement; + const int end = endElement-1; + const int length = endElement - beginElement; + const int middle = beginElement + length / 2; + + const MeasurementType v1 = sample->GetMeasurementVectorByIndex(begin)[activeDimension]; + const MeasurementType v2 = sample->GetMeasurementVectorByIndex(end)[activeDimension]; + const MeasurementType v3 = sample->GetMeasurementVectorByIndex(middle)[activeDimension]; + + const MeasurementType tempMedian = MedianOfThree< MeasurementType >( v1, v2, v3 ); + + int cut = UnguardedPartition( sample, activeDimension, beginElement, endElement, tempMedian ); + + if( cut <= nthIndex ) + { + beginElement = cut; + } + else + { + endElement = cut; + } + } + + InsertSort( sample, activeDimension, beginElement, endElement ); + + return sample->GetMeasurementVectorByIndex(nthIndex)[activeDimension]; +} + + +template< class TSubsample > +inline int UnguardedPartition(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, + int endIndex, + typename TSubsample::MeasurementType pivotValue ) +{ + typedef typename TSubsample::MeasurementType MeasurementType; + while( true ) + { + MeasurementType beginValue = + sample->GetMeasurementVectorByIndex(beginIndex)[activeDimension]; + + while( beginValue < pivotValue ) + { + ++beginIndex; + + beginValue = sample->GetMeasurementVectorByIndex(beginIndex)[activeDimension]; + } + + --endIndex; + + MeasurementType endValue = + sample->GetMeasurementVectorByIndex(endIndex)[activeDimension]; + + while( pivotValue < endValue ) + { + --endIndex; + endValue = sample->GetMeasurementVectorByIndex(endIndex)[activeDimension]; + } + + if( !(beginIndex < endIndex) ) + { + return beginIndex; + } + + sample->Swap( beginIndex, endIndex ); + + ++beginIndex; + } +} + + +template< class TSubsample > +inline void InsertSort(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, + int endIndex) +{ + int backwardSearchBegin; + int backwardIndex; + + for (backwardSearchBegin = beginIndex + 1; + backwardSearchBegin < endIndex; + backwardSearchBegin++) + { + backwardIndex = backwardSearchBegin; + while (backwardIndex > beginIndex) + { + if (sample->GetMeasurementVectorByIndex(backwardIndex)[activeDimension] < + sample->GetMeasurementVectorByIndex(backwardIndex - 1)[activeDimension]) + { + sample->Swap(backwardIndex, backwardIndex - 1); + } + else + { + break; + } + --backwardIndex; + } + } +} + +template< class TSubsample > +inline void DownHeap(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, int endIndex, int node) +{ + int currentNode = node; + int leftChild; + int rightChild; + int largerChild; + typedef typename TSubsample::MeasurementType MeasurementType; + MeasurementType currentNodeValue = + sample->GetMeasurementVectorByIndex(currentNode)[activeDimension]; + MeasurementType leftChildValue; + MeasurementType rightChildValue; + MeasurementType largerChildValue; + + while (true) + { + // location of first child + largerChild = leftChild = + beginIndex + 2*(currentNode - beginIndex) + 1; + rightChild = leftChild + 1; + if (leftChild > endIndex - 1) + { + // leaf node + return; + } + + largerChildValue = rightChildValue = leftChildValue = + sample->GetMeasurementVectorByIndex(leftChild)[activeDimension]; + + if (rightChild < endIndex) + { + rightChildValue = + sample->GetMeasurementVectorByIndex(rightChild)[activeDimension]; + } + + if (leftChildValue < rightChildValue) + { + largerChild = rightChild; + largerChildValue = rightChildValue; + } + + if (largerChildValue <= currentNodeValue) + { + // the node satisfies heap property + return; + } + // move down current node value to the larger child + sample->Swap(currentNode, largerChild); + currentNode = largerChild; + } +} + +template< class TSubsample > +inline void HeapSort(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, + int endIndex) +{ + // construct a heap + int node; + + for (node = beginIndex + (endIndex - beginIndex) / 2 - 1; + node >= beginIndex; node--) + { + DownHeap< TSubsample >(sample, activeDimension, + beginIndex, endIndex, node); + } + + // sort + int newEndIndex; + for (newEndIndex = endIndex - 1; newEndIndex >= beginIndex; + --newEndIndex) + { + sample->Swap(beginIndex, newEndIndex); + DownHeap< TSubsample >(sample, activeDimension, + beginIndex, newEndIndex, beginIndex); + } +} + + +template< class TSubsample > +inline void IntrospectiveSortLoop(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, + int endIndex, + int depthLimit, + int sizeThreshold) +{ + typedef typename TSubsample::MeasurementType MeasurementType; + + int length = endIndex - beginIndex; + int cut; + while(length > sizeThreshold) + { + if (depthLimit == 0) + { + HeapSort< TSubsample >(sample, activeDimension, + beginIndex, endIndex); + return; + } + + --depthLimit; + cut = Partition< TSubsample >(sample, activeDimension, + beginIndex, endIndex, + MedianOfThree< MeasurementType > + (sample->GetMeasurementVectorByIndex(beginIndex)[activeDimension], + sample->GetMeasurementVectorByIndex(beginIndex + length/2)[activeDimension], + sample->GetMeasurementVectorByIndex(endIndex - 1)[activeDimension])); + IntrospectiveSortLoop< TSubsample >(sample, activeDimension, + cut, endIndex, + depthLimit, sizeThreshold); + endIndex = cut; + length = endIndex - beginIndex; + } +} + +template< class TSubsample > +inline void IntrospectiveSort(TSubsample* sample, + unsigned int activeDimension, + int beginIndex, + int endIndex, + int sizeThreshold) +{ + typedef typename TSubsample::MeasurementType MeasurementType; + IntrospectiveSortLoop< TSubsample >(sample, activeDimension, beginIndex, endIndex, + 2 * FloorLog(endIndex - beginIndex), sizeThreshold); + InsertSort< TSubsample >(sample, activeDimension, beginIndex, endIndex); +} + +} // end of namespace Algorithm +} // end of namespace Statistics +} // end of namespace itk + +#endif // #ifndef __itkStatisticsAlgorithm_txx diff --git a/Utilities/ITK/Code/Review/Statistics/itkSubsample.h b/Utilities/ITK/Code/Review/Statistics/itkSubsample.h new file mode 100644 index 0000000000..c42a0be2ec --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSubsample.h @@ -0,0 +1,290 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSubsample.h,v $ + Language: C++ + Date: $Date: 2009-05-22 12:55:07 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSubsample_h +#define __itkSubsample_h + +#include "itkSample.h" +#include "itkMacro.h" +#include "itkObjectFactory.h" + +namespace itk { +namespace Statistics { + +/** \class Subsample + * \brief This class stores a subset of instance identifiers from another sample + * object. You can create a subsample out of another sample object or another + * subsample object. The class is useful when storing or extracting a portion + * of a sample object. Note that when the elements of a subsample are sorted, + * the instance identifiers of the subsample are sorted without changing the + * original source sample. Most Statistics algorithms (that derive from + * StatisticsAlgorithmBase accept Subsample objects as inputs). + * + */ +template< class TSample > +class ITK_EXPORT Subsample : + public TSample +{ +public: + /** Standard class typedefs */ + typedef Subsample Self; + typedef TSample Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(Subsample, Sample); + + /** standard New() method support */ + itkNewMacro(Self); + + /** Smart pointer to the actual sample data holder */ + typedef typename TSample::Pointer SamplePointer; + + /** Typedefs for Measurement vector, measurement, Instance Identifier, + * frequency, size, size element value from the template argument TSample */ + typedef typename TSample::MeasurementVectorType MeasurementVectorType; + typedef typename TSample::MeasurementType MeasurementType; + typedef typename TSample::InstanceIdentifier InstanceIdentifier; + typedef MeasurementVectorType ValueType; + + typedef typename TSample::AbsoluteFrequencyType AbsoluteFrequencyType; + typedef typename TSample::TotalAbsoluteFrequencyType TotalAbsoluteFrequencyType; + + /** Type of the storage for instances that belong to the class + * represented by a Subsample object. A Subsample object stores + * only the InstanceIdentifiers. The actual data is still in the Sample + * object */ + typedef std::vector< InstanceIdentifier > InstanceIdentifierHolder; + + /** Get the Id Holder */ + virtual const InstanceIdentifierHolder & GetIdHolder () const + { \ + return this->m_IdHolder; + } + + /** Plug in the actual sample data */ + void SetSample(const TSample* sample); + const TSample* GetSample() const; + + /** Initialize the subsample with all instances of the sample */ + void InitializeWithAllInstances(); + + /** Add instance to the subsample */ + void AddInstance(InstanceIdentifier id); + + /** returns SizeType object whose each element is the number of + * elements in each dimension */ + InstanceIdentifier Size() const; + + /** Clear the subsample */ + void Clear(); + + /** retunrs the measurement of the instance which is identified + * by the 'id' */ + const MeasurementVectorType & GetMeasurementVector( InstanceIdentifier id) const; + + /** returns the frequency of the instance which is identified by the 'id' */ + AbsoluteFrequencyType GetFrequency( InstanceIdentifier id ) const; + + /** returns the total frequency for the 'd' dimension */ + TotalAbsoluteFrequencyType GetTotalFrequency() const; + + void Swap(unsigned int index1, unsigned int index2); + + InstanceIdentifier GetInstanceIdentifier( unsigned int index ); + + MeasurementVectorType GetMeasurementVectorByIndex(unsigned int index) const; + + AbsoluteFrequencyType GetFrequencyByIndex(unsigned int index) const; + + /** Method to graft another sample */ + virtual void Graft( const DataObject *thatObject ); + + class ConstIterator + { + friend class Subsample; + public: + + ConstIterator( const Self * sample ) + { + *this = sample->Begin(); + } + + ConstIterator(const ConstIterator& iter) + { + m_Iter = iter.m_Iter; + m_Subsample = iter.m_Subsample; + m_Sample = iter.m_Sample; + } + + ConstIterator& operator=(const ConstIterator& iter) + { + m_Iter = iter.m_Iter; + m_Subsample = iter.m_Subsample; + m_Sample = iter.m_Sample; + return *this; + } + + bool operator!=(const ConstIterator& it) + { + return (m_Iter != it.m_Iter); + } + + bool operator==(const ConstIterator& it) + { + return (m_Iter == it.m_Iter); + } + + ConstIterator& operator++() + { + ++m_Iter; + return *this; + } + + AbsoluteFrequencyType GetFrequency() const + { + return m_Sample->GetFrequency(*m_Iter); + } + + const MeasurementVectorType & GetMeasurementVector() const + { + return m_Sample->GetMeasurementVector(*m_Iter); + } + + InstanceIdentifier GetInstanceIdentifier() const + { + return ( m_Iter - m_Subsample->GetIdHolder().begin() ); + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // Purposely not implemented + ConstIterator(); + + // Only to be called from the Subsample + ConstIterator(typename InstanceIdentifierHolder::const_iterator iter, + const Self* classSample) + :m_Iter(iter), m_Subsample(classSample), m_Sample(classSample->GetSample()) + {} + + // ConstIterator pointing to ImageToListAdaptor + typename InstanceIdentifierHolder::const_iterator m_Iter; + + // Pointer to Subsample object + const Self* m_Subsample; + const TSample* m_Sample; + + private: + + }; + + class Iterator: public ConstIterator + { + friend class Subsample; + + public: + + Iterator(Self * sample):ConstIterator( sample ) + { + } + + Iterator(const Iterator &iter):ConstIterator( iter ) + { + } + + Iterator& operator =(const Iterator & iter) + { + this->ConstIterator::operator=( iter ); + return *this; + } + +#if !(defined(_MSC_VER) && (_MSC_VER <= 1200)) + protected: +#endif + // To ensure const-correctness these method must not be in the public API. + // The are purposly not implemented, since they should never be called. + Iterator(); + Iterator(const Self * sample); + Iterator(typename InstanceIdentifierHolder::const_iterator iter, + const Self* classSample); + Iterator(const ConstIterator & it); + ConstIterator& operator=(const ConstIterator& it); + + // Only to be called from the Subsample + Iterator(typename InstanceIdentifierHolder::iterator iter, + Self* classSample) + :ConstIterator( iter, classSample ) + {} + + + private: + }; + + /** This method returns an iterator to the beginning of the + measurement vectors */ + Iterator Begin() + { + Iterator iter(m_IdHolder.begin(), this); + return iter; + } + + /** This method returns an iterator to the beginning of the + measurement vectors */ + Iterator End() + { + Iterator iter(m_IdHolder.end(), this); + return iter; + } + + ConstIterator Begin() const + { + ConstIterator iter(m_IdHolder.begin(), this); + return iter; + } + + ConstIterator End() const + { + ConstIterator iter(m_IdHolder.end(), this); + return iter; + } + +protected: + Subsample(); + virtual ~Subsample() {} + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + Subsample(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + const TSample* m_Sample; + InstanceIdentifierHolder m_IdHolder; + unsigned int m_ActiveDimension; + TotalAbsoluteFrequencyType m_TotalFrequency; +}; // end of class + + +} // end of namespace Statistics +} // end of namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkSubsample.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkSubsample.txx b/Utilities/ITK/Code/Review/Statistics/itkSubsample.txx new file mode 100644 index 0000000000..6db53da5d3 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkSubsample.txx @@ -0,0 +1,249 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSubsample.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSubsample_txx +#define __itkSubsample_txx + +#include "itkObject.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +Subsample< TSample > +::Subsample() +{ + m_Sample = 0; + m_TotalFrequency = NumericTraits< AbsoluteFrequencyType >::Zero; + m_ActiveDimension = 0; +} + +template< class TSample > +void +Subsample< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Sample: "; + if ( m_Sample != 0 ) + { + os << m_Sample << std::endl; + } + else + { + os << "not set." << std::endl; + } + + os << indent << "TotalFrequency: " << m_TotalFrequency << std::endl; + os << indent << "ActiveDimension: " << m_ActiveDimension << std::endl; + os << indent << "InstanceIdentifierHolder : " << &m_IdHolder << std::endl; +} + + +template< class TSample > +void +Subsample< TSample > +::SetSample(const TSample* sample) +{ + m_Sample = sample; + this->SetMeasurementVectorSize( m_Sample->GetMeasurementVectorSize() ); + this->Modified(); +} + +template< class TSample > +const TSample* +Subsample< TSample > +::GetSample() const +{ + return m_Sample; +} + +template< class TSample > +void +Subsample< TSample > +::InitializeWithAllInstances() +{ + m_IdHolder.resize(m_Sample->Size()); + typename InstanceIdentifierHolder::iterator idIter = m_IdHolder.begin(); + typename TSample::ConstIterator iter = m_Sample->Begin(); + typename TSample::ConstIterator last = m_Sample->End(); + m_TotalFrequency = NumericTraits< AbsoluteFrequencyType >::Zero; + while (iter != last) + { + *idIter++ = iter.GetInstanceIdentifier(); + m_TotalFrequency += iter.GetFrequency(); + ++iter; + } + this->Modified(); +} + + +template< class TSample > +void +Subsample< TSample > +::AddInstance(InstanceIdentifier id) +{ + if ( id > m_Sample->Size() ) + { + itkExceptionMacro("MeasurementVector " << id << " does not exist in the Sample"); + } + + m_IdHolder.push_back(id); + m_TotalFrequency += m_Sample->GetFrequency(id); + this->Modified(); +} + +template< class TSample > +typename Subsample< TSample >::InstanceIdentifier +Subsample< TSample > +::Size() const +{ + return static_cast<unsigned int>( m_IdHolder.size() ); +} + +template< class TSample > +void +Subsample< TSample > +::Clear() +{ + m_IdHolder.clear(); + m_TotalFrequency = NumericTraits< AbsoluteFrequencyType >::Zero; + this->Modified(); +} + +template< class TSample > +const typename Subsample< TSample>::MeasurementVectorType & +Subsample< TSample > +::GetMeasurementVector( InstanceIdentifier id) const +{ + if ( id >= m_IdHolder.size() ) + { + itkExceptionMacro("MeasurementVector " << id << " does not exist"); + } + + // translate the id to its Sample container id + InstanceIdentifier idInTheSample = m_IdHolder[id]; + return m_Sample->GetMeasurementVector( idInTheSample ); +} + +template< class TSample > +inline typename Subsample< TSample >::AbsoluteFrequencyType +Subsample< TSample > +::GetFrequency( InstanceIdentifier id ) const +{ + if ( id >= m_IdHolder.size() ) + { + itkExceptionMacro("MeasurementVector " << id << " does not exist"); + } + + // translate the id to its Sample container id + InstanceIdentifier idInTheSample = m_IdHolder[id]; + return m_Sample->GetFrequency(idInTheSample); +} + + +template< class TSample > +inline typename Subsample< TSample >::TotalAbsoluteFrequencyType +Subsample< TSample > +::GetTotalFrequency() const +{ + return m_TotalFrequency; +} + + +template< class TSample > +inline void +Subsample< TSample > +::Swap(unsigned int index1, unsigned int index2) +{ + if ( index1 >= m_IdHolder.size() || + index2 >= m_IdHolder.size() ) + { + itkExceptionMacro("Index out of range"); + } + + InstanceIdentifier temp = m_IdHolder[index1]; + m_IdHolder[index1] = m_IdHolder[index2]; + m_IdHolder[index2] = temp; + this->Modified(); +} + +template< class TSample > +inline typename Subsample< TSample >::MeasurementVectorType +Subsample< TSample > +::GetMeasurementVectorByIndex(unsigned int index) const +{ + if ( index >= m_IdHolder.size() ) + { + itkExceptionMacro("Index out of range"); + } + return m_Sample->GetMeasurementVector(m_IdHolder[index]); +} + +template< class TSample > +inline typename Subsample< TSample >::AbsoluteFrequencyType +Subsample< TSample > +::GetFrequencyByIndex(unsigned int index) const +{ + if ( index >= m_IdHolder.size() ) + { + itkExceptionMacro("Index out of range"); + } + + return m_Sample->GetFrequency(m_IdHolder[index]); +} + + +template< class TSample > +typename Subsample< TSample >::InstanceIdentifier +Subsample< TSample > +::GetInstanceIdentifier(unsigned int index) +{ + if ( index >= m_IdHolder.size() ) + { + itkExceptionMacro("Index out of range"); + } + return m_IdHolder[index]; +} + + +template< class TSample > +void +Subsample< TSample > +::Graft( const DataObject *thatObject ) +{ + this->Superclass::Graft(thatObject); + + // Most of what follows is really a deep copy, rather than grafting of + // output. Wish it were managed by pointers to bulk data. Sigh ! + + const Self *thatConst = dynamic_cast< const Self * >(thatObject); + if (thatConst) + { + Self *that = const_cast< Self * >(thatConst); + this->SetSample( that->GetSample() ); + this->m_IdHolder = that->m_IdHolder; + this->m_ActiveDimension = that->m_ActiveDimension; + this->m_TotalFrequency = that->m_TotalFrequency; + } +} + + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkTDistribution.cxx b/Utilities/ITK/Code/Review/Statistics/itkTDistribution.cxx new file mode 100644 index 0000000000..f567de0ad6 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkTDistribution.cxx @@ -0,0 +1,443 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkTDistribution.cxx,v $ + Language: C++ + Date: $Date: 2009-05-10 18:27:08 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "itkTDistribution.h" +#include "itkGaussianDistribution.h" +#include "itkNumericTraits.h" +#include "vnl/vnl_math.h" +#include "vnl/vnl_erf.h" + +extern "C" double dbetai_(double *x, double *pin, double *qin); +extern "C" double dgamma_(double *x); + +namespace itk { +namespace Statistics { + +TDistribution +::TDistribution() +{ + m_Parameters = ParametersType(1); + m_Parameters[0] = 1.0; +} + +void +TDistribution +::SetDegreesOfFreedom(long dof) +{ + bool modified = false; + + if (m_Parameters.GetSize() > 0) + { + if (m_Parameters[0] != static_cast<double>(dof) ) + { + modified = true; + } + } + + if (m_Parameters.GetSize() != 1) + { + m_Parameters = ParametersType(1); + } + + m_Parameters[0] = static_cast<double>(dof); + + if (modified) + { + this->Modified(); + } +} + +long +TDistribution +::GetDegreesOfFreedom() const +{ + if (m_Parameters.GetSize() != 1) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return static_cast<long>(m_Parameters[0]); +} + +double +TDistribution +::PDF(double x, long degreesOfFreedom) +{ + double dof = static_cast<double>(degreesOfFreedom); + double dofplusoneon2 = 0.5*(dof+1.0); + double dofon2 = 0.5*dof; + double pdf; + + pdf = (dgamma_(&dofplusoneon2) / dgamma_(&dofon2)) + / (sqrt(dof*vnl_math::pi) * pow(1.0 + ((x*x)/dof), dofplusoneon2)); + + return pdf; +} + +double +TDistribution +::PDF(double x, const ParametersType& p) +{ + if( p.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << p.size() + << " parameters."); + } + return TDistribution::PDF(x, static_cast<long>(p[0])); +} + +double +TDistribution +::CDF(double x, long degreesOfFreedom) +{ + double bx; + double pin, qin; + double dof; + + + // Based on Abramowitz and Stegun 26.7.1, which gives the probability + // that the absolute value of a random variable with a Student-t + // distribution is less than or equal to a specified t. + // + // P[|x| <= t] = 1 - Ix(v/2, 1/2) + // + // where Ix is the incomplete beta function and v is the number of + // degrees of freedom in the Student-t distribution and x is + // v / (v + t^2). + // + // To calculate the cdf of the Student-t we need to convert + // this formula. For an x >= 0, + // + // P[|x| <= t] = \int_{-t}^{t} p(x) dx + // = 2 \int_0^t p(x) dx + // + // The cdf of the Student-t is + // + // P[x <= t] = \int_{-\inf}^t p(x) dx + // = 0.5 + \int_0^t p(x) dx (for x >= 0) + // = 0.5 + 0.5 * P[|x| < t] (from above) + // = 0.5 + 0.5 * (1 - Ix(v/2. 1/2)) + // = 1 - 0.5 * Ix(v/2, 1/2) + // + dof = static_cast<double>(degreesOfFreedom); + bx = dof / (dof + (x*x)); + pin = dof / 2.0; + qin = 0.5; + + if (x >= 0.0) + { + return 1.0 - 0.5 * dbetai_(&bx, &pin, &qin); + } + else + { + return 0.5 * dbetai_(&bx, &pin, &qin); + } +} + +double +TDistribution +::CDF(double x, const ParametersType& p) +{ + if (p.GetSize() != 1) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << p.size() + << " parameters."); + } + return TDistribution::CDF(x, static_cast<long>(p[0])); +} + + +double +TDistribution +::InverseCDF(double p, long degreesOfFreedom) +{ + if (p <= 0.0) + { + return itk::NumericTraits<double>::NonpositiveMin(); + } + else if (p >= 1.0) + { + return itk::NumericTraits<double>::max(); + } + + double x; + double dof, dof2, dof3, dof4; + double gaussX, gaussX3, gaussX5, gaussX7, gaussX9; + + // Based on Abramowitz and Stegun 26.7.5 + dof = static_cast<double>(degreesOfFreedom); + dof2 = dof*dof; + dof3 = dof*dof2; + dof4 = dof*dof3; + + gaussX = GaussianDistribution::InverseCDF(p); + gaussX3 = pow(gaussX, 3.0); + gaussX5 = pow(gaussX, 5.0); + gaussX7 = pow(gaussX, 7.0); + gaussX9 = pow(gaussX, 9.0); + + x = gaussX + + (gaussX3 + gaussX) / (4.0 * dof) + + (5.0*gaussX5 + 16.0*gaussX3 + 3*gaussX) / (96.0 * dof2) + + (3.0*gaussX7 + 19.0*gaussX5 + 17.0*gaussX3 - 15.0*gaussX) / (384.0*dof3) + + (79.0*gaussX9 + + 776.0*gaussX7 + + 1482.0*gaussX5 + - 1920.0*gaussX3 + - 945.0*gaussX) / (92160.0 * dof4); + + // The polynomial approximation above is only accurate for large degrees + // of freedom. We'll improve the approximation by a few Newton + // iterations. + // + // 0 iterations, error = 1 at 1 degree of freedom + // 3 iterations, error = 10^-10 at 1 degree of freedom + // 100 iterations, erorr = 10^-12 at 1 degree of freedom + // + // 0 iterations, error = 10^-2 at 11 degrees of freedom + // 3 iterations, error = 10^-11 at 11 degrees of freedom + // 100 iterations, erorr = 10^-12 at 11 degrees of freedom + // + // + // We are trying to find the zero of + // + // f(x) = p - tcdf(x) = 0; + // + // So, + // + // x(n+1) = x(n) - f(x(n)) / f'(x(n)) + // = x(n) + (p - tcdf(x)) / tpdf(x) + // + // Note that f'(x) = - tpdf(x) + // + double delta; + for (unsigned int newt = 0; newt < 3; ++newt) + { + delta = (p - TDistribution::CDF(x, degreesOfFreedom)) + / TDistribution::PDF(x, degreesOfFreedom); + x += delta; + } + + + return x; +} + +double +TDistribution +::InverseCDF(double p, const ParametersType& params) +{ + if( params.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << params.size() + << " parameters."); + } + return TDistribution::InverseCDF(p, static_cast<long>(params[0])); +} + + +double +TDistribution +::EvaluatePDF(double x) const +{ + if( m_Parameters.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return TDistribution::PDF(x, static_cast<long>(m_Parameters[0])); +} + +double +TDistribution +::EvaluatePDF(double x, const ParametersType& p) const +{ + if (p.GetSize() != 1) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << p.size() + << " parameters."); + } + return TDistribution::PDF(x, static_cast<long>(p[0])); +} + +double +TDistribution +::EvaluatePDF(double x, long degreesOfFreedom) const +{ + return TDistribution::PDF(x, degreesOfFreedom); +} + + +double +TDistribution +::EvaluateCDF(double x) const +{ + if( m_Parameters.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return TDistribution::CDF(x, static_cast<long>(m_Parameters[0])); +} + +double +TDistribution +::EvaluateCDF(double x, const ParametersType& p) const +{ + if( p.GetSize() != 1 ) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << p.size() + << " parameters."); + } + return TDistribution::CDF(x, static_cast<long>(p[0])); +} + +double +TDistribution +::EvaluateCDF(double x, long degreesOfFreedom) const +{ + return TDistribution::CDF(x, degreesOfFreedom); +} + + +double +TDistribution +::EvaluateInverseCDF(double p) const +{ + if (m_Parameters.GetSize() != 1) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + return TDistribution::InverseCDF(p, static_cast<long>(m_Parameters[0])); +} + +double +TDistribution +::EvaluateInverseCDF(double p, const ParametersType& params) const +{ + if (params.GetSize() != 1) + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << params.size() + << " parameters."); + } + return TDistribution::InverseCDF(p, static_cast<long>(params[0])); +} + +double +TDistribution +::EvaluateInverseCDF(double p, long degreesOfFreedom) const +{ + return TDistribution::InverseCDF(p, degreesOfFreedom); +} + +bool +TDistribution +::HasVariance() const +{ + if (m_Parameters.GetSize() == 1) + { + if (m_Parameters[0] > 2) + { + return true; + } + } + else + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + + return false; +} + +double +TDistribution +::GetMean() const +{ + return 0.0; +} + +double +TDistribution +::GetVariance() const +{ + if (m_Parameters.GetSize() == 1) + { + if (m_Parameters[0] > 2) + { + double dof = static_cast<double>(m_Parameters[0]); + + return dof / (dof - 2.0); + } + else + { + return NumericTraits<double>::quiet_NaN(); + } + } + else + { + itkGenericExceptionMacro( + "Invalid number of parameters to describe distribution. Expected 1 parameter, but got " + << m_Parameters.size() + << " parameters."); + } + + return NumericTraits<double>::quiet_NaN(); +} + +void +TDistribution +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + if (m_Parameters.GetSize() > 0) + { + os << indent << "Degrees of freedom: " + << static_cast<long>(m_Parameters[0]) << std::endl; + } + else + { + os << indent << "Degrees of freedom: (unknown)" + << std::endl; + } +} + +} // end of namespace Statistics +} // end namespace itk diff --git a/Utilities/ITK/Code/Review/Statistics/itkTDistribution.h b/Utilities/ITK/Code/Review/Statistics/itkTDistribution.h new file mode 100644 index 0000000000..c48eb88ae1 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkTDistribution.h @@ -0,0 +1,212 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkTDistribution.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkTDistribution_h +#define __itkTDistribution_h + +#include "itkProbabilityDistribution.h" +#include "itkNumericTraits.h" + +namespace itk { +namespace Statistics { + +/** \class TDistribution + * \brief TDistribution class defines the interface for a univariate + * Student-t distribution (pdfs, cdfs, etc.). + * + * TDistribution provides access to the probability density + * function (pdf), the cumulative distribution function (cdf), and the + * inverse cumulative distribution function for a Student-t distribution. + * + * The EvaluatePDF(), EvaluateCDF, EvaluateInverseCDF() methods are + * all virtual, allowing algorithms to be written with an abstract + * interface to a distribution (with said distribution provided to the + * algorithm at run-time). Static methods, not requiring an instance + * of the distribution, are also provided. The static methods allow + * for optimized access to distributions when the distribution is + * known a priori to the algorithm. + * + * TDistributions are univariate. Multivariate versions may + * be provided under a separate superclass (since the parameters to the + * pdf and cdf would have to be vectors not scalars). + * + * TDistributions can be used for t tests. + * + * \note This work is part of the National Alliance for Medical Image + * Computing (NAMIC), funded by the National Institutes of Health + * through the NIH Roadmap for Medical Research, Grant U54 EB005149. + * Information on the National Centers for Biomedical Computing + * can be obtained from http://nihroadmap.nih.gov/bioinformatics. + */ +class ITK_EXPORT TDistribution : + public ProbabilityDistribution +{ +public: + /** Standard class typedefs */ + typedef TDistribution Self; + typedef ProbabilityDistribution Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Strandard macros */ + itkTypeMacro(TDistribution, ProbabilityDistribution); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Return the number of parameters. For a univariate Student-t + * distribution, the number of parameters is 1 (degrees of freedom) */ + virtual unsigned long GetNumberOfParameters() const { return 1; } + + /** Evaluate the probability density function (pdf). The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluatePDF(double x) const; + + /** Evaluate the probability density function (pdf). The parameters + * for the distribution are passed as a parameters vector. The + * ordering of the parameters is (degrees of freedom). */ + virtual double EvaluatePDF(double x, const ParametersType&) const; + + /** Evaluate the probability density function (pdf). The parameters + * of the distribution are passed as separate parameters. */ + virtual double EvaluatePDF(double x, long degreesOfFreedom) const; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluateCDF(double x) const; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * for the distribution are passed as a parameters vector. The + * ordering of the parameters is (degreesOfFreedom). */ + virtual double EvaluateCDF(double x, const ParametersType&) const; + + /** Evaluate the cumulative distribution function (cdf). The parameters + * of the distribution are passed as separate parameters. */ + virtual double EvaluateCDF(double x, long degreesOfFreedom) const; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * of the distribution are assigned via SetParameters(). */ + virtual double EvaluateInverseCDF(double p) const; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * for the distribution are passed as a parameters vector. The + * ordering of the parameters is (degrees of freedom). */ + virtual double EvaluateInverseCDF(double p, const ParametersType&) const; + + /** Evaluate the inverse cumulative distribution function (inverse + * cdf). Parameter p must be between 0.0 and 1.0. The parameters + * of the distribution are passed as separate parameters. */ + virtual double EvaluateInverseCDF(double p, long degreesOfFreedom) const; + + /** Set the number of degrees of freedom in the Student-t distribution. + * Defaults to 1 */ + virtual void SetDegreesOfFreedom(long); + + /** Get the number of degrees of freedom in the t + * distribution. Defaults to 1 */ + virtual long GetDegreesOfFreedom() const; + + /** Does the Student-t distribution have a mean? */ + virtual bool HasMean() const { return true; } + + /** Get the mean of the distribution. */ + virtual double GetMean() const; + + /** Does the Student-t distribution have a variance? Variance is + * only defined for degrees of freedom greater than 2 */ + virtual bool HasVariance() const; + + /** Get the variance of the distribution. If the variance does not exist, + * then quiet_NaN is returned. */ + virtual double GetVariance() const; + + + /** Static method to evaluate the probability density function (pdf) + * of a Student-t with a specified number of degrees of freedom. The + * static method provides optimized access without requiring an + * instance of the class. The degrees of freedom for the + * distribution are passed in a parameters vector. */ + static double PDF(double x, const ParametersType&); + + /** Static method to evaluate the probability density function (pdf) + * of a Student-t with a specified number of degrees of freedom. The + * static method provides optimized access without requiring an + * instance of the class. */ + static double PDF(double x, long degreesOfFreedom); + + /** Static method to evaluate the cumulative distribution function + * (cdf) of a Student-t with a specified number of degrees of + * freedom. The static method provides optimized access without + * requiring an instance of the class. The degrees of freedom are + * passed as a parameters vector. + * + * This is based on Abramowitz and Stegun 26.7.1. Accuracy is + * approximately 10^-14. + */ + static double CDF(double x, const ParametersType&); + + /** Static method to evaluate the cumulative distribution function + * (cdf) of a Student-t with a specified number of degrees of + * freedom. The static method provides optimized access without + * requiring an instance of the class. + * + * This is based on Abramowitz and Stegun 26.7.1. Accuracy is + * approximately 10^-14. + */ + static double CDF(double x, long degreesOfFreedom); + + /** Static method to evaluate the inverse cumulative distribution + * function of a Student-t with a specified number of degrees of + * freedom. The static method provides optimized access without + * requiring an instance of the class. Parameter p must be between + * 0.0 and 1.0. The degrees of freedom are passed as a parameters vector. + * + * This is based on Abramowitz and Stegun 26.7.5 followed by a few + * Newton iterations to improve the precision at low degrees of + * freedom. Accuracy is approximately 10^-10. + **/ + static double InverseCDF(double p, const ParametersType&); + + /** Static method to evaluate the inverse cumulative distribution + * function of a Student-t with a specified number of degrees of + * freedom. The static method provides optimized access without + * requiring an instance of the class. Parameter p must be between + * 0.0 and 1.0. + * + * This is based on Abramowitz and Stegun 26.7.5 followed by a few + * Newton iterations to improve the precision at low degrees of + * freedom. Accuracy is approximately 10^-10. + **/ + static double InverseCDF(double p, long degreesOfFreedom); + +protected: + TDistribution(void); + virtual ~TDistribution(void) {} + + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + TDistribution(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end of namespace Statistics +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkWeightedCentroidKdTreeGenerator.h b/Utilities/ITK/Code/Review/Statistics/itkWeightedCentroidKdTreeGenerator.h new file mode 100644 index 0000000000..7ed2fc7ad9 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkWeightedCentroidKdTreeGenerator.h @@ -0,0 +1,125 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkWeightedCentroidKdTreeGenerator.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkWeightedCentroidKdTreeGenerator_h +#define __itkWeightedCentroidKdTreeGenerator_h + +#include <vector> + +#include "itkSample.h" +#include "itkSubsample.h" +#include "itkKdTree.h" +#include "itkKdTreeGenerator.h" +#include "itkStatisticsAlgorithm.h" + +namespace itk { +namespace Statistics { + +/** \class WeightedCentroidKdTreeGenerator + * \brief This class generates a KdTree object with centroid information. + * + * The KdTree object stores measurment vectors in a k-d tree structure + * that is a binary tree. The partition value is the median value of one + * of the k dimension (partition dimension). The partition dimension is + * determined by the spread of measurement values in each dimension. The + * partition dimension is the dimension has the widest spread. Our + * implementation of k-d tree doesn't have any construction or insertion + * logic. Users should use this class or the KdTreeGenerator class. + * + * This class is derived from the KdTreeGenerator class. The only + * difference between this class and the KdTreeGenerator class is that + * the nonterminal node type of this class is + * KdTreeWeightedCentroidNonterminalNode and that of the + * KdTreeGenerator is KdTreeNonterminalNode. Therefore, the public + * interface is identical to each other. The nonterminal node generation + * routines differ. + * + * To run this generator, users should provides the bucket size + * (SetBucketSize method) and the input sample (SetSample method). The + * Update method will run this generator. To get the resulting KdTree + * object, call the GetOutput method. + * + * <b>Recent API changes:</b> + * The static const macro to get the length of a measurement vector, + * 'MeasurementVectorSize' has been removed to allow the length of a measurement + * vector to be specified at run time. It is now obtained from the sample set + * as input. You may query this length using the function GetMeasurementVectorSize(). + * + * \sa KdTree, KdTreeNode, KdTreeWeightedCentroidNonterminalNode, + * KdTreeTerminalNode, KdTreeGenerator + */ + +template < class TSample > +class ITK_EXPORT WeightedCentroidKdTreeGenerator : + public KdTreeGenerator< TSample > +{ +public: + /** Standard class typedefs */ + typedef WeightedCentroidKdTreeGenerator Self; + typedef KdTreeGenerator< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro(WeightedCentroidKdTreeGenerator, KdTreeGenerator); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** typedef alias for the source data container */ + typedef typename Superclass::MeasurementVectorType MeasurementVectorType; + typedef typename Superclass::MeasurementType MeasurementType; + typedef typename Superclass::SubsampleType SubsampleType; + typedef typename Superclass::SubsamplePointer SubsamplePointer; + typedef typename Superclass::KdTreeType KdTreeType; + typedef typename Superclass::KdTreeNodeType KdTreeNodeType; + + +protected: + /** Constructor */ + WeightedCentroidKdTreeGenerator(); + + /** Destructor */ + virtual ~WeightedCentroidKdTreeGenerator() {} + + void PrintSelf(std::ostream& os, Indent indent) const; + + /** Nonterminal node generation routine */ + virtual KdTreeNodeType* GenerateNonterminalNode(unsigned int beginIndex, + unsigned int endIndex, + MeasurementVectorType + &lowerBound, + MeasurementVectorType + &upperBound, + unsigned int level); + +private: + WeightedCentroidKdTreeGenerator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + MeasurementVectorType m_TempLowerBound; + MeasurementVectorType m_TempUpperBound; + MeasurementVectorType m_TempMean; +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkWeightedCentroidKdTreeGenerator.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkWeightedCentroidKdTreeGenerator.txx b/Utilities/ITK/Code/Review/Statistics/itkWeightedCentroidKdTreeGenerator.txx new file mode 100644 index 0000000000..985e70d7e4 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkWeightedCentroidKdTreeGenerator.txx @@ -0,0 +1,148 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkWeightedCentroidKdTreeGenerator.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkWeightedCentroidKdTreeGenerator_txx +#define __itkWeightedCentroidKdTreeGenerator_txx + +namespace itk { +namespace Statistics { + +template< class TSample > +WeightedCentroidKdTreeGenerator< TSample > +::WeightedCentroidKdTreeGenerator() +{ +} + +template< class TSample > +void +WeightedCentroidKdTreeGenerator< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); +} + +template< class TSample > +inline typename WeightedCentroidKdTreeGenerator< TSample >::KdTreeNodeType* +WeightedCentroidKdTreeGenerator< TSample > +::GenerateNonterminalNode(unsigned int beginIndex, + unsigned int endIndex, + MeasurementVectorType &lowerBound, + MeasurementVectorType &upperBound, + unsigned int level) +{ + MeasurementType dimensionLowerBound; + MeasurementType dimensionUpperBound; + MeasurementType partitionValue; + unsigned int partitionDimension = 0; + unsigned int i; + unsigned int j; + MeasurementType spread; + MeasurementType maxSpread; + unsigned int medianIndex; + + SubsamplePointer subsample = this->GetSubsample(); + + // Sanity check. Verify that the subsample has measurement vectors of the + // same length as the sample generated by the tree. + if( this->GetMeasurementVectorSize() != subsample->GetMeasurementVectorSize() ) + { + itkExceptionMacro( << "Measurement Vector Length mismatch" ); + } + + // calculates the weighted centroid which is the vector sum + // of all the associated instances. + typename KdTreeNodeType::CentroidType weightedCentroid; + MeasurementVectorTraits::SetLength( weightedCentroid, this->GetMeasurementVectorSize() ); + MeasurementVectorType tempVector; + weightedCentroid.Fill(NumericTraits< MeasurementType >::Zero); + + for (i = beginIndex; i < endIndex; i++) + { + tempVector = subsample->GetMeasurementVectorByIndex(i); + for(j = 0; j < this->GetMeasurementVectorSize(); j++) + { + weightedCentroid[j] += tempVector[j]; + } + } + + // find most widely spread dimension + Algorithm::FindSampleBoundAndMean< SubsampleType >(this->GetSubsample(), + beginIndex, endIndex, + m_TempLowerBound, m_TempUpperBound, + m_TempMean); + + maxSpread = NumericTraits< MeasurementType >::NonpositiveMin(); + for (i = 0; i < this->GetMeasurementVectorSize(); i++) + { + spread = m_TempUpperBound[i] - m_TempLowerBound[i]; + if (spread >= maxSpread) + { + maxSpread = spread; + partitionDimension = i; + } + } + + + medianIndex = (endIndex - beginIndex) / 2; + + // + // Find the medial element by using the NthElement function + // based on the STL implementation of the QuickSelect algorithm. + // + partitionValue = + Algorithm::NthElement< SubsampleType >(this->GetSubsample(), + partitionDimension, + beginIndex, endIndex, + medianIndex); + + medianIndex += beginIndex; + + // save bounds for cutting dimension + dimensionLowerBound = lowerBound[partitionDimension]; + dimensionUpperBound = upperBound[partitionDimension]; + + upperBound[partitionDimension] = partitionValue; + const unsigned int beginLeftIndex = beginIndex; + const unsigned int endLeftIndex = medianIndex; + KdTreeNodeType* left = GenerateTreeLoop(beginLeftIndex, endLeftIndex, lowerBound, upperBound, level + 1); + upperBound[partitionDimension] = dimensionUpperBound; + + lowerBound[partitionDimension] = partitionValue; + const unsigned int beginRightIndex = medianIndex+1; + const unsigned int endRighIndex = endIndex; + KdTreeNodeType* right = GenerateTreeLoop(beginRightIndex, endRighIndex, lowerBound, upperBound, level + 1); + lowerBound[partitionDimension] = dimensionLowerBound; + + + typedef KdTreeWeightedCentroidNonterminalNode< TSample > KdTreeNonterminalNodeType; + + KdTreeNonterminalNodeType * nonTerminalNode = + new KdTreeNonterminalNodeType( partitionDimension, + partitionValue, + left, right, + weightedCentroid, + endIndex - beginIndex); + + nonTerminalNode->AddInstanceIdentifier( + subsample->GetInstanceIdentifier( medianIndex ) ); + + return nonTerminalNode; +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkWeightedCovarianceSampleFilter.h b/Utilities/ITK/Code/Review/Statistics/itkWeightedCovarianceSampleFilter.h new file mode 100644 index 0000000000..009fd64311 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkWeightedCovarianceSampleFilter.h @@ -0,0 +1,113 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkWeightedCovarianceSampleFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkWeightedCovarianceSampleFilter_h +#define __itkWeightedCovarianceSampleFilter_h + +#include "itkFunctionBase.h" +#include "itkCovarianceSampleFilter.h" +#include "itkDataObjectDecorator.h" + +namespace itk { +namespace Statistics { + +/** \class WeightedCovarianceSampleFilter + * \brief Calculates the covariance matrix of the target sample data. + * where each measurement vector has an associated weight value + * + * Weight values can be specified in two ways: using a weighting function + * or an array containing weight values. If none of these two is specified, + * the covariance matrix is generated with equal weights. + * + * \sa CovarianceSampleFilter + * + */ + +template< class TSample > +class ITK_EXPORT WeightedCovarianceSampleFilter : + public CovarianceSampleFilter< TSample > +{ +public: + /** Standard class typedefs. */ + typedef WeightedCovarianceSampleFilter Self; + typedef CovarianceSampleFilter< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Standard Macros */ + itkTypeMacro(WeightedCovarianceSampleFilter, CovarianceSampleFilter); + itkNewMacro(Self); + + /** Traits derived from the base class */ + itkSuperclassTraitMacro( SampleType ) + itkSuperclassTraitMacro( MeasurementVectorType ) + itkSuperclassTraitMacro( MeasurementVectorSizeType ) + itkSuperclassTraitMacro( MeasurementVectorDecoratedType ) + itkSuperclassTraitMacro( OutputType ) + + /** Typedef for WeightedCovariance output */ + typedef VariableSizeMatrix< double > MatrixType; + + /** Weight calculation function typedef */ + typedef FunctionBase< MeasurementVectorType, double > WeightingFunctionType; + + /** VariableSizeMatrix is not a DataObject, we need to decorate it to push it down + * a ProcessObject's pipeline */ + typedef SimpleDataObjectDecorator< MatrixType > MatrixDecoratedType; + + /** Array typedef for weights */ + typedef Array< double > WeightArrayType; + + /** Type of DataObjects to use for the weight array type */ + typedef SimpleDataObjectDecorator< WeightArrayType > InputWeightArrayObjectType; + + /** Method to set the input value of the weight array */ + itkSetDecoratedInputMacro( Weights, WeightArrayType, 1 ); + + /** Type of DataObjects to use for Weight function */ + typedef DataObjectDecorator< WeightingFunctionType > InputWeightingFunctionObjectType; + + /** Method to set the weighting function */ + itkSetDecoratedObjectInputMacro( WeightingFunction, WeightingFunctionType, 2 ); + +protected: + WeightedCovarianceSampleFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + WeightedCovarianceSampleFilter(); + virtual ~WeightedCovarianceSampleFilter(); + void PrintSelf(std::ostream& os, Indent indent) const; + + void GenerateData(); + + /** Compute covariance matrix with weights computed from a function */ + void ComputeCovarianceMatrixWithWeightingFunction(); + + /** Compute covariance matrix with weights specified in an array */ + void ComputeCovarianceMatrixWithWeights(); + +private: +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkWeightedCovarianceSampleFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkWeightedCovarianceSampleFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkWeightedCovarianceSampleFilter.txx new file mode 100644 index 0000000000..99af06cefa --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkWeightedCovarianceSampleFilter.txx @@ -0,0 +1,288 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkWeightedCovarianceSampleFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkWeightedCovarianceSampleFilter_txx +#define __itkWeightedCovarianceSampleFilter_txx + +namespace itk { +namespace Statistics { + +template< class TSample > +WeightedCovarianceSampleFilter< TSample > +::WeightedCovarianceSampleFilter() +{ + this->ProcessObject::SetNthInput(1, NULL ); +} + + +template< class TSample > +WeightedCovarianceSampleFilter< TSample > +::~WeightedCovarianceSampleFilter() +{ +} + + +template< class TSample > +void +WeightedCovarianceSampleFilter< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + // m_Weights + os << indent << "Weights: " << this->GetWeightsInput() << std::endl; + // m_WeightingFunction + os << indent << "WeightingFunction: " << this->GetWeightingFunctionInput() << std::endl; +} + +template< class TSample > +inline void +WeightedCovarianceSampleFilter< TSample > +::GenerateData() +{ + // if weighting function is specifed, use it to compute the mean + const InputWeightingFunctionObjectType * functionObject = + this->GetWeightingFunctionInput(); + + if ( functionObject != NULL ) + { + this->ComputeCovarianceMatrixWithWeightingFunction(); + return; + } + + // if weight array is specified use it to compute the covariance + const InputWeightArrayObjectType * weightArrayObject = + this->GetWeightsInput(); + + if ( weightArrayObject != NULL ) + { + this->ComputeCovarianceMatrixWithWeights(); + return; + } + + // Otherwise compute the regular covariance matrix ( without weight coefficients) + Superclass::GenerateData(); + return; +} + +template< class TSample > +inline void +WeightedCovarianceSampleFilter< TSample > +::ComputeCovarianceMatrixWithWeightingFunction() +{ + const SampleType *input = this->GetInput(); + + MeasurementVectorSizeType measurementVectorSize = + input->GetMeasurementVectorSize(); + + MatrixDecoratedType * decoratedOutput = + static_cast< MatrixDecoratedType * >( + this->ProcessObject::GetOutput(0)); + + MatrixType output = decoratedOutput->Get(); + + MeasurementVectorDecoratedType * decoratedMeanOutput = + static_cast< MeasurementVectorDecoratedType * >( + this->ProcessObject::GetOutput(1)); + + output.SetSize( measurementVectorSize, measurementVectorSize ); + output.Fill(0.0); + + MeasurementVectorType mean; + mean.Fill(0.0); + + typename TSample::ConstIterator iter = input->Begin(); + typename TSample::ConstIterator end = input->End(); + + MeasurementVectorType diff; + MeasurementVectorType measurements; + + double weight; + double totalWeight = 0.0; + double sumSquaredWeight=0.0; + + // if weighting function is specifed, use it to compute the mean + const InputWeightingFunctionObjectType * functionObject = + this->GetWeightingFunctionInput(); + + const WeightingFunctionType * weightFunction = functionObject->Get(); + + //Compute the mean first + while (iter != end) + { + measurements = iter.GetMeasurementVector(); + weight = iter.GetFrequency() * weightFunction->Evaluate(measurements); + totalWeight += weight; + sumSquaredWeight += weight * weight; + + for( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + mean[i] += weight * measurements[i]; + } + ++iter; + } + + for( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + mean[i] = mean[i] / totalWeight; + } + + decoratedMeanOutput->Set( mean ); + + //reset iterator + iter = input->Begin(); + // fills the lower triangle and the diagonal cells in the covariance matrix + while (iter != end) + { + measurements = iter.GetMeasurementVector(); + weight = iter.GetFrequency() * weightFunction->Evaluate(measurements); + for ( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + diff[i] = measurements[i] - mean[i]; + } + + // updates the covariance matrix + for( unsigned int row = 0; row < measurementVectorSize; row++ ) + { + for( unsigned int col = 0; col < row + 1; col++) + { + output(row,col) += weight * diff[row] * diff[col]; + } + } + ++iter; + } + + // fills the upper triangle using the lower triangle + for( unsigned int row = 1; row < measurementVectorSize; row++) + { + for( unsigned int col = 0; col < row; col++) + { + output(col, row) = output(row, col); + } + } + + output /= ( totalWeight - ( sumSquaredWeight / totalWeight ) ); + + decoratedOutput->Set( output ); +} + + +template< class TSample > +inline void +WeightedCovarianceSampleFilter< TSample > +::ComputeCovarianceMatrixWithWeights() +{ + const SampleType *input = this->GetInput(); + + MeasurementVectorSizeType measurementVectorSize = + input->GetMeasurementVectorSize(); + + MatrixDecoratedType * decoratedOutput = + static_cast< MatrixDecoratedType * >( + this->ProcessObject::GetOutput(0)); + + MatrixType output = decoratedOutput->Get(); + + MeasurementVectorDecoratedType * decoratedMeanOutput = + static_cast< MeasurementVectorDecoratedType * >( + this->ProcessObject::GetOutput(1)); + + output.SetSize( measurementVectorSize, measurementVectorSize ); + output.Fill(0.0); + + MeasurementVectorType mean; + mean.Fill(0.0); + + typename TSample::ConstIterator iter = input->Begin(); + typename TSample::ConstIterator end = input->End(); + + MeasurementVectorType diff; + MeasurementVectorType measurements; + + double weight; + double totalWeight = 0.0; + double sumSquaredWeight=0.0; + + const InputWeightArrayObjectType * weightArrayObject = this->GetWeightsInput(); + const WeightArrayType weightArray = weightArrayObject->Get(); + + //Compute the mean first + unsigned int measurementVectorIndex = 0; + while (iter != end) + { + measurements = iter.GetMeasurementVector(); + weight = iter.GetFrequency() * (weightArray)[measurementVectorIndex]; + totalWeight += weight; + sumSquaredWeight += weight * weight; + + for( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + mean[i] += weight * measurements[i]; + } + ++iter; + ++measurementVectorIndex; + } + + for( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + mean[i] = mean[i] / totalWeight; + } + + decoratedMeanOutput->Set( mean ); + + //reset iterator + iter = input->Begin(); + // fills the lower triangle and the diagonal cells in the covariance matrix + measurementVectorIndex = 0; + while (iter != end) + { + weight = iter.GetFrequency() * (weightArray)[measurementVectorIndex]; + measurements = iter.GetMeasurementVector(); + + for ( unsigned int i = 0; i < measurementVectorSize; ++i ) + { + diff[i] = measurements[i] - mean[i]; + } + + // updates the covariance matrix + for( unsigned int row = 0; row < measurementVectorSize; row++ ) + { + for( unsigned int col = 0; col < row + 1; col++) + { + output(row,col) += weight * diff[row] * diff[col]; + } + } + ++iter; + ++measurementVectorIndex; + } + + // fills the upper triangle using the lower triangle + for( unsigned int row = 1; row < measurementVectorSize; row++) + { + for( unsigned int col = 0; col < row; col++) + { + output(col, row) = output(row, col); + } + } + + output /= ( totalWeight - ( sumSquaredWeight / totalWeight ) ); + + decoratedOutput->Set( output ); +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkWeightedMeanSampleFilter.h b/Utilities/ITK/Code/Review/Statistics/itkWeightedMeanSampleFilter.h new file mode 100644 index 0000000000..4b00184660 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkWeightedMeanSampleFilter.h @@ -0,0 +1,105 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkWeightedMeanSampleFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkWeightedMeanSampleFilter_h +#define __itkWeightedMeanSampleFilter_h + +#include "itkMeanSampleFilter.h" +#include "itkFunctionBase.h" +#include "itkDataObjectDecorator.h" + +namespace itk { +namespace Statistics { + +/** \class WeightedMeanSampleFilter + * \brief Given a sample where each measurement vector has + * associated weight value, this filter computes the sample mean + * + * To run this algorithm, you have plug in the target sample data + * using SetInput method and provides weight by an array or function. + *. Then call the Update method to run the alogithm. + * + * \sa MeanSampleFilter + * + */ +template< class TSample > +class ITK_EXPORT WeightedMeanSampleFilter : public MeanSampleFilter< TSample > +{ +public: + /**Standard class typedefs. */ + typedef WeightedMeanSampleFilter Self; + typedef MeanSampleFilter< TSample > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /**Standard Macros */ + itkTypeMacro(WeightedMeanSampleFilter, MeanSampleFilter); + itkNewMacro(Self); + + /** Traits derived from the base class */ + itkSuperclassTraitMacro( SampleType ) + itkSuperclassTraitMacro( MeasurementType ) + itkSuperclassTraitMacro( MeasurementVectorType ) + itkSuperclassTraitMacro( MeasurementVectorSizeType ) + itkSuperclassTraitMacro( MeasurementVectorDecoratedType ) + itkSuperclassTraitMacro( OutputType ) + + /** Array typedef for weights */ + typedef Array< double > WeightArrayType; + + /** Type of DataObjects to use for the weight array type */ + typedef SimpleDataObjectDecorator< WeightArrayType > InputWeightArrayObjectType; + + /** Method to set the input value of the weight array */ + itkSetDecoratedInputMacro( Weights, WeightArrayType, 1 ); + + /** Weight calculation function typedef */ + typedef FunctionBase< MeasurementVectorType, double > WeightingFunctionType; + + /** Type of DataObjects to use for Weight function */ + typedef DataObjectDecorator< WeightingFunctionType > InputWeightingFunctionObjectType; + + /** Method to set the weighting function */ + itkSetDecoratedObjectInputMacro( WeightingFunction, WeightingFunctionType, 2 ); + +protected: + WeightedMeanSampleFilter(); + virtual ~WeightedMeanSampleFilter(); + void PrintSelf(std::ostream& os, Indent indent) const; + + void GenerateData(); + + // compute mean with weight array + void ComputeMeanWithWeights(); + + // compute mean using a weighting function + void ComputeMeanWithWeightingFunction(); + +private: + WeightedMeanSampleFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end of namespace Statistics +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkWeightedMeanSampleFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/Statistics/itkWeightedMeanSampleFilter.txx b/Utilities/ITK/Code/Review/Statistics/itkWeightedMeanSampleFilter.txx new file mode 100644 index 0000000000..2818574ca6 --- /dev/null +++ b/Utilities/ITK/Code/Review/Statistics/itkWeightedMeanSampleFilter.txx @@ -0,0 +1,207 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkWeightedMeanSampleFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-02 05:44:00 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkWeightedMeanSampleFilter_txx +#define __itkWeightedMeanSampleFilter_txx + +#include "itkMeasurementVectorTraits.h" +#include "itkNumericTraits.h" + +namespace itk { +namespace Statistics { + +template< class TSample > +WeightedMeanSampleFilter< TSample > +::WeightedMeanSampleFilter() +{ + this->ProcessObject::SetNthInput(1, NULL ); +} + + +template< class TSample > +WeightedMeanSampleFilter< TSample > +::~WeightedMeanSampleFilter() +{ +} + + +template< class TSample > +void +WeightedMeanSampleFilter< TSample > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + // m_Weights + os << indent << "Weights: " << this->GetWeightsInput() << std::endl; + // m_WeightingFunction + os << indent << "Weighting Function: " << this->GetWeightingFunctionInput() << std::endl; +} + +template< class TSample > +void +WeightedMeanSampleFilter< TSample > +::GenerateData() +{ + // if weighting function is specifed, use it to compute the mean + const InputWeightingFunctionObjectType * functionObject = + this->GetWeightingFunctionInput(); + + + if ( functionObject != NULL ) + { + this->ComputeMeanWithWeightingFunction(); + return; + } + + // if weight array is specified use it to compute the mean + const InputWeightArrayObjectType * weightArrayObject = + this->GetWeightsInput(); + + if ( weightArrayObject != NULL ) + { + this->ComputeMeanWithWeights(); + return; + } + + // Otherwise compute the regular mean ( without weight coefficients) + Superclass::GenerateData(); + return; +} + +template< class TSample > +void +WeightedMeanSampleFilter< TSample > +::ComputeMeanWithWeights() +{ + const SampleType *input = this->GetInput(); + + MeasurementVectorSizeType measurementVectorSize = + input->GetMeasurementVectorSize(); + + MeasurementVectorDecoratedType * decoratedOutput = + static_cast< MeasurementVectorDecoratedType * >( + this->ProcessObject::GetOutput(0)); + + MeasurementVectorType output = decoratedOutput->Get(); + + //reset the output + for (unsigned int dim = 0; dim < measurementVectorSize; dim++) + { + output[dim] = NumericTraits< MeasurementType >::Zero; + } + + typename TSample::ConstIterator iter = input->Begin(); + typename TSample::ConstIterator end = input->End(); + double totalWeight = 0.0; + double weight; + + typename TSample::MeasurementVectorType measurements; + + const InputWeightArrayObjectType * weightArrayObject = this->GetWeightsInput(); + const WeightArrayType weightArray = weightArrayObject->Get(); + + int measurementVectorIndex = 0; + + while (iter != end) + { + measurements = iter.GetMeasurementVector(); + weight = iter.GetFrequency() * (weightArray)[measurementVectorIndex]; + totalWeight += weight; + + for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) + { + output[dim] += measurements[dim] * weight; + } + ++measurementVectorIndex; + ++iter; + } + + if ( totalWeight != 0.0 ) + { + for (unsigned int dim = 0; dim < measurementVectorSize; dim++) + { + output[dim] /= totalWeight; + } + } + + decoratedOutput->Set( output ); + +} + +template< class TSample > +void +WeightedMeanSampleFilter< TSample > +::ComputeMeanWithWeightingFunction() +{ + const SampleType *input = this->GetInput(); + + MeasurementVectorSizeType measurementVectorSize = + input->GetMeasurementVectorSize(); + + MeasurementVectorDecoratedType * decoratedOutput = + static_cast< MeasurementVectorDecoratedType * >( + this->ProcessObject::GetOutput(0)); + + MeasurementVectorType output = decoratedOutput->Get(); + + //reset the output + for (unsigned int dim = 0; dim < measurementVectorSize; dim++) + { + output[dim] = NumericTraits< MeasurementType >::Zero; + } + + typename TSample::ConstIterator iter = input->Begin(); + typename TSample::ConstIterator end = input->End(); + double totalWeight = 0.0; + double weight; + + typename TSample::MeasurementVectorType measurements; + + // if weighting function is specifed, use it to compute the mean + const InputWeightingFunctionObjectType * functionObject = + this->GetWeightingFunctionInput(); + + const WeightingFunctionType * weightFunction = functionObject->Get(); + + while (iter != end) + { + measurements = iter.GetMeasurementVector(); + weight = + iter.GetFrequency() * weightFunction->Evaluate(measurements); + totalWeight += weight; + for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) + { + output[dim] += measurements[dim] * weight; + } + ++iter; + } + + if ( totalWeight != 0.0 ) + { + for (unsigned int dim = 0; dim < measurementVectorSize; dim++) + { + output[dim] /= totalWeight; + } + } + + decoratedOutput->Set( output ); + +} + +} // end of namespace Statistics +} // end of namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkAnchorErodeDilateImageFilter.h b/Utilities/ITK/Code/Review/itkAnchorErodeDilateImageFilter.h index 88271951d1..660cd3927d 100644 --- a/Utilities/ITK/Code/Review/itkAnchorErodeDilateImageFilter.h +++ b/Utilities/ITK/Code/Review/itkAnchorErodeDilateImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnchorErodeDilateImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-07 03:20:20 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -79,7 +79,7 @@ public: /** Set/Get the boundary value. */ void SetBoundary( const InputImagePixelType value ); - itkGetMacro(Boundary, InputImagePixelType); + itkGetConstMacro(Boundary, InputImagePixelType); protected: AnchorErodeDilateImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkAnchorOpenCloseImageFilter.txx b/Utilities/ITK/Code/Review/itkAnchorOpenCloseImageFilter.txx index 6d3c4a0fe8..628afa54ea 100644 --- a/Utilities/ITK/Code/Review/itkAnchorOpenCloseImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkAnchorOpenCloseImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnchorOpenCloseImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-20 16:32:08 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-05-08 19:48:04 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -194,16 +194,25 @@ AnchorOpenCloseImageFilter<TImage, TKernel, TLessThan, TGreaterThan, TLessEqual, const InputImageRegionType face) { // iterate over the face - typedef ImageRegionConstIteratorWithIndex<InputImageType> ItType; - ItType it(input, face); - it.GoToBegin(); + + // we can't use an iterator with a region outside the image. All we need here is to + // iterate over all the indexes of the face, without accessing the content of the image. + // I can't find any cleaner way, so we use a dumb image, not even allocated, to iterate + // over all the indexes inside the region. + // + // typedef ImageRegionConstIteratorWithIndex<TImage> ItType; + // ItType it(input, face); + + typename TImage::Pointer dumbImg = TImage::New(); + dumbImg->SetRegions( face ); + KernelLType NormLine = line; NormLine.Normalize(); // set a generous tolerance float tol = 1.0/LineOffsets.size(); - while (!it.IsAtEnd()) + for( unsigned int it=0; it<face.GetNumberOfPixels(); it++ ) { - typename TImage::IndexType Ind = it.GetIndex(); + typename TImage::IndexType Ind = dumbImg->ComputeIndex( it ); unsigned start, end, len; if (FillLineBuffer<TImage, BresType, KernelLType>(input, Ind, @@ -223,7 +232,6 @@ AnchorOpenCloseImageFilter<TImage, TKernel, TLessThan, TGreaterThan, TLessEqual, AnchorLineOpen.DoLine(outbuffer,len+2); // compat CopyLineToImage<TImage, BresType>(output, Ind, LineOffsets, outbuffer, start, end); } - ++it; } } diff --git a/Utilities/ITK/Code/Review/itkAnchorUtilities.txx b/Utilities/ITK/Code/Review/itkAnchorUtilities.txx index fddd9b910b..e219ec41e7 100644 --- a/Utilities/ITK/Code/Review/itkAnchorUtilities.txx +++ b/Utilities/ITK/Code/Review/itkAnchorUtilities.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnchorUtilities.txx,v $ Language: C++ - Date: $Date: 2008-10-20 16:32:08 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-08 19:48:04 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -98,16 +98,25 @@ void DoAnchorFace(const TImage * input, const typename TImage::RegionType face) { // iterate over the face - typedef ImageRegionConstIteratorWithIndex<TImage> ItType; - ItType it(input, face); - it.GoToBegin(); + + // we can't use an iterator with a region outside the image. All we need here is to + // iterate over all the indexes of the face, without accessing the content of the image. + // I can't find any cleaner way, so we use a dumb image, not even allocated, to iterate + // over all the indexes inside the region. + // + // typedef ImageRegionConstIteratorWithIndex<TImage> ItType; + // ItType it(input, face); + + typename TImage::Pointer dumbImg = TImage::New(); + dumbImg->SetRegions( face ); + TLine NormLine = line; NormLine.Normalize(); // set a generous tolerance float tol = 1.0/LineOffsets.size(); - while (!it.IsAtEnd()) + for( unsigned int it=0; it<face.GetNumberOfPixels(); it++ ) { - typename TImage::IndexType Ind = it.GetIndex(); + typename TImage::IndexType Ind = dumbImg->ComputeIndex( it ); unsigned start, end, len; if (FillLineBuffer<TImage, TBres, TLine>(input, Ind, NormLine, tol, LineOffsets, AllImage, inbuffer, start, end)) @@ -125,7 +134,6 @@ void DoAnchorFace(const TImage * input, CopyLineToImage<TImage, TBres>(output, Ind, LineOffsets, inbuffer, start, end); #endif } - ++it; } } diff --git a/Utilities/ITK/Code/Review/itkAtanRegularizedHeavisideStepFunction.h b/Utilities/ITK/Code/Review/itkAtanRegularizedHeavisideStepFunction.h new file mode 100644 index 0000000000..054454dbe7 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkAtanRegularizedHeavisideStepFunction.h @@ -0,0 +1,95 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkAtanRegularizedHeavisideStepFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-09 21:12:23 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkAtanRegularizedHeavisideStepFunction_h +#define __itkAtanRegularizedHeavisideStepFunction_h + +#include "itkRegularizedHeavisideStepFunction.h" + +namespace itk +{ + +/** \class AtanRegularizedHeavisideStepFunction + * + * \brief Atan-based implementation of the Regularized (smoothed) Heaviside functions. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template< class TInput = float, class TOutput = double > +class AtanRegularizedHeavisideStepFunction : + public RegularizedHeavisideStepFunction< TInput, TOutput > +{ +public: + typedef AtanRegularizedHeavisideStepFunction Self; + typedef RegularizedHeavisideStepFunction< TInput, TOutput > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + itkNewMacro( Self ); + + itkTypeMacro( AtanRegularizedHeavisideStepFunction, RegularizedHeavisideStepFunction ); + + typedef typename Superclass::InputType InputType; + typedef typename Superclass::OutputType OutputType; + typedef typename Superclass::RealType RealType; + + /** Evaluate at the specified input position */ + virtual OutputType Evaluate( const InputType& input ) const + { + return 0.5 + ( vnl_math::one_over_pi * vcl_atan( input * this->GetOneOverEpsilon() ) ); + } + + /** Evaluate the derivative at the specified input position */ + virtual OutputType EvaluateDerivative( const InputType& input ) const + { + const RealType t = ( input * this->GetOneOverEpsilon() ); + return static_cast< OutputType>( vnl_math::one_over_pi / (1.0 + t * t ) ); + } + +protected: + AtanRegularizedHeavisideStepFunction() {} + virtual ~AtanRegularizedHeavisideStepFunction() {} + +private: + AtanRegularizedHeavisideStepFunction(const Self& ); //purposely not implemented + void operator=(const Self& ); //purposely not implemented + +}; + +} + +#endif diff --git a/Utilities/ITK/Code/Review/itkAttributeMorphologyBaseImageFilter.h b/Utilities/ITK/Code/Review/itkAttributeMorphologyBaseImageFilter.h index dd1c96f711..db15441fd6 100644 --- a/Utilities/ITK/Code/Review/itkAttributeMorphologyBaseImageFilter.h +++ b/Utilities/ITK/Code/Review/itkAttributeMorphologyBaseImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAttributeMorphologyBaseImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-20 17:59:59 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.5 $ Copyright ( c ) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -127,7 +127,7 @@ public: * are removed. Lambda defaults to 0. */ itkSetMacro(Lambda, AttributeType); - itkGetMacro(Lambda, AttributeType); + itkGetConstMacro(Lambda, AttributeType); protected: AttributeMorphologyBaseImageFilter() diff --git a/Utilities/ITK/Code/Review/itkAutumnColormapFunctor.h b/Utilities/ITK/Code/Review/itkAutumnColormapFunctor.h new file mode 100644 index 0000000000..8b2d75d886 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkAutumnColormapFunctor.h @@ -0,0 +1,76 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkAutumnColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkAutumnColormapFunctor_h +#define __itkAutumnColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class AutumnColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT AutumnColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef AutumnColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + AutumnColormapFunctor() {}; + ~AutumnColormapFunctor() {}; + +private: + AutumnColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkAutumnColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkAutumnColormapFunctor.txx b/Utilities/ITK/Code/Review/itkAutumnColormapFunctor.txx new file mode 100644 index 0000000000..fb151edf2f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkAutumnColormapFunctor.txx @@ -0,0 +1,56 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkAutumnColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkAutumnColormapFunctor_txx +#define __itkAutumnColormapFunctor_txx + +#include "itkAutumnColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename AutumnColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +AutumnColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color mapping. + RealType red = 1.0; + + RealType green = value; + + RealType blue = 0.0; + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkBSplineDeformableTransformInitializer.h b/Utilities/ITK/Code/Review/itkBSplineDeformableTransformInitializer.h new file mode 100644 index 0000000000..e9c93690b4 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBSplineDeformableTransformInitializer.h @@ -0,0 +1,137 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBSplineDeformableTransformInitializer.h,v $ + Language: C++ + Date: $Date: 2009-05-14 20:35:00 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkBSplineDeformableTransformInitializer_h +#define __itkBSplineDeformableTransformInitializer_h + +#include "itkObject.h" +#include "itkObjectFactory.h" + +#include <iostream> + +namespace itk +{ + +/** \class BSplineDeformableTransformInitializer + * \brief BSplineDeformableTransformInitializer is a helper class intended to + * initialize the grid parameters of a BSplineDeformableTransform based on the + * parameters of an image. + * + * In the context of image registration, the image to be used are reference will + * be the fixed image. The BSpline grid will use the fixed image as a base for + * computing the grid spacing, orientation and origin, among other things. + * + * This code was contributed in the Insight Journal paper: + * + * "Helper class for initializing the grid parameters of + * a BSpline deformable transform by using an image as reference" + * + * http://www.insight-journal.org/browse/publication/216 + * http://hdl.handle.net/1926/1338 + * + * + * \ingroup Transforms + */ +template < class TTransform, class TImage > +class ITK_EXPORT BSplineDeformableTransformInitializer : public Object +{ +public: + /** Standard class typedefs. */ + typedef BSplineDeformableTransformInitializer Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** New macro for creation of through a Smart Pointer. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( BSplineDeformableTransformInitializer, Object ); + + /** Type of the transform to initialize */ + typedef TTransform TransformType; + + /** Types defined from transform traits */ + typedef typename TransformType::Pointer TransformPointer; + typedef typename TransformType::RegionType TransformRegionType; + typedef typename TransformRegionType::SizeType TransformSizeType; + + + /** Dimension of parameters. */ + itkStaticConstMacro(SpaceDimension, unsigned int, + TransformType::InputSpaceDimension); + + /** Image Types to use in the initialization of the transform */ + typedef TImage ImageType; + typedef typename ImageType::ConstPointer ImagePointer; + + + /** Set the transform to be initialized */ + itkSetObjectMacro( Transform, TransformType ); + + /** Set the fixed image used in the registration process */ + itkSetConstObjectMacro( Image, ImageType ); + + /** Set the number of grid nodes that we want to place inside the image. This + * method will override the settings of any previous call to + * SetNumberOfGridNodesInsideTheImage(). */ + itkSetMacro( GridSizeInsideTheImage, TransformSizeType ); + + /** Set the number of grid nodes that we want to place inside the image. This + * number of node is used along one dimension of the image. Therefore, if + * you pass the number 5 as argument of this method, in a 3D space, then the + * total number of grid nodes inside the image will be \$ 5 x 5 x 5 \$ . + * This method will override the settings of any previous call to + * SetGridSizeInsideTheImage(). */ + void SetNumberOfGridNodesInsideTheImage( unsigned int numberOfNodes ) + { + this->m_GridSizeInsideTheImage.Fill( numberOfNodes ); + this->Modified(); + } + + /** Initialize the transform using data from the images */ + virtual void InitializeTransform() const; + +protected: + BSplineDeformableTransformInitializer(); + ~BSplineDeformableTransformInitializer(){}; + + void PrintSelf(std::ostream &os, Indent indent) const; + +private: + BSplineDeformableTransformInitializer(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + TransformPointer m_Transform; + + ImagePointer m_Image; + + TransformSizeType m_GridSizeInsideTheImage; + + unsigned int m_NumberOfGridNodesInsideTheImage; + +}; //class BSplineDeformableTransformInitializer + + +} // namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkBSplineDeformableTransformInitializer.txx" +#endif + +#endif /* __itkBSplineDeformableTransformInitializer_h */ diff --git a/Utilities/ITK/Code/Review/itkBSplineDeformableTransformInitializer.txx b/Utilities/ITK/Code/Review/itkBSplineDeformableTransformInitializer.txx new file mode 100644 index 0000000000..869f7aff2e --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBSplineDeformableTransformInitializer.txx @@ -0,0 +1,154 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBSplineDeformableTransformInitializer.txx,v $ + Language: C++ + Date: $Date: 2009-05-14 23:34:24 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkBSplineDeformableTransformInitializer_txx +#define __itkBSplineDeformableTransformInitializer_txx + +#include "itkBSplineDeformableTransformInitializer.h" + +namespace itk +{ + + +template < class TTransform, class TImage > +BSplineDeformableTransformInitializer<TTransform, TImage > +::BSplineDeformableTransformInitializer() +{ + this->m_GridSizeInsideTheImage.Fill( 5 ); +} + + +template < class TTransform, class TImage > +void +BSplineDeformableTransformInitializer<TTransform, TImage > +::InitializeTransform() const +{ + // Sanity check + if( ! this->m_Image ) + { + itkExceptionMacro( "Reference Image has not been set" ); + return; + } + + if( ! this->m_Transform ) + { + itkExceptionMacro( "Transform has not been set" ); + return; + } + + // If the image come from a filter, then update that filter. + if( this->m_Image->GetSource() ) + { + this->m_Image->GetSource()->Update(); + } + + typedef typename TransformType::RegionType RegionType; + + typename RegionType::SizeType numberOfGridNodesOutsideTheImageSupport; + typename RegionType::SizeType totalGridSize; + + numberOfGridNodesOutsideTheImageSupport.Fill( TransformType::SplineOrder ); + + totalGridSize = this->m_GridSizeInsideTheImage; + totalGridSize += numberOfGridNodesOutsideTheImageSupport; + + RegionType gridRegion; + gridRegion.SetSize( totalGridSize ); + + typedef typename TransformType::SpacingType SpacingType; + const SpacingType & imageSpacing = this->m_Image->GetSpacing(); + + typedef typename TransformType::OriginType OriginType; + const OriginType & imageOrigin = this->m_Image->GetOrigin(); + + const typename TransformType::RegionType & imageRegion = + this->m_Image->GetLargestPossibleRegion(); + + typename ImageType::SizeType fixedImageSize = imageRegion.GetSize(); + + SpacingType gridSpacing; + SpacingType gridOriginShift; + + const unsigned int orderShift = TransformType::SplineOrder / 2; + + for( unsigned int r = 0; r < SpaceDimension; r++ ) + { + const unsigned int numberOfGridCells = this->m_GridSizeInsideTheImage[r] - 1; + const unsigned int numberOfImagePixels = fixedImageSize[r]; + + gridSpacing[r] = imageSpacing[r] * + static_cast<double>(numberOfImagePixels) / + static_cast<double>(numberOfGridCells); + + // Shift half image pixel to cover the image support + const double imageSupportShift = - imageSpacing[r] / 2.0; + + // Shift by the number of extra grid cells required by + // the BSpline order. + const double gridSupportShift = -1.0 * gridSpacing[r] * orderShift; + + // Combine both shifts. They are both aligned with the coordinate + // system of the grid. Direction has not been considered so far. + gridOriginShift[r] = gridSupportShift + imageSupportShift; + } + + typename ImageType::DirectionType gridDirection = this->m_Image->GetDirection(); + SpacingType gridOriginOffset = gridDirection * gridOriginShift; + + OriginType gridOrigin = imageOrigin + gridOriginOffset; + + this->m_Transform->SetGridRegion( gridRegion ); + this->m_Transform->SetGridOrigin( gridOrigin ); + this->m_Transform->SetGridSpacing( gridSpacing ); + this->m_Transform->SetGridDirection( gridDirection ); +} + + +template < class TTransform, class TImage > +void +BSplineDeformableTransformInitializer<TTransform, TImage > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Transform = " << std::endl; + if( this->m_Transform ) + { + os << indent << this->m_Transform << std::endl; + } + else + { + os << indent << "None" << std::endl; + } + + os << indent << "Image = " << std::endl; + if( this->m_Image ) + { + os << indent << this->m_Image << std::endl; + } + else + { + os << indent << "None" << std::endl; + } + os << "Grid size inside the image " << this->m_GridSizeInsideTheImage << std::endl; + os << "Number of grid nodes inside the image " << this->m_NumberOfGridNodesInsideTheImage << std::endl; + +} + +} // namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkBSplineScatteredDataPointSetToImageFilter.h b/Utilities/ITK/Code/Review/itkBSplineScatteredDataPointSetToImageFilter.h index 04b243b2f0..5a935450b5 100644 --- a/Utilities/ITK/Code/Review/itkBSplineScatteredDataPointSetToImageFilter.h +++ b/Utilities/ITK/Code/Review/itkBSplineScatteredDataPointSetToImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineScatteredDataPointSetToImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-10 12:16:55 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-20 14:53:42 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,6 +18,7 @@ #define __itkBSplineScatteredDataPointSetToImageFilter_h #include "itkPointSetToImageFilter.h" +#include "itkBSplineKernelFunction.h" #include "itkCoxDeBoorBSplineKernelFunction.h" #include "itkFixedArray.h" #include "itkVariableSizeMatrix.h" @@ -48,9 +49,7 @@ namespace itk * the number of control points for the coarsest level. The algorithm * then increases the number of control points at each level so that * the B-spline n-D grid is refined to twice the previous level. The - * scattered data is specified by the pixel values. Pixels which - * are not to be included in the calculation of the B-spline grid must - * have a value equal to that specified by the variable m_BackgroundValue. + * scattered data is specified by the pixel values. * * Note that the specified number of control points must be > m_SplineOrder. * @@ -118,6 +117,10 @@ public: * Interpolation kernel type (default spline order = 3) */ typedef CoxDeBoorBSplineKernelFunction<3> KernelType; + typedef BSplineKernelFunction<0> KernelOrder0Type; + typedef BSplineKernelFunction<1> KernelOrder1Type; + typedef BSplineKernelFunction<2> KernelOrder2Type; + typedef BSplineKernelFunction<3> KernelOrder3Type; /** Helper functions */ @@ -213,12 +216,17 @@ private: ArrayType m_SplineOrder; ArrayType m_NumberOfLevels; typename WeightsContainerType::Pointer m_PointWeights; - typename KernelType::Pointer m_Kernel[ImageDimension]; typename PointDataImageType::Pointer m_PhiLattice; typename PointDataImageType::Pointer m_PsiLattice; typename PointDataContainerType::Pointer m_InputPointData; typename PointDataContainerType::Pointer m_OutputPointData; + typename KernelType::Pointer m_Kernel[ImageDimension]; + typename KernelOrder0Type::Pointer m_KernelOrder0; + typename KernelOrder1Type::Pointer m_KernelOrder1; + typename KernelOrder2Type::Pointer m_KernelOrder2; + typename KernelOrder3Type::Pointer m_KernelOrder3; + RealType m_BSplineEpsilon; vnl_matrix<RealType> diff --git a/Utilities/ITK/Code/Review/itkBSplineScatteredDataPointSetToImageFilter.txx b/Utilities/ITK/Code/Review/itkBSplineScatteredDataPointSetToImageFilter.txx index 6dcbb83492..2b726c3cee 100644 --- a/Utilities/ITK/Code/Review/itkBSplineScatteredDataPointSetToImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkBSplineScatteredDataPointSetToImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineScatteredDataPointSetToImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-11-07 19:39:44 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-20 17:34:43 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,6 +52,10 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> this->m_Kernel[i] = KernelType::New(); this->m_Kernel[i]->SetSplineOrder( this->m_SplineOrder[i] ); } + this->m_KernelOrder0 = KernelOrder0Type::New(); + this->m_KernelOrder1 = KernelOrder1Type::New(); + this->m_KernelOrder2 = KernelOrder2Type::New(); + this->m_KernelOrder3 = KernelOrder3Type::New(); this->m_CloseDimension.Fill( 0 ); this->m_DoMultilevel = false; @@ -637,10 +641,37 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> typename RealImageType::IndexType idx = Itw.GetIndex(); for( unsigned int i = 0; i < ImageDimension; i++ ) { - RealType u = static_cast<RealType>( p[i] - + RealType u = static_cast<RealType>( p[i] - static_cast<unsigned>( p[i] ) - idx[i] ) + 0.5*static_cast<RealType>( this->m_SplineOrder[i] - 1 ); - B *= this->m_Kernel[i]->Evaluate( u ); + switch( this->m_SplineOrder[i] ) + { + case 0: + { + B *= this->m_KernelOrder0->Evaluate( u ); + break; + } + case 1: + { + B *= this->m_KernelOrder1->Evaluate( u ); + break; + } + case 2: + { + B *= this->m_KernelOrder2->Evaluate( u ); + break; + } + case 3: + { + B *= this->m_KernelOrder3->Evaluate( u ); + break; + } + default: + { + B *= this->m_Kernel[i]->Evaluate( u ); + break; + } + } } Itw.Set( B ); w2_sum += B*B; @@ -660,8 +691,8 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> RealType wc = this->m_PointWeights->GetElement( It.Index() ); RealType t = Itw.Get(); if(idx[0]>=0 && idx[1]>=0 && static_cast<typename RealImageType::RegionType::SizeValueType>(idx[0])< omega->GetLargestPossibleRegion().GetSize()[0] && static_cast<typename RealImageType::RegionType::SizeValueType>(idx[1])< omega->GetLargestPossibleRegion().GetSize()[1]) - omega->SetPixel( idx, omega->GetPixel( idx ) + wc*t*t ); - + omega->SetPixel( idx, omega->GetPixel( idx ) + wc*t*t ); + PointDataType data = It.Value(); data *= ( t / w2_sum ); @@ -672,9 +703,9 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> { delta->SetPixel( idx, delta->GetPixel( idx ) + data ); delta->GetPixel( idx ) + data; - } } } + } ImageRegionIterator<PointDataImageType> Itl( this->m_PhiLattice, this->m_PhiLattice->GetLargestPossibleRegion() ); @@ -912,8 +943,37 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> for( unsigned int i = 0; i < this->m_SplineOrder[dimension] + 1; i++ ) { idx[dimension] = static_cast<unsigned int>( u ) + i; - RealType B = this->m_Kernel[dimension]->Evaluate( u - idx[dimension] - + 0.5*static_cast<RealType>( this->m_SplineOrder[dimension] - 1 ) ); + RealType v = u - idx[dimension] + + 0.5*static_cast<RealType>( this->m_SplineOrder[dimension] - 1 ); + RealType B; + switch( this->m_SplineOrder[dimension] ) + { + case 0: + { + B = this->m_KernelOrder0->Evaluate( v ); + break; + } + case 1: + { + B = this->m_KernelOrder1->Evaluate( v ); + break; + } + case 2: + { + B = this->m_KernelOrder2->Evaluate( v ); + break; + } + case 3: + { + B = this->m_KernelOrder3->Evaluate( v ); + break; + } + default: + { + B = this->m_Kernel[dimension]->Evaluate( v ); + break; + } + } if( this->m_CloseDimension[dimension] ) { idx[dimension] %= @@ -921,7 +981,7 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> } if(idx[dimension]>=0 && static_cast<typename PointDataImageType::RegionType::SizeValueType>(idx[dimension])<lattice->GetLargestPossibleRegion().GetSize()[dimension]) - data += ( lattice->GetPixel( idx ) * B ); + data += ( lattice->GetPixel( idx ) * B ); } It.Set( data ); } @@ -936,7 +996,7 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> { point[i] -= this->m_Origin[i]; point[i] /= - ( static_cast<RealType>( this->m_Size[i]-1 ) * this->m_Spacing[i] ); + ( static_cast<RealType>( this->m_Size[i] - 1 ) * this->m_Spacing[i] ); } this->Evaluate( point, data ); } @@ -1007,7 +1067,34 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> { RealType u = p[i] - static_cast<RealType>( static_cast<unsigned>( p[i] ) + idx[i] ) + 0.5*static_cast<RealType>( this->m_SplineOrder[i] - 1 ); - B *= this->m_Kernel[i]->Evaluate( u ); + switch( this->m_SplineOrder[i] ) + { + case 0: + { + B *= this->m_KernelOrder0->Evaluate( u ); + break; + } + case 1: + { + B *= this->m_KernelOrder1->Evaluate( u ); + break; + } + case 2: + { + B *= this->m_KernelOrder2->Evaluate( u ); + break; + } + case 3: + { + B *= this->m_KernelOrder3->Evaluate( u ); + break; + } + default: + { + B *= this->m_Kernel[i]->Evaluate( u ); + break; + } + } } for( unsigned int i = 0; i < ImageDimension; i++ ) { diff --git a/Utilities/ITK/Code/Review/itkBasicDilateImageFilter.h b/Utilities/ITK/Code/Review/itkBasicDilateImageFilter.h index 93b1f29d89..e201b33c52 100644 --- a/Utilities/ITK/Code/Review/itkBasicDilateImageFilter.h +++ b/Utilities/ITK/Code/Review/itkBasicDilateImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBasicDilateImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-06 08:53:28 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-28 14:36:36 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -83,6 +83,9 @@ public: itkStaticConstMacro(KernelDimension, unsigned int, TKernel::NeighborhoodDimension); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(InputConvertibleToOutputCheck, @@ -93,8 +96,8 @@ public: (Concept::SameDimension<InputImageDimension, KernelDimension>)); itkConceptMacro(InputGreaterThanComparableCheck, (Concept::GreaterThanComparable<PixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/Review/itkBasicDilateImageFilter.txx b/Utilities/ITK/Code/Review/itkBasicDilateImageFilter.txx index 07625d647e..908ef56d33 100644 --- a/Utilities/ITK/Code/Review/itkBasicDilateImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkBasicDilateImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBasicDilateImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-09-30 16:55:24 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-28 14:36:41 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,11 +42,11 @@ BasicDilateImageFilter<TInputImage, TOutputImage, TKernel> KernelIteratorType kernel_it; - for (i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i) + for( i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i ) { // if structuring element is positive, use the pixel under that element // in the image - if (*kernel_it) + if( *kernel_it > NumericTraits< KernelPixelType >::Zero ) { // note we use GetPixel() on the SmartNeighborhoodIterator to // respect boundary conditions diff --git a/Utilities/ITK/Code/Review/itkBasicErodeImageFilter.h b/Utilities/ITK/Code/Review/itkBasicErodeImageFilter.h index ac050c7ab6..4c47cc93a9 100644 --- a/Utilities/ITK/Code/Review/itkBasicErodeImageFilter.h +++ b/Utilities/ITK/Code/Review/itkBasicErodeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBasicErodeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-09-29 18:36:37 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-28 14:36:43 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,6 +81,9 @@ public: itkStaticConstMacro(KernelDimension, unsigned int, TKernel::NeighborhoodDimension); + /** Type of the pixels in the Kernel. */ + typedef typename TKernel::PixelType KernelPixelType; + #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(InputConvertibleToOutputCheck, @@ -91,8 +94,8 @@ public: (Concept::SameDimension<InputImageDimension, KernelDimension>)); itkConceptMacro(InputLessThanComparableCheck, (Concept::LessThanComparable<PixelType>)); - itkConceptMacro(KernelGreaterThanIntCheck, - (Concept::GreaterThanComparable<typename TKernel::PixelType, int>)); + itkConceptMacro(KernelGreaterThanComparableCheck, + (Concept::GreaterThanComparable<KernelPixelType>)); /** End concept checking */ #endif diff --git a/Utilities/ITK/Code/Review/itkBasicErodeImageFilter.txx b/Utilities/ITK/Code/Review/itkBasicErodeImageFilter.txx index 5d70cc92f9..ecb01c6e4f 100644 --- a/Utilities/ITK/Code/Review/itkBasicErodeImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkBasicErodeImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBasicErodeImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-09-30 16:41:10 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-28 14:36:46 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,17 +42,17 @@ BasicErodeImageFilter<TInputImage, TOutputImage, TKernel> KernelIteratorType kernel_it; - for (i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i) + for( i=0, kernel_it=kernelBegin; kernel_it<kernelEnd; ++kernel_it, ++i ) { // if structuring element is positive, use the pixel under that element // in the image - if (*kernel_it) + if( *kernel_it > NumericTraits< KernelPixelType >::Zero ) { // note we use GetPixel() on the NeighborhoodIterator in order // to respect boundary conditions. temp = nit.GetPixel(i); - if (temp < min) + if( temp < min ) { min = temp; } diff --git a/Utilities/ITK/Code/Review/itkBinaryContourImageFilter.h b/Utilities/ITK/Code/Review/itkBinaryContourImageFilter.h index 765be23377..6420d218f8 100644 --- a/Utilities/ITK/Code/Review/itkBinaryContourImageFilter.h +++ b/Utilities/ITK/Code/Review/itkBinaryContourImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryContourImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-14 22:00:53 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -134,14 +134,14 @@ public: * objects. */ itkSetMacro(BackgroundValue, OutputImagePixelType); - itkGetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); /** * Set/Get the foreground value used to identify the objects in the input and * output images. */ itkSetMacro(ForegroundValue, InputImagePixelType); - itkGetMacro(ForegroundValue, InputImagePixelType); + itkGetConstMacro(ForegroundValue, InputImagePixelType); protected: BinaryContourImageFilter() diff --git a/Utilities/ITK/Code/Review/itkBinaryContourImageFilter.txx b/Utilities/ITK/Code/Review/itkBinaryContourImageFilter.txx index a2eb98452b..40bce64336 100644 --- a/Utilities/ITK/Code/Review/itkBinaryContourImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkBinaryContourImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryContourImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-14 22:00:53 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-05-13 21:52:25 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -76,7 +76,6 @@ BinaryContourImageFilter< TInputImage, TOutputImage> // to get the real number of threads which will be used typename TOutputImage::RegionType splitRegion; // dummy region - just to call the following method nbOfThreads = this->SplitRequestedRegion(0, nbOfThreads, splitRegion); -// std::cout << "nbOfThreads: " << nbOfThreads << std::endl; m_Barrier = Barrier::New(); m_Barrier->Initialize( nbOfThreads ); @@ -150,7 +149,7 @@ BinaryContourImageFilter< TInputImage, TOutputImage> while (! inLineIt.IsAtEndOfLine()) { InputPixelType PVal = inLineIt.Get(); - //std::cout << inLineIt.GetIndex() << std::endl; + if (PVal == m_ForegroundValue) { // We've hit the start of a run @@ -158,7 +157,7 @@ BinaryContourImageFilter< TInputImage, TOutputImage> long length=0; IndexType thisIndex; thisIndex = inLineIt.GetIndex(); - //std::cout << thisIndex << std::endl; + outLineIt.Set( m_BackgroundValue ); ++length; ++inLineIt; @@ -175,7 +174,7 @@ BinaryContourImageFilter< TInputImage, TOutputImage> thisRun.length=length; thisRun.where = thisIndex; fgLine.push_back(thisRun); -// std::cout << "fg " << thisIndex << " " << length << std::endl; + } else { @@ -184,7 +183,7 @@ BinaryContourImageFilter< TInputImage, TOutputImage> long length=0; IndexType thisIndex; thisIndex = inLineIt.GetIndex(); - //std::cout << thisIndex << std::endl; + outLineIt.Set( PVal ); ++length; ++inLineIt; @@ -201,10 +200,10 @@ BinaryContourImageFilter< TInputImage, TOutputImage> thisRun.length=length; thisRun.where = thisIndex; bgLine.push_back(thisRun); -// std::cout << "bg " << thisIndex << " " << length << std::endl; + } } -// std::cout << std::endl; + m_ForegroundLineMap[lineId] = fgLine; m_BackgroundLineMap[lineId] = bgLine; lineId++; @@ -215,9 +214,7 @@ BinaryContourImageFilter< TInputImage, TOutputImage> // wait for the other threads to complete that part this->Wait(); - // now process the map and make appropriate entries in an equivalence - // table - // assert( linecount == m_ForegroundLineMap.size() ); + // now process the map and make appropriate entries in an equivalence table long pixelcount = output->GetRequestedRegion().GetNumberOfPixels(); long xsize = output->GetRequestedRegion().GetSize()[0]; long linecount = pixelcount/xsize; @@ -364,7 +361,7 @@ BinaryContourImageFilter< TInputImage, TOutputImage> { offset = 1; } -// std::cout << "offset: " << offset << std::endl; + typename TOutputImage::Pointer output = this->GetOutput(); @@ -408,7 +405,6 @@ BinaryContourImageFilter< TInputImage, TOutputImage> if ((ss1 >= cStart) && (ee2 <= cLast)) { // case 1 -// std::cout << "case 1" << std::endl; eq = true; oStart = ss1; oLast = ee2; @@ -416,7 +412,6 @@ BinaryContourImageFilter< TInputImage, TOutputImage> else if ((ss1 <= cStart) && (ee2 >= cLast)) { // case 4 -// std::cout << "case 4" << std::endl; eq = true; oStart = cStart; oLast = cLast; @@ -424,7 +419,6 @@ BinaryContourImageFilter< TInputImage, TOutputImage> else if ((ss1 <= cLast) && (ee2 >= cLast)) { // case 2 -// std::cout << "case 2" << std::endl; eq = true; oStart = ss1; oLast = cLast; @@ -432,7 +426,6 @@ BinaryContourImageFilter< TInputImage, TOutputImage> else if ((ss1 <= cStart) && (ee2 >= cStart)) { // case 3 -// std::cout << "case 3" << std::endl; eq = true; oStart = cStart; oLast = ee2; @@ -440,12 +433,10 @@ BinaryContourImageFilter< TInputImage, TOutputImage> if (eq) { -// std::cout << oStart << " " << oLast << std::endl; - assert( oStart <= oLast ); + itkAssertOrThrowMacro( ( oStart <= oLast ), "Start and Last out of order" ); IndexType idx = cIt->where; for( int x=oStart; x<=oLast; x++ ) { -// std::cout << idx << std::endl; idx[0] = x; output->SetPixel( idx, m_ForegroundValue ); } diff --git a/Utilities/ITK/Code/Review/itkBinaryMorphologicalClosingImageFilter.h b/Utilities/ITK/Code/Review/itkBinaryMorphologicalClosingImageFilter.h index 3ae68b90be..83c71ea1bc 100644 --- a/Utilities/ITK/Code/Review/itkBinaryMorphologicalClosingImageFilter.h +++ b/Utilities/ITK/Code/Review/itkBinaryMorphologicalClosingImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMorphologicalClosingImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -79,7 +79,7 @@ public: /** Get the value in the image considered as "foreground". Defaults to * maximum value of InputPixelType. */ - itkGetMacro(ForegroundValue, InputPixelType); + itkGetConstMacro(ForegroundValue, InputPixelType); /** A safe border is added to input image to avoid borders effects diff --git a/Utilities/ITK/Code/Review/itkBinaryMorphologicalOpeningImageFilter.h b/Utilities/ITK/Code/Review/itkBinaryMorphologicalOpeningImageFilter.h index 30eae1afce..4fe14f4bb2 100644 --- a/Utilities/ITK/Code/Review/itkBinaryMorphologicalOpeningImageFilter.h +++ b/Utilities/ITK/Code/Review/itkBinaryMorphologicalOpeningImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMorphologicalOpeningImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -78,13 +78,13 @@ public: /** Get the value in the image considered as "foreground". Defaults to * maximum value of PixelType. */ - itkGetMacro(ForegroundValue, PixelType); + itkGetConstMacro(ForegroundValue, PixelType); /** Set the value in eroded part of the image. Defaults to zero */ itkSetMacro(BackgroundValue, PixelType); /** Set the value in eroded part of the image. Defaults to zero */ - itkGetMacro(BackgroundValue, PixelType); + itkGetConstMacro(BackgroundValue, PixelType); protected: BinaryMorphologicalOpeningImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkBlueColormapFunctor.h b/Utilities/ITK/Code/Review/itkBlueColormapFunctor.h new file mode 100644 index 0000000000..f43f246921 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBlueColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBlueColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:08:09 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBlueColormapFunctor_h +#define __itkBlueColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class BlueColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT BlueColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef BlueColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + BlueColormapFunctor() {}; + ~BlueColormapFunctor() {}; + +private: + BlueColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkBlueColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkBlueColormapFunctor.txx b/Utilities/ITK/Code/Review/itkBlueColormapFunctor.txx new file mode 100644 index 0000000000..4130546e52 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBlueColormapFunctor.txx @@ -0,0 +1,49 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBlueColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBlueColormapFunctor_txx +#define __itkBlueColormapFunctor_txx + +#include "itkBlueColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename BlueColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +BlueColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = 0; + pixel[1] = 0; + pixel[2] = this->RescaleRGBComponentValue( value ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkBruker2DSEQImageIO.cxx b/Utilities/ITK/Code/Review/itkBruker2DSEQImageIO.cxx index 51b58b5952..085fdae1ca 100644 --- a/Utilities/ITK/Code/Review/itkBruker2DSEQImageIO.cxx +++ b/Utilities/ITK/Code/Review/itkBruker2DSEQImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBruker2DSEQImageIO.cxx,v $ Language: C++ - Date: $Date: 2008-06-25 22:54:41 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-16 17:11:53 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -147,8 +147,9 @@ Bruker2DSEQImageIO::SwapBytesIfNecessary( void* buffer, ((double*)buffer, numberOfPixels ); break; default: - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Pixel Type Unknown"); + ExceptionObject exception(__FILE__, __LINE__, + "Component Type Unknown", + ITK_LOCATION); throw exception; } } @@ -197,8 +198,9 @@ Bruker2DSEQImageIO::SwapBytesIfNecessary( void* buffer, ((double *)buffer, numberOfPixels ); break; default: - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Pixel Type Unknown"); + ExceptionObject exception(__FILE__, __LINE__, + "Component Type Unknown", + ITK_LOCATION); throw exception; } } @@ -260,23 +262,25 @@ void Bruker2DSEQImageIO::Read(void* buffer) std::ios::in | std::ios::binary ); if( twodseq_InputStream.fail() ) { - ExceptionObject exception(__FILE__, __LINE__); - std::string errMsg="The 2dseq Data File can not be opened: "; - errMsg += "The following file was attempted:\n "; - errMsg += file2Dseq; - errMsg += '\n'; - exception.SetDescription(errMsg.c_str()); + OStringStream message; + message << "The Brucker2DSEG Data File can not be opened. " + << "The following file was attempted:" << std::endl + << file2Dseq; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } twodseq_InputStream.read(p, this->GetImageSizeInBytes()); if( twodseq_InputStream.fail() ) { - ExceptionObject exception(__FILE__, __LINE__); - std::string errMsg="The 2dseq Data File can not be read: "; - errMsg += "The following file was attempted:\n "; - errMsg += file2Dseq; - errMsg += '\n'; - exception.SetDescription(errMsg.c_str()); + OStringStream message; + message << "The Brucker2DSEG Data File can not be read. " + << "The following file was attempted:" << std::endl + << file2Dseq; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } twodseq_InputStream.close(); @@ -505,8 +509,17 @@ void Bruker2DSEQImageIO::ReadImageInformation() itksys::SystemTools::SplitPath(path.c_str(), pathComponents); if(pathComponents.size() < 3) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Cannot create path for acqp file"); + OStringStream message; + message << "Cannot create path for acqp file: " + << path << std::endl + << "Path Components: "; + for (unsigned int i = 0; i < pathComponents.size(); i++) + { + message << pathComponents[i] << "' "; + } + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } // Go two directories up. @@ -550,8 +563,11 @@ void Bruker2DSEQImageIO::ReadImageInformation() std::ios::in ); if( d3proc_InputStream.fail() ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("d3proc file cannot be read"); + OStringStream message; + message << "d3proc file: " << filed3proc << " cannot be opened."; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } while( !d3proc_InputStream.eof() ) @@ -604,13 +620,17 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!im_sixString) { d3proc_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$IM_SIX"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$IM_SIX" << std::endl + << ". File is " + << filed3proc; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } im_sixString >> imageDim[0]; - //std::cout << "imageDim[0] = " << imageDim[0] << std::endl; } // Get the y size. @@ -623,13 +643,17 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!im_siyString) { d3proc_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$IM_SIY"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$IM_SIY" << std::endl + << ". File is " + << filed3proc; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } im_siyString >> imageDim[1]; - //std::cout << "imageDim[1] = " << imageDim[1] << std::endl; } // Get the z size. @@ -642,13 +666,17 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!im_sizString) { d3proc_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$IM_SIZ"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$IM_SIZ" << std::endl + << ". File is " + << filed3proc; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } im_sizString >> imageDim[2]; - //std::cout << "imageDim[2] = " << imageDim[2] << std::endl; } } @@ -659,8 +687,11 @@ void Bruker2DSEQImageIO::ReadImageInformation() std::ios::in ); if( reco_InputStream.fail()) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("reco file cannot be read"); + OStringStream message; + message << "reco file: " << filereco << " cannot be opened"; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } while( !reco_InputStream.eof() ) @@ -698,9 +729,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() else { reco_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid reco file: Couldn't locate proper " - "fov parameters"); + OStringStream message; + message << "Invalid reco file: Couldn't locate proper " + << "fov parameters" << std::endl + << "Reco file is " + << filereco; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } } @@ -721,9 +757,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if( tempIndex == std::string::npos ) { reco_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid reco file: Couldn't locate proper " - "dimension parameters"); + OStringStream message; + message << "Invalid reco file: Couldn't locate proper " + << "dimension parameters" << std::endl + << "Reco file is " + << filereco; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } } @@ -786,9 +827,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() else { reco_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid reco file: Couldn't locate " - "proper wordtype parameter"); + OStringStream message; + message << "Invalid reco file: Couldn't locate proper " + << "wordtype parameter" << std::endl + << "Reco file is " + << filereco; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } } @@ -807,9 +853,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!recoTransposeString) { reco_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$RECO_transposition"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$RECO_transposition" << std::endl + << "Reco file is " + << filereco; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } recoTransposeString >> numRecoTranspose; @@ -870,9 +921,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() else { reco_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid reco file: Couldn't locate proper " - "datatype parameter"); + OStringStream message; + message << "Invalid reco file: Couldn't locate proper" + << "datatype parameter" << std::endl + << "Reco file is " + << filereco; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } } @@ -902,9 +958,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() else { reco_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid reco file: Couldn't locate proper " - "byte order parameter"); + OStringStream message; + message << "Invalid reco file: Couldn't locate proper" + << "byte order parameter" << std::endl + << "Reco file is " + << filereco; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } } @@ -914,23 +975,38 @@ void Bruker2DSEQImageIO::ReadImageInformation() if( !numDimensions ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid reco file: Couldn't locate " - "'##$RECO_fov=(' tag"); + OStringStream message; + message << "Invalid reco file: Couldn't locate " + << "'##$RECO_fov=(' tag" << std::endl + << "Reco file is " + << filereco; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if( !byteOrder ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid reco file: Couldn't locate " - "'##$RECO_byte_order=' tag"); + OStringStream message; + message << "Invalid reco file: Couldn't locate " + << "'##$RECO_byte_order=' tag" << std::endl + << "Reco file is " + << filereco; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if( numRecoTranspose < 0 ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid reco file: Couldn't locate " - "'##$RECO_transposition=(' tag"); + OStringStream message; + message << "Invalid reco file: Couldn't locate " + << "'##$RECO_transposition=(' tag" << std::endl + << "Reco file is " + << filereco; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } @@ -942,8 +1018,13 @@ void Bruker2DSEQImageIO::ReadImageInformation() //std::cout << fileacqp.c_str() << std::endl; if( acqp_InputStream.fail() ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("acqp file cannot be read"); + OStringStream message; + message << "acqp file cannot be opened. " + << "File is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } while( !acqp_InputStream.eof() ) @@ -965,9 +1046,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!acqDimString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$ACQ_dim"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$ACQ_dim. " + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } acqDimString >> acq_dim; @@ -986,9 +1072,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!niString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$NI"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$NI" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } niString >> ni; @@ -1006,9 +1097,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!nrString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$NR"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$NR" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } nrString >> nr; @@ -1026,9 +1122,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!dimString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$NECHOES"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$NECHOES" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } dimString >> numEchoImages; @@ -1046,9 +1147,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!sliceThickString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$ACQ_slice_thick"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$ACQ_slice_thick" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } sliceThickString >> sliceThick; @@ -1067,9 +1173,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!sliceSepString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$ACQ_slice_sepn"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$ACQ_slice_sepn" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } sliceSepString >> numSeperation; @@ -1112,9 +1223,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!echoTimeString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$ACQ_echo_time"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$ACQ_echo_time" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } echoTimeString >> numEchoes; @@ -1137,8 +1253,13 @@ void Bruker2DSEQImageIO::ReadImageInformation() else { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not retrieve ##$ACQ_echo_times"); + OStringStream message; + message << "Could not retrieve ##$ACQ_echo_times" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } } @@ -1153,9 +1274,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!reptitionTimeString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$ACQ_repetition_time"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$ACQ_repetition_time" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } reptitionTimeString >> numRepetitions; @@ -1178,8 +1304,13 @@ void Bruker2DSEQImageIO::ReadImageInformation() else { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not retrieve ##$ACQ_repetition_time"); + OStringStream message; + message << "Could not retrieve ##$ACQ_repetition_time" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } } @@ -1194,9 +1325,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!inversionTimeString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$ACQ_inversion_time"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$ACQ_inversion_time" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } inversionTimeString >> numInversionTimes; @@ -1219,8 +1355,13 @@ void Bruker2DSEQImageIO::ReadImageInformation() else { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not retrieve ##$ACQ_inversion_time"); + OStringStream message; + message << "Could not retrieve ##$ACQ_inversion_time" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } } @@ -1245,9 +1386,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if (!gradMatrixString) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not create std::istringstream for " - "##$ACQ_grad_matrix"); + OStringStream message; + message << "Could not create std::istringstream for " + << "##$ACQ_grad_matrix" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } gradMatrixString >> numMatrix >> dim1 >> dim2; @@ -1261,9 +1407,14 @@ void Bruker2DSEQImageIO::ReadImageInformation() if( acq_dim < 0 ) { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid acqp file: Couldn't locate " - "'##$ACQ_dim=' tag"); + OStringStream message; + message << "Invalid acqp file: Couldn't locate " + << "'##$ACQ_dim=' tag" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } int i=0; @@ -1438,8 +1589,13 @@ void Bruker2DSEQImageIO::ReadImageInformation() else { acqp_InputStream.close(); - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Could not retrieve ##$ACQ_grad_matrix"); + OStringStream message; + message << "Could not retrieve ##$ACQ_grad_matrix" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } } @@ -1448,63 +1604,105 @@ void Bruker2DSEQImageIO::ReadImageInformation() if( !echoTime ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid acqp file: Couldn't locate " - "'##$ACQ_echo_time=( ' tag"); + OStringStream message; + message << "Invalid acqp file: Couldn't locate " + << "'##$ACQ_echo_time=( ' tag" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if( !sliceThickness ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid acqp file: Couldn't locate " - "'##$ACQ_slice_thick=' tag"); + OStringStream message; + message << "Invalid acqp file: Couldn't locate " + << "'##$ACQ_slice_thick=' tag" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if( !sliceSeperation ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid acqp file: Couldn't locate " - "'##$ACQ_slice_sepn=(' tag"); + OStringStream message; + message << "Invalid acqp file: Couldn't locate " + << "'##$ACQ_slice_sepn=(' tag" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if( !nr ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid acqp file: Couldn't locate '##$NR=' tag"); + OStringStream message; + message << "Invalid acqp file: Couldn't locate " + << "'##$NR=' tag" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if( !ni ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid acqp file: Couldn't locate '##$NI=' tag"); + OStringStream message; + message << "Invalid acqp file: Couldn't locate " + << "'##$NI=' tag" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if( !echoTime ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid acqp file: Couldn't locate " - "'##$ACQ_echo_time=( ' tag"); + OStringStream message; + message << "Invalid acqp file: Couldn't locate " + << "'##$ACQ_echo_time=( ' tag" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if( !repetitionTime ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid acqp file: Couldn't locate " - "'##$ACQ_repetition_time=( ' tag"); + OStringStream message; + message << "Invalid acqp file: Couldn't locate " + << "'##$ACQ_repetition_time=( ' tag" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if( !inversionTime ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Invalid acqp file: Couldn't locate " - "'##$ACQ_inversion_time=( ' tag"); + OStringStream message; + message << "Invalid acqp file: Couldn't locate " + << "'##$ACQ_inversion_time=( ' tag" << std::endl + << "The file is " + << fileacqp; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } diff --git a/Utilities/ITK/Code/Review/itkColormapFunctor.h b/Utilities/ITK/Code/Review/itkColormapFunctor.h new file mode 100644 index 0000000000..84359bc4f7 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkColormapFunctor.h @@ -0,0 +1,153 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-21 20:16:56 $ + Version: $Revision: 1.6 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkColormapFunctor_h +#define __itkColormapFunctor_h + +#include "itkLightObject.h" +#include "itkNumericTraits.h" +#include "itkRGBPixel.h" + +namespace itk { + +namespace Functor { + +/** + * \class ColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT ColormapFunctor : public Object +{ +public: + + typedef ColormapFunctor Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(ColormapFunctor, Object); + + typedef TRGBPixel RGBPixelType; + typedef typename TRGBPixel::ComponentType RGBComponentType; + typedef TScalar ScalarType; + typedef typename NumericTraits<ScalarType>::RealType RealType; + + itkSetMacro( MinimumRGBComponentValue, RGBComponentType ); + itkGetConstMacro( MinimumRGBComponentValue, RGBComponentType ); + + itkSetMacro( MaximumRGBComponentValue, RGBComponentType ); + itkGetConstMacro( MaximumRGBComponentValue, RGBComponentType ); + + itkSetMacro( MinimumInputValue, ScalarType ); + itkGetConstMacro( MinimumInputValue, ScalarType ); + + itkSetMacro( MaximumInputValue, ScalarType ); + itkGetConstMacro( MaximumInputValue, ScalarType ); + + virtual bool operator!=( const ColormapFunctor & ) const + { + return false; + } + virtual bool operator==( const ColormapFunctor & other ) const + { + return !(*this != other); + } + + virtual RGBPixelType operator()( const ScalarType & ) const = 0; + +protected: + ColormapFunctor() + { + this->m_MinimumInputValue = NumericTraits<TScalar>::min(); + this->m_MaximumInputValue = NumericTraits<TScalar>::max(); + this->m_MinimumRGBComponentValue = NumericTraits<RGBComponentType>::min(); + this->m_MaximumRGBComponentValue = NumericTraits<RGBComponentType>::max(); + } + + ~ColormapFunctor() {}; + + + /** + * Map [min, max] input values to [0, 1]. + */ + RealType RescaleInputValue( ScalarType v ) const + { + RealType d = static_cast<RealType>( this->m_MaximumInputValue - this->m_MinimumInputValue ); + RealType value = ( static_cast<RealType>( v ) + - static_cast<RealType>( this->m_MinimumInputValue ) ) / d; + value = vnl_math_max( 0.0, value ); + value = vnl_math_min( 1.0, value ); + return value; + } + + /** + * Map [0, 1] value to [min, max] rgb component values. + */ + RGBComponentType RescaleRGBComponentValue( RealType v ) const + { + RealType d = static_cast<RealType>( m_MaximumRGBComponentValue - m_MinimumRGBComponentValue ); + const RGBComponentType rescaled = + static_cast<RGBComponentType>( d * v ) + this->m_MinimumRGBComponentValue; + return rescaled; + } + + void PrintSelf(std::ostream& os, Indent indent) const + { + Superclass::PrintSelf(os, indent); + + os << indent << "Minimum RGB Component Value: " + << static_cast<typename NumericTraits<RGBComponentType>::PrintType>( + this->GetMinimumRGBComponentValue()) << std::endl; + os << indent << "Maximum RGB Component Value: " + << static_cast<typename NumericTraits<RGBComponentType>::PrintType>( + this->GetMaximumRGBComponentValue()) << std::endl; + os << indent << "Minimum Input Value: " + << static_cast<typename NumericTraits<ScalarType>::PrintType>( + this->GetMinimumInputValue()) << std::endl; + os << indent << "Maximum Input Value: " + << static_cast<typename NumericTraits<ScalarType>::PrintType>( + this->GetMaximumInputValue()) << std::endl; + } + +private: + ColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + ScalarType m_MinimumInputValue; + ScalarType m_MaximumInputValue; + + RGBComponentType m_MinimumRGBComponentValue; + RGBComponentType m_MaximumRGBComponentValue; + +}; + +} // end namespace functor + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkComplexBSplineInterpolateImageFunction.h b/Utilities/ITK/Code/Review/itkComplexBSplineInterpolateImageFunction.h new file mode 100644 index 0000000000..69f020c81f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkComplexBSplineInterpolateImageFunction.h @@ -0,0 +1,152 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkComplexBSplineInterpolateImageFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-15 20:10:02 $ + Version: $Revision: 1.2 $ + + Copyright ( c ) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkComplexBSplineInterpolateImageFunction_h +#define __itkComplexBSplineInterpolateImageFunction_h + +#include "itkInterpolateImageFunction.h" +#include "itkBSplineInterpolateImageFunction.h" +#include "itkComplexToRealImageFilter.h" +#include "itkComplexToImaginaryImageFilter.h" + +namespace itk { +/** + * \class ComplexBSplineInterpolateImageFunction. + * \brief Complex wrapper around BSplineInterpolateImageFunction. + * + * A complex wrapper class that splits complex input image in two real-type + * subimages containing real and imaginary parts, that are interpolated using + * the standard itkBSplineInterpolateImageFunction. The same requirements apply + * for this class: Set spline order before setting the input image! + * Derivative support is currently not implemented + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/585 + * + * \ingroup ImageInterpolators + */ + template< class TImageType, class TCoordRep = double, class TCoefficientType = double > + class ITK_EXPORT ComplexBSplineInterpolateImageFunction : + public InterpolateImageFunction< TImageType, TCoordRep > +{ +public: + /** Standard class typedef. */ + typedef ComplexBSplineInterpolateImageFunction Self; + /** Standard class typedef. */ + typedef InterpolateImageFunction< TImageType, TCoordRep > Superclass; + /** Standard class typedef. */ + typedef SmartPointer< Self > Pointer; + /** Standard class typedef. */ + typedef SmartPointer< const Self > ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro( ComplexBSplineInterpolateImageFunction, InterpolateImageFunction ); + + + /** New macro for creation of through a Smart Pointer */ + itkNewMacro( Self ); + + /** Dimension underlying input image. */ + itkStaticConstMacro( ImageDimension, unsigned int,Superclass::ImageDimension ); + + /** OutputType typedef support. */ + typedef typename Superclass::OutputType OutputType; + + /** InputImageType typedef support. */ + typedef typename Superclass::InputImageType InputImageType; + + /** Index typedef support. */ + typedef typename Superclass::IndexType IndexType; + + /** ContinuousIndex typedef support. */ + typedef typename Superclass::ContinuousIndexType ContinuousIndexType; + + /** PointType typedef support */ + typedef typename Superclass::PointType PointType; + + /** Internal Real and imaginary image type */ + typedef Image< double, itkGetStaticConstMacro( ImageDimension ) > InternalImageType; + + /** Complex to Real filter type */ + typedef ComplexToRealImageFilter< InputImageType, InternalImageType > RealFilterType; + typedef ComplexToImaginaryImageFilter< InputImageType, InternalImageType > ImaginaryFilterType; + + /** Underlying real BSpline interpolator */ + typedef BSplineInterpolateImageFunction< InternalImageType, TCoordRep, TCoefficientType > InterpolatorType; + + + + /** Evaluate the function at a ContinuousIndex position. + * + * Returns the B-Spline interpolated image intensity at a + * specified point position. No bounds checking is done. + * The point is assumed to lie within the image buffer. + * + * ImageFunction::IsInsideBuffer() can be used to check bounds before + * calling the method. */ + virtual OutputType EvaluateAtContinuousIndex( const ContinuousIndexType & index ) const; + + /** Derivative typedef support */ +/* typedef CovariantVector< OutputType, itkGetStaticConstMacro( ImageDimension ) > CovariantVectorType; + + CovariantVectorType EvaluateDerivative( const PointType & point ) const + { + ContinuousIndexType index; + this->GetInputImage()->TransformPhysicalPointToContinuousIndex( point, index ); + return ( this->EvaluateDerivativeAtContinuousIndex( index ) ); + } + + CovariantVectorType EvaluateDerivativeAtContinuousIndex( const ContinuousIndexType & x ) const; +*/ + + /** Get/Sets the Spline Order, supports 0th - 5th order splines. The default + * is a 3rd order spline. */ + void SetSplineOrder( unsigned int SplineOrder ); + itkGetConstMacro( SplineOrder, int ); + + /** Set the input image. This must be set by the user, after setting the spline order! */ + virtual void SetInputImage(const TImageType * inputData); + + +protected: + ComplexBSplineInterpolateImageFunction(); + virtual ~ComplexBSplineInterpolateImageFunction() {}; + void operator=( const Self& ); //purposely not implemented + void PrintSelf(std::ostream& os, Indent indent) const; + + +private: + ComplexBSplineInterpolateImageFunction( const Self& ); //purposely not implemented + + + unsigned int m_SplineOrder; + typename InterpolatorType::Pointer m_RealInterpolator; + typename InterpolatorType::Pointer m_ImaginaryInterpolator; + typename RealFilterType::Pointer m_RealFilter; + typename ImaginaryFilterType::Pointer m_ImaginaryFilter; + +}; // class + + +} // namespace + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkComplexBSplineInterpolateImageFunction.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkComplexBSplineInterpolateImageFunction.txx b/Utilities/ITK/Code/Review/itkComplexBSplineInterpolateImageFunction.txx new file mode 100644 index 0000000000..b651232fc6 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkComplexBSplineInterpolateImageFunction.txx @@ -0,0 +1,104 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkComplexBSplineInterpolateImageFunction.txx,v $ + Language: C++ + Date: $Date: 2009-05-01 18:33:35 $ + Version: $Revision: 1.4 $ + + Copyright ( c ) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkComplexBSplineInterpolateImageFunction_txx +#define __itkComplexBSplineInterpolateImageFunction_txx + +#include "itkComplexBSplineInterpolateImageFunction.h" + +namespace itk +{ + +/** + * Constructor + */ +template <class TImageType, class TCoordRep, class TCoefficientType> +ComplexBSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> +::ComplexBSplineInterpolateImageFunction() +{ + m_RealInterpolator = InterpolatorType::New(); + m_ImaginaryInterpolator = InterpolatorType::New(); + + m_RealFilter = RealFilterType::New(); + m_ImaginaryFilter = ImaginaryFilterType::New(); + + this->SetSplineOrder( 3 ); +} + + +/** + * Standard "PrintSelf" method + */ +template <class TImageType, class TCoordRep, class TCoefficientType> +void ComplexBSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> +::PrintSelf( std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf( os, indent ); + os << indent << "Spline Order: " << m_SplineOrder << std::endl; + os << indent << "Real Interpolator: " << m_RealInterpolator << std::endl; + os << indent << "Imaginary Interpolator: " << m_ImaginaryInterpolator << std::endl; + os << indent << "Complex to Real Filter: " << m_RealFilter << std::endl; + os << indent << "Complex to Imaginary Filter: " << m_ImaginaryFilter << std::endl; +} + + +template <class TImageType, class TCoordRep, class TCoefficientType> +void ComplexBSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> +::SetInputImage(const TImageType * inputData) +{ + if ( inputData ) + { + m_RealFilter->SetInput( inputData ); + m_ImaginaryFilter->SetInput( inputData ); + + m_RealInterpolator->SetInputImage( m_RealFilter->GetOutput() ); + m_ImaginaryInterpolator->SetInputImage( m_ImaginaryFilter->GetOutput() ); + + Superclass::SetInputImage( inputData ); + } +} + + +template <class TImageType, class TCoordRep, class TCoefficientType> +void ComplexBSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> +::SetSplineOrder(unsigned int SplineOrder) +{ + m_SplineOrder = SplineOrder; + m_RealInterpolator->SetSplineOrder( SplineOrder ); + m_ImaginaryInterpolator->SetSplineOrder( SplineOrder ); +} + + +template <class TImageType, class TCoordRep, class TCoefficientType> +typename ComplexBSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType>::OutputType ComplexBSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType> +::EvaluateAtContinuousIndex( const ContinuousIndexType & x ) const +{ + typename InterpolatorType::OutputType realPart = + m_RealInterpolator->EvaluateAtContinuousIndex( x ); + typename InterpolatorType::OutputType imagPart = + m_ImaginaryInterpolator->EvaluateAtContinuousIndex( x ); + typedef typename ComplexBSplineInterpolateImageFunction<TImageType,TCoordRep,TCoefficientType>::OutputType + ReturnType; + + return ReturnType( realPart, imagPart ); +} + + +} // namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkConformalFlatteningMeshFilter.txx b/Utilities/ITK/Code/Review/itkConformalFlatteningMeshFilter.txx index 648ba9ff21..475f04e163 100644 --- a/Utilities/ITK/Code/Review/itkConformalFlatteningMeshFilter.txx +++ b/Utilities/ITK/Code/Review/itkConformalFlatteningMeshFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConformalFlatteningMeshFilter.txx,v $ Language: C++ - Date: $Date: 2008-09-29 18:36:37 $ - Version: $Revision: 1.27 $ + Date: $Date: 2009-04-06 00:19:17 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -540,7 +540,7 @@ ConformalFlatteningMeshFilter< TInputMesh, TOutputMesh > { uiMidPointIdx = numberOfPoints/2; } - this->m_MapScale = 1.0/sqrt(v_r2[uiMidPointIdx]); + this->m_MapScale = 1.0/vcl_sqrt(v_r2[uiMidPointIdx]); } i = 0; diff --git a/Utilities/ITK/Code/Review/itkConstrainedRegionBasedLevelSetFunctionSharedData.h b/Utilities/ITK/Code/Review/itkConstrainedRegionBasedLevelSetFunctionSharedData.h new file mode 100644 index 0000000000..7100bb436a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkConstrainedRegionBasedLevelSetFunctionSharedData.h @@ -0,0 +1,190 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkConstrainedRegionBasedLevelSetFunctionSharedData.h,v $ + Language: C++ + Date: $Date: 2009-05-14 21:46:47 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkConstrainedRegionBasedLevelSetFunctionSharedData_h +#define __itkConstrainedRegionBasedLevelSetFunctionSharedData_h + +#include "itkRegionBasedLevelSetFunctionSharedData.h" + +namespace itk +{ + +/** \class ConstrainedRegionBasedLevelSetFunctionSharedData + * + * \brief Helper class used to share data in the ScalarChanAndVeseLevelSetFunction. + * + * This class holds cache data used during the computation of the LevelSet updates. + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template < class TInputImage, class TFeatureImage, class TSingleData > +class ConstrainedRegionBasedLevelSetFunctionSharedData : + public RegionBasedLevelSetFunctionSharedData< TInputImage, TFeatureImage, TSingleData > +{ +public: + + typedef ConstrainedRegionBasedLevelSetFunctionSharedData Self; + typedef RegionBasedLevelSetFunctionSharedData< TInputImage, TFeatureImage, TSingleData > + Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + itkStaticConstMacro( ImageDimension, unsigned int, TFeatureImage::ImageDimension ); + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + itkTypeMacro(ConstrainedRegionBasedLevelSetFunctionSharedData, RegionBasedLevelSetFunctionSharedData); + + typedef TInputImage InputImageType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputImageConstPointer InputImageConstPointer; + typedef typename Superclass::InputPixelType InputPixelType; + typedef typename Superclass::InputRegionType InputRegionType; + typedef typename Superclass::InputSizeType InputSizeType; + typedef typename Superclass::InputSizeValueType InputSizeValueType; + typedef typename Superclass::InputSpacingType InputSpacingType; + typedef typename Superclass::InputIndexType InputIndexType; + typedef typename Superclass::InputIndexValueType InputIndexValueType; + typedef typename Superclass::InputPointType InputPointType; + + typedef TFeatureImage FeatureImageType; + typedef typename Superclass::FeatureImagePointer FeatureImagePointer; + typedef typename Superclass::FeatureImageConstPointer FeatureImageConstPointer; + typedef typename Superclass::FeaturePixelType FeaturePixelType; + typedef typename Superclass::FeatureRegionType FeatureRegionType; + typedef typename Superclass::FeatureSizeType FeatureSizeType; + typedef typename Superclass::FeatureSizeValueType FeatureSizeValueType; + typedef typename Superclass::FeatureSpacingType FeatureSpacingType; + typedef typename Superclass::FeatureIndexType FeatureIndexType; + typedef typename Superclass::FeaturePointType FeaturePointType; + + typedef typename Superclass::ListPixelType ListPixelType; + typedef typename Superclass::ListImageType ListImageType; + typedef typename Superclass::ListImagePointer ListImagePointer; + typedef typename Superclass::ListImageConstPointer ListImageConstPointer; + typedef typename Superclass::ListRegionType ListRegionType; + typedef typename Superclass::ListSizeType ListSizeType; + typedef typename Superclass::ListSizeValueType ListSizeValueType; + typedef typename Superclass::ListSpacingType ListSpacingType; + typedef typename Superclass::ListIndexType ListIndexType; + typedef typename Superclass::ListIndexValueType ListIndexValueType; + typedef typename Superclass::ListPointType ListPointType; + typedef typename Superclass::ListIteratorType ListIteratorType; + + typedef typename Superclass::CentroidVectorType CentroidVectorType; + typedef typename Superclass::SampleType SampleType; + typedef typename Superclass::TreeGeneratorType TreeGeneratorType; + typedef typename Superclass::TreePointer TreePointer; + typedef typename Superclass::TreeType TreeType; + typedef typename Superclass::KdTreePointer KdTreePointer; + + typedef TSingleData LevelSetDataType; + typedef typename Superclass::LevelSetDataPointer LevelSetDataPointer; + typedef typename Superclass::LevelSetDataPointerVector LevelSetDataPointerVector; + typedef typename Superclass::LevelSetDataPointerVectorIterator LevelSetDataPointerVectorIterator; + + void PopulateListImage() + { + ListSpacingType spacing = this->m_NearestNeighborListImage->GetSpacing(); + + ListRegionType region = this->m_NearestNeighborListImage->GetLargestPossibleRegion(); + + ListIteratorType lIt( this->m_NearestNeighborListImage, region ); + + if ( this->m_KdTree.IsNotNull() ) + { + for(lIt.GoToBegin(); !lIt.IsAtEnd(); ++lIt ) + { + ListIndexType ind = lIt.GetIndex(); + + float queryPoint[ImageDimension]; + for( unsigned int i = 0; i < ImageDimension; i++ ) + { + queryPoint[i] = ind[i]*spacing[i]; + } + + typename TreeType::InstanceIdentifierVectorType neighbors; + this->m_KdTree->Search( queryPoint, this->m_NumberOfNeighbors, neighbors ); + + ListPixelType L; + for( unsigned int i = 0; i < this->m_NumberOfNeighbors; i++ ) + { + if( this->m_LevelSetDataPointerVector[i]->VerifyInsideRegion( ind ) ) + { + L.push_back( neighbors[i] ); + } + } + lIt.Set( L ); + } + } + else + { + for(lIt.GoToBegin(); !lIt.IsAtEnd(); ++lIt ) + { + ListIndexType ind = lIt.GetIndex(); + ListPixelType L; + for( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + { + if( this->m_LevelSetDataPointerVector[i]->VerifyInsideRegion( ind ) ) + { + L.push_back( i ); + } + } + lIt.Set( L ); + } + } + } + +protected: + ConstrainedRegionBasedLevelSetFunctionSharedData() : Superclass( ){} + ~ConstrainedRegionBasedLevelSetFunctionSharedData(){} + +private: + ConstrainedRegionBasedLevelSetFunctionSharedData(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} //end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkContourExtractor2DImageFilter.txx b/Utilities/ITK/Code/Review/itkContourExtractor2DImageFilter.txx index cd2b845cbf..58de23133f 100755 --- a/Utilities/ITK/Code/Review/itkContourExtractor2DImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkContourExtractor2DImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkContourExtractor2DImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-02-07 15:07:57 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-05-13 22:11:57 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,6 @@ #include "itkProgressReporter.h" #include "itkConstShapedNeighborhoodIterator.h" #include "vcl_cmath.h" -#include "vcl_cassert.h" #include "itkContourExtractor2DImageFilter.h" namespace itk @@ -258,10 +257,11 @@ ContourExtractor2DImageFilter<TInputImage> // Offset. value must have exactly one component 1 and the other component 0. // Also this assumes that fromValue and toValue are different. Otherwise we // can't interpolate anything! - assert(fromValue != toValue); + itkAssertOrThrowMacro( (fromValue != toValue), "source and destination are the same" ); - assert( (toOffset[0] == 0 && toOffset[1] == 1) || - (toOffset[0] == 1 && toOffset[1] == 0) ); + itkAssertOrThrowMacro( + ( (toOffset[0] == 0 && toOffset[1] == 1) || (toOffset[0] == 1 && toOffset[1] == 0) ), + "toOffset has unexpected values"); double x = (m_ContourValue - static_cast<InputRealType>(fromValue)) / (toValue - static_cast<InputRealType>(fromValue)); @@ -296,9 +296,9 @@ ContourExtractor2DImageFilter<TInputImage> // We need to connect these two contours. The act of connecting them will // add the needed arc. ContourRef tail = newTail->second; - assert(tail->front() == to); + itkAssertOrThrowMacro( (tail->front() == to), "End doesn't match Beginning" ); ContourRef head = newHead->second; - assert(head->back() == from); + itkAssertOrThrowMacro( (head->back() == from), "Beginning doesn't match End"); if (head == tail) { // We've closed a contour. Add the end point, and remove from the maps @@ -384,7 +384,7 @@ ContourExtractor2DImageFilter<TInputImage> { // Found a single contour to which the new arc should be prepended. ContourRef tail = newTail->second; - assert(tail->front() == to); + itkAssertOrThrowMacro( (tail->front() == to), "End doesn't match Beginning" ); tail->push_front(from); // erase the old start of this contour m_ContourStarts.erase(newTail); @@ -395,7 +395,7 @@ ContourExtractor2DImageFilter<TInputImage> { // Found a single contour to which the new arc should be appended. ContourRef head = newHead->second; - assert(head->back() == from); + itkAssertOrThrowMacro( (head->back() == from), "Beginning doesn't match End"); head->push_back(to); // erase the old end of this contour m_ContourEnds.erase(newHead); diff --git a/Utilities/ITK/Code/Review/itkCoolColormapFunctor.h b/Utilities/ITK/Code/Review/itkCoolColormapFunctor.h new file mode 100644 index 0000000000..42cdf8f305 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkCoolColormapFunctor.h @@ -0,0 +1,78 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCoolColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:08:09 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkCoolColormapFunctor_h +#define __itkCoolColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class CoolColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT CoolColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef CoolColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + CoolColormapFunctor() {}; + ~CoolColormapFunctor() {}; + +private: + CoolColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkCoolColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkCoolColormapFunctor.txx b/Utilities/ITK/Code/Review/itkCoolColormapFunctor.txx new file mode 100644 index 0000000000..5c55c52506 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkCoolColormapFunctor.txx @@ -0,0 +1,56 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCoolColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkCoolColormapFunctor_txx +#define __itkCoolColormapFunctor_txx + +#include "itkCoolColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename CoolColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +CoolColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color mapping. + RealType red = value; + + RealType green = 1.0 - value; + + RealType blue = 1.0; + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkCopperColormapFunctor.h b/Utilities/ITK/Code/Review/itkCopperColormapFunctor.h new file mode 100644 index 0000000000..63b460499f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkCopperColormapFunctor.h @@ -0,0 +1,78 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCopperColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:08:09 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkCopperColormapFunctor_h +#define __itkCopperColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class CopperColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT CopperColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef CopperColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + CopperColormapFunctor() {}; + ~CopperColormapFunctor() {}; + +private: + CopperColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkCopperColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkCopperColormapFunctor.txx b/Utilities/ITK/Code/Review/itkCopperColormapFunctor.txx new file mode 100644 index 0000000000..1719f67aa5 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkCopperColormapFunctor.txx @@ -0,0 +1,57 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCopperColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkCopperColormapFunctor_txx +#define __itkCopperColormapFunctor_txx + +#include "itkCopperColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename CopperColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +CopperColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color map. + RealType red = 1.2 * value; + red = vnl_math_min( 1.0, red ); + + RealType green = 0.8 * value; + + RealType blue = 0.5 * value; + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkCoxDeBoorBSplineKernelFunction.h b/Utilities/ITK/Code/Review/itkCoxDeBoorBSplineKernelFunction.h index 54b602896b..ae8b342dda 100755 --- a/Utilities/ITK/Code/Review/itkCoxDeBoorBSplineKernelFunction.h +++ b/Utilities/ITK/Code/Review/itkCoxDeBoorBSplineKernelFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCoxDeBoorBSplineKernelFunction.h,v $ Language: C++ - Date: $Date: 2008-08-04 12:54:50 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -77,7 +77,7 @@ public: /** Get/Sets the Spline Order */ void SetSplineOrder( unsigned int ); - itkGetMacro( SplineOrder, unsigned int ); + itkGetConstMacro( SplineOrder, unsigned int ); /** Evaluate the function. */ inline RealType Evaluate( const RealType & u ) const diff --git a/Utilities/ITK/Code/Review/itkCoxDeBoorBSplineKernelFunction.txx b/Utilities/ITK/Code/Review/itkCoxDeBoorBSplineKernelFunction.txx index a16c108603..60c0f89fa2 100755 --- a/Utilities/ITK/Code/Review/itkCoxDeBoorBSplineKernelFunction.txx +++ b/Utilities/ITK/Code/Review/itkCoxDeBoorBSplineKernelFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCoxDeBoorBSplineKernelFunction.txx,v $ Language: C++ - Date: $Date: 2008-09-29 18:36:38 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-05 03:23:29 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -162,10 +162,12 @@ CoxDeBoorBSplineKernelFunction<VSplineOrder> Superclass::PrintSelf( os, indent ); os << indent << "Spline Order: " << this->m_SplineOrder << std::endl; os << indent << "Piecewise Polynomial Pieces: " << std::endl; + + RealType a = 0.0; + RealType b = 0.0; + for ( unsigned int i = 0; i < this->m_BSplineShapeFunctions.rows(); i++ ) { - RealType a = 0.0; - RealType b = 0.0; os << indent << indent; PolynomialType( this->m_BSplineShapeFunctions.get_row( i ) ).print( os ); diff --git a/Utilities/ITK/Code/Review/itkCrossHelper.h b/Utilities/ITK/Code/Review/itkCrossHelper.h index ac47323a6c..a32989ab46 100644 --- a/Utilities/ITK/Code/Review/itkCrossHelper.h +++ b/Utilities/ITK/Code/Review/itkCrossHelper.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCrossHelper.h,v $ Language: C++ - Date: $Date: 2008-10-06 00:02:03 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-27 14:51:44 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,6 +17,8 @@ #ifndef __itkCrossHelper_h #define __itkCrossHelper_h +#include "itkNumericTraits.h" + namespace itk { /** \class Cross @@ -45,18 +47,22 @@ public: VectorType operator ( ) ( const VectorType& iU, const VectorType& iV ) const { - assert ( Dimension > 2 ); - VectorType oCross; - // *** Arnaud : InputVDimension == 3 - oCross[0] = iU[1] * iV[2] - iV[1] * iU[2]; - oCross[1] = iV[0] * iU[2] - iU[0] * iV[2]; - oCross[2] = iU[0] * iV[1] - iV[0] * iU[1]; + if( Dimension > 2 ) + { + oCross[0] = iU[1] * iV[2] - iV[1] * iU[2]; + oCross[1] = iV[0] * iU[2] - iU[0] * iV[2]; + oCross[2] = iU[0] * iV[1] - iV[0] * iU[1]; - for( unsigned int dim = 3; dim < Dimension; dim++ ) + for( unsigned int dim = 3; dim < Dimension; dim++ ) + { + oCross[dim] = 0.0; + } + } + else { - oCross[dim] = 0.0; + oCross.Fill( 0. ); } return oCross; diff --git a/Utilities/ITK/Code/Review/itkCustomColormapFunctor.h b/Utilities/ITK/Code/Review/itkCustomColormapFunctor.h new file mode 100644 index 0000000000..45164e4e87 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkCustomColormapFunctor.h @@ -0,0 +1,112 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCustomColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkCustomColormapFunctor_h +#define __itkCustomColormapFunctor_h + +#include "itkColormapFunctor.h" + +#include <vector> + +namespace itk { + +namespace Functor { + +/** + * \class CustomColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT CustomColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef CustomColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + typedef std::vector<RealType> ChannelType; + + virtual RGBPixelType operator()( const TScalar & ) const; + + void SetRedChannel( ChannelType red ) + { + m_RedChannel = red; + } + ChannelType GetRedChannel() const + { + return m_RedChannel; + } + void SetGreenChannel( ChannelType green ) + { + m_GreenChannel = green; + } + ChannelType GetGreenChannel() const + { + return m_GreenChannel; + } + void SetBlueChannel( ChannelType blue ) + { + m_BlueChannel = blue; + } + ChannelType GetBlueChannel() const + { + return m_BlueChannel; + } + + +protected: + CustomColormapFunctor() {}; + ~CustomColormapFunctor() {}; + +private: + CustomColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + ChannelType m_RedChannel; + ChannelType m_GreenChannel; + ChannelType m_BlueChannel; + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkCustomColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkCustomColormapFunctor.txx b/Utilities/ITK/Code/Review/itkCustomColormapFunctor.txx new file mode 100644 index 0000000000..7768e8202d --- /dev/null +++ b/Utilities/ITK/Code/Review/itkCustomColormapFunctor.txx @@ -0,0 +1,98 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCustomColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkCustomColormapFunctor_txx +#define __itkCustomColormapFunctor_txx + +#include "itkCustomColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename CustomColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +CustomColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color mapping. + RealType red = 0.0; + if ( this->m_RedChannel.size() == 1 || value == 0.0 ) + { + red = this->m_RedChannel[0]; + } + else if ( this->m_RedChannel.size() > 1 ) + { + RealType size = static_cast<RealType>( this->m_RedChannel.size() ); + RealType index = vcl_ceil( value * ( size - 1.0 ) ); + RealType p1 = this->m_RedChannel[static_cast<unsigned int>( index )]; + RealType m1 = this->m_RedChannel[static_cast<unsigned int>( index-1 )]; + RealType d = p1 - m1; + red = d * ( size - 1.0 ) * ( value - ( index - 1.0 )/( size - 1.0 ) ) + + m1; + } + + RealType green = 0.0; + if ( this->m_GreenChannel.size() == 1 || value == 0.0 ) + { + green = this->m_GreenChannel[0]; + } + else if ( this->m_GreenChannel.size() > 1 ) + { + RealType size = static_cast<RealType>( this->m_GreenChannel.size() ); + RealType index = vcl_ceil( value * ( size - 1.0 ) ); + RealType p1 = this->m_GreenChannel[static_cast<unsigned int>( index )]; + RealType m1 = this->m_GreenChannel[static_cast<unsigned int>( index-1 )]; + RealType d = p1 - m1; + green = d * ( size - 1.0 ) * ( value - ( index - 1.0 )/( size - 1.0 ) ) + + m1; + } + + RealType blue = 0.0; + if ( this->m_BlueChannel.size() == 1 || value == 0.0 ) + { + blue = this->m_BlueChannel[0]; + } + else if ( this->m_BlueChannel.size() > 1 ) + { + RealType size = static_cast<RealType>( this->m_BlueChannel.size() ); + RealType index = vcl_ceil( value * ( size - 1.0 ) ); + RealType p1 = this->m_BlueChannel[static_cast<unsigned int>( index )]; + RealType m1 = this->m_BlueChannel[static_cast<unsigned int>( index-1 )]; + RealType d = p1 - m1; + blue = d * ( size - 1.0 ) * ( value - ( index - 1.0 )/( size - 1.0 ) ) + + m1; + } + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkDiffeomorphicDemonsRegistrationFilter.h b/Utilities/ITK/Code/Review/itkDiffeomorphicDemonsRegistrationFilter.h index a9e0055c60..940bcc82a3 100755 --- a/Utilities/ITK/Code/Review/itkDiffeomorphicDemonsRegistrationFilter.h +++ b/Utilities/ITK/Code/Review/itkDiffeomorphicDemonsRegistrationFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiffeomorphicDemonsRegistrationFilter.h,v $ Language: C++ - Date: $Date: 2008-07-05 00:07:02 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -137,7 +137,7 @@ public: * This amounts to using an update rule of the type * s <- s o (Id + u) instead of s <- s o exp(u) */ itkSetMacro( UseFirstOrderExp, bool ); - itkGetMacro( UseFirstOrderExp, bool ); + itkGetConstMacro( UseFirstOrderExp, bool ); itkBooleanMacro( UseFirstOrderExp ); /** Set/Get the threshold below which the absolute difference of diff --git a/Utilities/ITK/Code/Review/itkDiffeomorphicDemonsRegistrationFilter.txx b/Utilities/ITK/Code/Review/itkDiffeomorphicDemonsRegistrationFilter.txx index 51ccc40f42..ae19a522bf 100755 --- a/Utilities/ITK/Code/Review/itkDiffeomorphicDemonsRegistrationFilter.txx +++ b/Utilities/ITK/Code/Review/itkDiffeomorphicDemonsRegistrationFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiffeomorphicDemonsRegistrationFilter.txx,v $ Language: C++ - Date: $Date: 2008-11-07 19:39:44 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-05 23:09:19 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -255,7 +255,7 @@ DiffeomorphicDemonsRegistrationFilter<TFixedImage,TMovingImage,TDeformationField // Use time step if necessary. In many cases // the time step is one so this will be skipped - if ( fabs(dt - 1.0)>1.0e-4 ) + if ( vcl_fabs(dt - 1.0)>1.0e-4 ) { itkDebugMacro( "Using timestep: " << dt ); m_Multiplier->SetConstant( dt ); @@ -341,7 +341,6 @@ DiffeomorphicDemonsRegistrationFilter<TFixedImage,TMovingImage,TDeformationField // Region passing stuff this->GraftOutput( m_Adder->GetOutput() ); - this->GetOutput()->Modified(); DemonsRegistrationFunctionType *drfp = this->DownCastDifferenceFunctionType(); diff --git a/Utilities/ITK/Code/Review/itkDirectFourierReconstructionImageToImageFilter.h b/Utilities/ITK/Code/Review/itkDirectFourierReconstructionImageToImageFilter.h new file mode 100644 index 0000000000..4a74832fd3 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkDirectFourierReconstructionImageToImageFilter.h @@ -0,0 +1,174 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDirectFourierReconstructionImageToImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-06 22:00:34 $ + Version: $Revision: 1.3 $ + + Copyright ( c ) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkDirectFourierReconstructionImageToImageFilter_h +#define __itkDirectFourierReconstructionImageToImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkImage.h" + +#include "itkVnlFFTRealToComplexConjugateImageFilter.h" +#include "itkVnlFFTComplexConjugateToRealImageFilter.h" + +#include "itkImageRegionIteratorWithIndex.h" +#include "itkImageSliceConstIteratorWithIndex.h" + +#include "itkComplexBSplineInterpolateImageFunction.h" + +#include <math.h> + +namespace itk +{ +/** + * \class DirectFourierReconstructionImageToImageFilter + * \brief Direct fourier reconstruction filter of a tomographic volume. + * + * The algorithm is detailed in the Insight Journal publication on + * "Direct Fourier Tomographic Reconstruction Image-to-Image Filter" + * by D. Zosso, M. Bach Cuadra and J. Thiran, August 2007 + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/585 + * + * \ingroup ImageFilters + */ +template< class TInputPixelType = double, class TOutputPixelType = double > + class ITK_EXPORT DirectFourierReconstructionImageToImageFilter : + public ImageToImageFilter< Image< TInputPixelType, 3 >, Image< TOutputPixelType, 3 > > + { +public: + /// Standard Self typedef + typedef DirectFourierReconstructionImageToImageFilter Self; + /// InputImageType from TInputPixelType + typedef Image< TInputPixelType, 3 > InputImageType; + /// OutputImageType from TOutputPixelType + typedef Image< TOutputPixelType, 3 > OutputImageType; + + /// Standard Superclass typedef + typedef ImageToImageFilter< InputImageType, OutputImageType > Superclass; + + /// Standard Pointer typedef + typedef SmartPointer< Self > Pointer; + /// Standard ConstPointer typedef + typedef SmartPointer< const Self > ConstPointer; + + itkNewMacro( Self ); + itkTypeMacro( DirectFourierReconstructionImageToImageFilter, ImageToImageFilter ); + + /// Class RegionType + typedef typename InputImageType::RegionType RegionType; + /// Class IndexType + typedef typename InputImageType::IndexType IndexType; + /// Class SizeType + typedef typename InputImageType::SizeType SizeType; + /// Class PointType + typedef typename InputImageType::PointType PointType; + /// Class SpacingType + typedef typename InputImageType::SpacingType SpacingType; + + /// Standard (const) InputImagePointer + typedef typename InputImageType::ConstPointer ConstInputImagePointer; + /// Special (non-const) InputImagePointer + typedef typename InputImageType::Pointer InputImagePointer; + /// OutputImagePointer + typedef typename OutputImageType::Pointer OutputImagePointer; + + itkSetMacro( ZeroPadding, unsigned short int ); + itkGetConstMacro( ZeroPadding, unsigned short int ); + itkSetMacro( OverSampling, unsigned short int ); + itkGetConstMacro( OverSampling, unsigned short int ); + itkSetMacro( Cutoff, double ); + itkGetConstMacro( Cutoff, double ); + itkSetMacro( AlphaRange, double ); + itkGetConstMacro( AlphaRange, double ); + itkSetMacro( AlphaDirection, unsigned short int ); + itkGetConstMacro( AlphaDirection, unsigned short int ); + itkSetMacro( ZDirection, unsigned short int ); + itkGetConstMacro( ZDirection, unsigned short int ); + itkSetMacro( RDirection, unsigned short int ); + itkGetConstMacro( RDirection, unsigned short int ); + itkSetMacro( RadialSplineOrder, unsigned short int ); + itkGetConstMacro( RadialSplineOrder, unsigned short int ); + +protected: + /// Constructor + DirectFourierReconstructionImageToImageFilter(); + /// Destructor + ~DirectFourierReconstructionImageToImageFilter() {}; + + /// Output class information + void PrintSelf( std::ostream &os, Indent indent ) const; + + /// Generate metadata for output image + void GenerateOutputInformation(); + /// Calculate the required input region + void GenerateInputRequestedRegion(); + /// Actual filter computation + void GenerateData(); + +private: + /// Const slice iterator type of the input image + typedef ImageSliceConstIteratorWithIndex< InputImageType > InputSliceIteratorType; + + /// 1D FFT filter type + typedef VnlFFTRealToComplexConjugateImageFilter< double, 1 > FFTLineFilterType; + /// Derived 1D FFT image type + typedef FFTLineFilterType::OutputImageType FFTLineType; + /// Derived 1D input image type + typedef FFTLineFilterType::InputImageType ProjectionLineType; + /// 1D FFT line iterator + typedef ImageRegionIteratorWithIndex< FFTLineType > FFTLineIteratorType; + /// 1D FFT line B-Spline interpolator + typedef ComplexBSplineInterpolateImageFunction< FFTLineType, double, double > FFTLineInterpolatorType; + + /// 2D inverse FFT filter type + typedef VnlFFTComplexConjugateToRealImageFilter< double, 2 > IFFTSliceFilterType; + /// Derived 2D FFT image type + typedef IFFTSliceFilterType::InputImageType FFTSliceType; + /// Derived 2D output slice type + typedef IFFTSliceFilterType::OutputImageType OutputSliceType; + /// 2D FFT slice iterator + typedef ImageRegionIteratorWithIndex< FFTSliceType > FFTSliceIteratorType; + /// 2D output slice iterator + typedef ImageRegionIteratorWithIndex< OutputSliceType > OutputSliceIteratorType; + + + unsigned short int m_ZeroPadding; ///< n-fold zero-padding + unsigned short int m_OverSampling; ///< n-fold oversampling + double m_Cutoff; ///< Radial lowpass cut-off frequency + double m_AlphaRange; ///< Covered angular range + + unsigned short int m_ZDirection; ///< Axial index in the input image + unsigned short int m_AlphaDirection; ///< Angular index in the input image + unsigned short int m_RDirection; ///< Radial index in the input image + unsigned short int m_RadialSplineOrder; ///< Spline order for the radial BSpline interpolation + + double m_PI; ///< The constant pi.... + + RegionType m_InputRequestedRegion; ///< The region requested from the input image + + DirectFourierReconstructionImageToImageFilter(const Self&); ///< purposely not implemented + void operator=(const Self&); ///< purposely not implemented +}; + +} // namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkDirectFourierReconstructionImageToImageFilter.txx" +#endif + +#endif /* __itkDirectFourierReconstructionImageToImageFilter_h */ diff --git a/Utilities/ITK/Code/Review/itkDirectFourierReconstructionImageToImageFilter.txx b/Utilities/ITK/Code/Review/itkDirectFourierReconstructionImageToImageFilter.txx new file mode 100644 index 0000000000..d19957e7fd --- /dev/null +++ b/Utilities/ITK/Code/Review/itkDirectFourierReconstructionImageToImageFilter.txx @@ -0,0 +1,447 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkDirectFourierReconstructionImageToImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-06 22:00:34 $ + Version: $Revision: 1.6 $ + + Copyright ( c ) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkDirectFourierReconstructionImageToImageFilter_txx +#define __itkDirectFourierReconstructionImageToImageFilter_txx + +#include "itkDirectFourierReconstructionImageToImageFilter.h" + +namespace itk +{ +/** + * Initialize member variables with meaningful values. + */ +template< class TInputPixelType, class TOutputPixelType > + DirectFourierReconstructionImageToImageFilter< TInputPixelType, TOutputPixelType >:: + DirectFourierReconstructionImageToImageFilter():Superclass() +{ + const double RADIANS=1.0; + m_ZeroPadding = 2; + m_OverSampling = 2; + m_Cutoff = 1.0; + m_AlphaRange = 180; + + m_ZDirection = 1; + m_RDirection = 0; + m_AlphaDirection = 2; + + m_RadialSplineOrder = 3; + + m_PI = 4 * vcl_atan(RADIANS); +} + +/** + * Print out class state (member variables) + */ +template< class TInputPixelType, class TOutputPixelType > + void DirectFourierReconstructionImageToImageFilter< TInputPixelType, TOutputPixelType >:: + PrintSelf(std::ostream& os, Indent indent) const +{ + // call the superclass' implementation of this method + Superclass::PrintSelf(os,indent); + + os << indent << "Zero Padding Factor: " + << this->GetZeroPadding() << std::endl; + os << indent << "Fourier Oversampling Factor: " + << this->GetOverSampling() << std::endl; + os << indent << "Radial Spline Order: " + << this->GetRadialSplineOrder() << std::endl; + os << indent << "Fourier Radial Cutoff Frequency: " + << this->GetCutoff() << std::endl; + os << indent << "Alpha Range: " + << this->GetAlphaRange() << std::endl; + os << indent << "Z Direction: " + << this->GetZDirection() << std::endl; + os << indent << "Alpha Direction: " + << this->GetAlphaDirection() << std::endl; + os << indent << "Radial Direction: " + << this->GetRDirection() << std::endl; + os << indent << "Input Requested Region: " + << m_InputRequestedRegion << std::endl; +} + + /** + * Calculate image boundaries and define output regions, spacing, origin etc. + */ +template< class TInputPixelType, class TOutputPixelType > + void DirectFourierReconstructionImageToImageFilter< TInputPixelType, TOutputPixelType >:: + GenerateOutputInformation() +{ + // call the superclass' implementation of this method + Superclass::GenerateOutputInformation(); + + ConstInputImagePointer inputImage = this->GetInput(); + OutputImagePointer outputImage = this->GetOutput(); + + if ( !inputImage || !outputImage ) + { + return; + } + + RegionType inputRegion = inputImage->GetLargestPossibleRegion(); + IndexType inputStart = inputRegion.GetIndex(); + SizeType inputSize = inputRegion.GetSize(); + + IndexType outputStart; + SizeType outputSize; + + // Conserve axial dimensions + outputSize[2] = inputSize[m_ZDirection]; + outputStart[2] = inputStart[m_ZDirection]; + + // Radial dimensions give in-plane extent + outputSize[0] = outputSize[1] = inputSize[m_RDirection]; + outputStart[0] = outputStart[1] = 0; + + RegionType outputRegion; + outputRegion.SetIndex( outputStart ); + outputRegion.SetSize( outputSize ); + + outputImage->SetLargestPossibleRegion( outputRegion ); + + // Could be elsewhere... + PointType outputOrigin; + outputOrigin[0] = outputOrigin[1] = outputOrigin[2] = 0; + + outputImage->SetOrigin( outputOrigin ); + + + SpacingType inputSpacing = inputImage->GetSpacing(); + SpacingType outputSpacing; + // Conserve axial spacing + outputSpacing[2] = inputSpacing[m_ZDirection]; + // in-plane spacing = Radial spacing + outputSpacing[0] = outputSpacing[1] = inputSpacing[m_RDirection]; + + outputImage->SetSpacing( outputSpacing ); +} + +/** + * Calculate necessary input image boundaries + */ +template< class TInputPixelType, class TOutputPixelType > + void DirectFourierReconstructionImageToImageFilter< TInputPixelType, TOutputPixelType >:: + GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + OutputImagePointer outputImage = this->GetOutput(); + InputImagePointer inputImage = const_cast< InputImageType * >( this->GetInput() ); + if ( !inputImage || !outputImage ) + { + return; + } + + // request maximum angular and radial information / to be optimized + + SizeType inputSize = inputImage->GetLargestPossibleRegion().GetSize(); + IndexType inputStart = inputImage->GetLargestPossibleRegion().GetIndex(); + + // crop to requested z-axis + inputSize[m_ZDirection] = outputImage->GetRequestedRegion().GetSize()[2]; + inputStart[m_ZDirection] = outputImage->GetRequestedRegion().GetIndex()[2]; + + m_InputRequestedRegion.SetSize( inputSize ); + m_InputRequestedRegion.SetIndex( inputStart ); + + m_InputRequestedRegion.Crop( inputImage->GetLargestPossibleRegion() ); + inputImage->SetRequestedRegion( m_InputRequestedRegion ); +} + + +/** + * Actual computation + */ +template< class TInputPixelType, class TOutputPixelType > + void DirectFourierReconstructionImageToImageFilter< TInputPixelType, TOutputPixelType >:: + GenerateData() +{ + OutputImagePointer outputImage = this->GetOutput(); + ConstInputImagePointer inputImage = this->GetInput(); + + if ( !inputImage || !outputImage ) + { + return; + } + + outputImage->SetBufferedRegion( outputImage->GetRequestedRegion() ); + outputImage->Allocate(); + + // Crop angular input image size to 180 degrees + typename InputImageType::RegionType inputROI = m_InputRequestedRegion; + typename InputImageType::SizeType inputROISize = inputROI.GetSize(); + typename InputImageType::IndexType inputROIStart = inputROI.GetIndex(); + + // the number of projections needed to cover 180 degrees + const unsigned int alpha_size = static_cast< unsigned int >( vcl_floor( ( 180 * ( inputROISize[m_AlphaDirection] ) ) / m_AlphaRange ) ); + const double last_alpha_size = 1 + ( 180.0 * ( inputROISize[m_AlphaDirection] ) ) / m_AlphaRange - alpha_size; + inputROIStart[m_AlphaDirection] += ( inputROISize[m_AlphaDirection] - alpha_size ) / 2; + inputROISize[m_AlphaDirection] = alpha_size; + inputROI.SetSize( inputROISize ); + inputROI.SetIndex( inputROIStart ); + + // Setup the input ROI iterator + InputSliceIteratorType inputIt ( inputImage, inputROI ); + inputIt.SetFirstDirection( m_RDirection ); // Iterate first along r + inputIt.SetSecondDirection( m_AlphaDirection ); // then alpha (slice), and finally z (stack) + inputIt.GoToBegin(); + + // Setup projection line + ProjectionLineType::Pointer projectionLine = ProjectionLineType::New(); + ProjectionLineType::RegionType pRegion; + ProjectionLineType::SizeType pSize; + ProjectionLineType::IndexType pStart; + pSize[0] = inputROISize[m_RDirection] * m_ZeroPadding; + pStart[0] = inputROIStart[m_RDirection]; + pRegion.SetSize( pSize ); + pRegion.SetIndex( pStart ); + projectionLine->SetRegions( pRegion ); + projectionLine->Allocate(); + projectionLine->FillBuffer( 0 ); + + ProjectionLineType::IndexType pIdx; + const unsigned int pLineHalfShift = pSize[0] - inputROISize[m_RDirection] / 2; + + // Setup 1D FFT Filter + FFTLineFilterType::Pointer FFT = FFTLineFilterType::New(); + FFT->SetInput( projectionLine ); + + + // Setup FFT Line interpolator stack + FFTLineInterpolatorType::Pointer * FFTLineInterpolator = new FFTLineInterpolatorType::Pointer[alpha_size]; + for ( unsigned int alpha = 0; alpha < alpha_size; alpha++ ) + { + FFTLineInterpolator[alpha] = FFTLineInterpolatorType::New(); + FFTLineInterpolator[alpha]->SetSplineOrder( m_RadialSplineOrder ); + } + + // Setup cartesian FFTSlice domain + FFTSliceType::RegionType FFTSliceRegion; + FFTSliceType::SizeType FFTSliceSize; + FFTSliceType::IndexType FFTSliceStart; + + FFTSliceSize[0] = FFTSliceSize[1] = inputROISize[m_RDirection] * m_ZeroPadding * m_OverSampling; + FFTSliceStart[0] = FFTSliceStart[1] = 0; + FFTSliceRegion.SetSize( FFTSliceSize ); + FFTSliceRegion.SetIndex( FFTSliceStart ); + + FFTSliceType::Pointer FFTSlice = FFTSliceType::New(); + FFTSlice->SetRegions( FFTSliceRegion ); + FFTSlice->Allocate(); + FFTSlice->FillBuffer( 0 ); + + FFTSliceIteratorType FFTSliceIt ( FFTSlice, FFTSliceRegion ); + FFTSliceType::IndexType sIdx; + + + const double r_max = inputROISize[m_RDirection] * m_ZeroPadding * m_Cutoff / 2.0 - 1; + const double halfR = inputROISize[m_RDirection] * m_ZeroPadding / 2; + + + + // Only the central frame will be copied to the output + OutputSliceType::RegionType outputWindow; + OutputSliceType::SizeType outputWindowSize; + OutputSliceType::IndexType outputWindowStart; + + const unsigned int outputWindowShift = inputROISize[m_RDirection] * ( m_ZeroPadding * m_OverSampling - 1 ) / 2; + const unsigned int outputWindowHalf = inputROISize[m_RDirection] * m_ZeroPadding * m_OverSampling / 2; + + outputWindowSize[0] = outputImage->GetRequestedRegion().GetSize()[0]; + outputWindowSize[1] = outputImage->GetRequestedRegion().GetSize()[1]; + outputWindowStart[0] = outputImage->GetRequestedRegion().GetIndex()[0] + outputWindowShift; + outputWindowStart[1] = outputImage->GetRequestedRegion().GetIndex()[1] + outputWindowShift; + + outputWindow.SetSize( outputWindowSize ); + outputWindow.SetIndex( outputWindowStart ); + + + + OutputSliceType::IndexType wIdx; + typename OutputImageType::IndexType oIdx; + + ProgressReporter progress( this, 0, outputImage->GetRequestedRegion().GetNumberOfPixels() ); + + // Start iterating through slices + while ( !inputIt.IsAtEnd() ) + { + while ( !inputIt.IsAtEndOfSlice() ) // Start iterating through angles + { + while ( !inputIt.IsAtEndOfLine() ) // copy the whole input line + { + pIdx[0] = inputIt.GetIndex()[m_RDirection]; + + // Shift the pixel to the borders of the image (origin @ 0) + pIdx[0] += pLineHalfShift; + pIdx[0] %= pSize[0]; + + // Modulate image to shift DC to center of FFT line + ProjectionLineType::PixelType val = static_cast< ProjectionLineType::PixelType>( ( pIdx[0] & 1 ) ? -inputIt.Get() : inputIt.Get() ); + projectionLine->SetPixel( pIdx, val ); + + ++inputIt; + } // while ( !inputIt.IsAtEndOfLine() ) + + // Compute FFT + FFT->Update(); + + // link fft line into interpolator stack ... + FFTLineInterpolator[inputIt.GetIndex()[m_AlphaDirection] - inputROIStart[m_AlphaDirection]]->SetInputImage( FFT->GetOutput() ); + + // ... and unlink from upstream pipeline + FFT->GetOutput()->DisconnectPipeline(); + + inputIt.NextLine(); + } // while ( !inputIt.IsAtEndOfSlice() ) + + + + + double u, v; + double theta, r; + double alpha; + unsigned int a_lo; + + // Resample the cartesian FFT Slice from polar lines + for ( FFTSliceIt.GoToBegin(); !FFTSliceIt.IsAtEnd(); ++FFTSliceIt ) + { + sIdx = FFTSliceIt.GetIndex(); + + // center on DC + u = static_cast< double >( sIdx[ 0 ] ) - static_cast< double >( FFTSliceSize[0] ) / 2; + v = static_cast< double >( sIdx[ 1 ] ) - static_cast< double >( FFTSliceSize[1] ) / 2; + + // Calculate polar radius + r = sqrt( u*u + v*v ) / m_OverSampling; + + // Radial cutoff frequency + if ( r >= r_max ) + { + continue; + } + + + // Get polar angle - and map into [0 PI] + if (u == 0.0 && v == 0.0) + { + theta = 0.0; + } + else + { + theta = vcl_atan2( v, u ); + } + if ( theta < 0 ) + { + theta += m_PI; + r = -r; + } + + // Convert into alpha-image indices + alpha = theta * alpha_size / m_PI; + if ( alpha >= alpha_size ) + { + alpha -= alpha_size; + r = -r; + } + + + FFTLineType::PixelType out; + + // radial BSpline / linear angle interpolation + a_lo = static_cast< unsigned int >( vcl_floor( alpha ) ); + + if ( a_lo < alpha_size - 1 ) // no date-line crossing + { + // compute angular interpolation weights + FFTLineType::PixelType w_a_lo( 1 - ( alpha - a_lo ) ); + FFTLineType::PixelType w_a_hi( alpha - a_lo ); + + // get radial BSpline interpolations + FFTLineInterpolatorType::ContinuousIndexType idx; + idx[0] = r + halfR; + FFTLineType::PixelType o_lo = FFTLineInterpolator[ a_lo ]->EvaluateAtContinuousIndex( idx ); + FFTLineType::PixelType o_hi = FFTLineInterpolator[ a_lo + 1 ]->EvaluateAtContinuousIndex( idx ); + + out = w_a_lo * o_lo + w_a_hi * o_hi; + } + else // date-line crossing + { + // compute angular interpolation weights (bigger last interval) + FFTLineType::PixelType w_a_lo( 1 - ( alpha - a_lo ) / last_alpha_size ); + FFTLineType::PixelType w_a_hi( ( alpha - a_lo ) / last_alpha_size ); + + // get radial BSpline interpolations + FFTLineInterpolatorType::ContinuousIndexType idx; + idx[0] = r + halfR; + FFTLineType::PixelType o_lo = FFTLineInterpolator[ a_lo ]->EvaluateAtContinuousIndex( idx ); + idx[0] = halfR - r; + FFTLineType::PixelType o_hi = FFTLineInterpolator[ 0 ]->EvaluateAtContinuousIndex( idx ); + + out = w_a_lo * o_lo + w_a_hi * o_hi; + } + + FFTSliceIt.Set( out ); + + } // for FFTSliceIt + + // Setup inverse 2D FFT Filter + IFFTSliceFilterType::Pointer IFFT = IFFTSliceFilterType::New(); + IFFT->SetInput( FFTSlice ); + + // Calculate the inverse 2D FFT of the slice + IFFT->Update(); + + + // Copy desired region into the outputImage + + // Setup output iterator + OutputSliceIteratorType outputIt( IFFT->GetOutput(), outputWindow ); + // Current z-slice + oIdx[2] = inputIt.GetIndex()[m_ZDirection]; + for ( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt ) + { + wIdx = outputIt.GetIndex(); + // Write to correct window + oIdx[0] = wIdx[0] - outputWindowShift; + oIdx[1] = wIdx[1] - outputWindowShift; + // Fetch output data from buffer corners + wIdx[0] += outputWindowHalf; + wIdx[1] += outputWindowHalf; + wIdx[0] %= FFTSliceSize[0]; + wIdx[1] %= FFTSliceSize[1]; + + // Demodulate the image + TOutputPixelType val = static_cast< TOutputPixelType >( IFFT->GetOutput()->GetPixel( wIdx ) ); + outputImage->SetPixel( oIdx, ( ( wIdx[0] + wIdx[1] ) & 1 ) ? -val : val ); + progress.CompletedPixel(); + } // for outputIt + + + + inputIt.NextSlice(); + + } // while ( !inputIt.IsAtEnd() ) + + delete[] FFTLineInterpolator; + return; + +} + +} // namespace + +#endif diff --git a/Utilities/ITK/Code/Review/itkDiscreteGaussianDerivativeImageFilter.h b/Utilities/ITK/Code/Review/itkDiscreteGaussianDerivativeImageFilter.h index 390bc0e294..1615fa385c 100644 --- a/Utilities/ITK/Code/Review/itkDiscreteGaussianDerivativeImageFilter.h +++ b/Utilities/ITK/Code/Review/itkDiscreteGaussianDerivativeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiscreteGaussianDerivativeImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -99,7 +99,7 @@ public: * independently for each dimension, but see also * SetOrder(const unsigned int v). The default is 1 in each dimension. */ itkSetMacro(Order, OrderArrayType); - itkGetMacro(Order, const OrderArrayType); + itkGetConstMacro(Order, const OrderArrayType); /** The variance for the discrete Gaussian kernel. Sets the variance * independently for each dimension, but @@ -108,17 +108,17 @@ public: * of your image. If UseImageSpacing is false then the units are * pixels. */ itkSetMacro(Variance, ArrayType); - itkGetMacro(Variance, const ArrayType); + itkGetConstMacro(Variance, const ArrayType); /** The algorithm will size the discrete kernel so that the error * resulting from truncation of the kernel is no greater than * MaximumError. The default is 0.01 in each dimension. */ itkSetMacro(MaximumError, ArrayType); - itkGetMacro(MaximumError, const ArrayType); + itkGetConstMacro(MaximumError, const ArrayType); /** Set the kernel to be no wider than MaximumKernelWidth pixels, * even if MaximumError demands it. The default is 32 pixels. */ - itkGetMacro(MaximumKernelWidth, int); + itkGetConstMacro(MaximumKernelWidth, int); itkSetMacro(MaximumKernelWidth, int); /** Convenience Set methods for setting all dimensional parameters @@ -200,7 +200,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input image in its calculations */ itkSetMacro(UseImageSpacing, bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); /** DiscreteGaussianDerivativeImageFilter needs a larger input requested region * than the output requested region (larger by the size of the diff --git a/Utilities/ITK/Code/Review/itkDiscreteGaussianDerivativeImageFunction.h b/Utilities/ITK/Code/Review/itkDiscreteGaussianDerivativeImageFunction.h index 61d8fcba8d..a3be57561d 100644 --- a/Utilities/ITK/Code/Review/itkDiscreteGaussianDerivativeImageFunction.h +++ b/Utilities/ITK/Code/Review/itkDiscreteGaussianDerivativeImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiscreteGaussianDerivativeImageFunction.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -122,7 +122,7 @@ public: * the units are pixels. */ itkSetMacro( Variance, VarianceArrayType ); - itkGetMacro( Variance, const VarianceArrayType ); + itkGetConstMacro( Variance, const VarianceArrayType ); itkSetVectorMacro( Variance, double, VarianceArrayType::Length ); /** Convenience method for setting the variance for all dimensions. */ @@ -147,11 +147,11 @@ public: * 0.99999. */ itkSetClampMacro( MaximumError, double, 0.00001, 0.99999 ); - itkGetMacro( MaximumError, double ); + itkGetConstMacro( MaximumError, double ); /** Set/Get the derivative order for an individual dimension. */ itkSetMacro( Order, OrderArrayType ); - itkGetMacro( Order, const OrderArrayType ); + itkGetConstMacro( Order, const OrderArrayType ); itkSetVectorMacro( Order, unsigned int, OrderArrayType::Length ); /** Convenience method for setting the order for all dimensions. */ @@ -165,12 +165,12 @@ public: * Normalized derivatives are obtained multiplying by the scale * parameter t. */ itkSetMacro( NormalizeAcrossScale, bool ); - itkGetMacro( NormalizeAcrossScale, bool ); + itkGetConstMacro( NormalizeAcrossScale, bool ); itkBooleanMacro( NormalizeAcrossScale ); /** Set/Get the flag for using image spacing when calculating derivatives. */ itkSetMacro( UseImageSpacing, bool ); - itkGetMacro( UseImageSpacing, bool ); + itkGetConstMacro( UseImageSpacing, bool ); itkBooleanMacro( UseImageSpacing ); /** Set/Get a limit for growth of the kernel. Small maximum error values with @@ -178,11 +178,11 @@ public: * used to truncate a kernel in such instances. A warning will be given on * truncation of the kernel. */ itkSetMacro( MaximumKernelWidth, unsigned int ); - itkGetMacro( MaximumKernelWidth, unsigned int ); + itkGetConstMacro( MaximumKernelWidth, unsigned int ); /** Set/Get the interpolation mode. */ itkSetMacro( InterpolationMode, InterpolationModeType ); - itkGetMacro( InterpolationMode, InterpolationModeType ); + itkGetConstMacro( InterpolationMode, InterpolationModeType ); /** Set the input image. * \warning this method caches BufferedRegion information. diff --git a/Utilities/ITK/Code/Review/itkDiscreteGradientMagnitudeGaussianImageFunction.h b/Utilities/ITK/Code/Review/itkDiscreteGradientMagnitudeGaussianImageFunction.h index 0930f1df09..fcd86c3789 100644 --- a/Utilities/ITK/Code/Review/itkDiscreteGradientMagnitudeGaussianImageFunction.h +++ b/Utilities/ITK/Code/Review/itkDiscreteGradientMagnitudeGaussianImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiscreteGradientMagnitudeGaussianImageFunction.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -123,7 +123,7 @@ public: * If UseImageSpacing is true, the units are the physical units of your image. * If UseImageSpacing is false then the units are pixels */ itkSetMacro(Variance, VarianceArrayType); - itkGetMacro(Variance, const VarianceArrayType); + itkGetConstMacro(Variance, const VarianceArrayType); itkSetVectorMacro( Variance, double, VarianceArrayType::Length ); /** Convenience method for setting the variance for all dimensions */ @@ -145,18 +145,18 @@ public: * Gaussian operator size. The value is clamped between 0.00001 and * 0.99999. */ itkSetClampMacro( MaximumError, double, 0.00001, 0.99999 ); - itkGetMacro( MaximumError, double ); + itkGetConstMacro( MaximumError, double ); /** Set/Get the flag for calculating scale-space normalized derivatives. * Normalized derivatives are obtained multiplying by the scale * parameter t. */ itkSetMacro( NormalizeAcrossScale, bool ); - itkGetMacro( NormalizeAcrossScale, bool ); + itkGetConstMacro( NormalizeAcrossScale, bool ); itkBooleanMacro( NormalizeAcrossScale ); /** Set/Get the flag for using image spacing when calculating derivatives. */ itkSetMacro( UseImageSpacing, bool ); - itkGetMacro( UseImageSpacing, bool ); + itkGetConstMacro( UseImageSpacing, bool ); itkBooleanMacro( UseImageSpacing ); /** Set/Get a limit for growth of the kernel. Small maximum error values with @@ -164,11 +164,11 @@ public: * used to truncate a kernel in such instances. A warning will be given on * truncation of the kernel. */ itkSetMacro( MaximumKernelWidth, unsigned int ); - itkGetMacro( MaximumKernelWidth, unsigned int ); + itkGetConstMacro( MaximumKernelWidth, unsigned int ); /** Set/Get the interpolation mode. */ itkSetMacro( InterpolationMode, InterpolationModeType ); - itkGetMacro( InterpolationMode, InterpolationModeType ); + itkGetConstMacro( InterpolationMode, InterpolationModeType ); /** Set the input image. * \warning this method caches BufferedRegion information. diff --git a/Utilities/ITK/Code/Review/itkDiscreteHessianGaussianImageFunction.h b/Utilities/ITK/Code/Review/itkDiscreteHessianGaussianImageFunction.h index 4e681aceb0..f6d7ae8cc4 100644 --- a/Utilities/ITK/Code/Review/itkDiscreteHessianGaussianImageFunction.h +++ b/Utilities/ITK/Code/Review/itkDiscreteHessianGaussianImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiscreteHessianGaussianImageFunction.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -129,7 +129,7 @@ public: * If UseImageSpacing is true, the units are the physical units of your image. * If UseImageSpacing is false then the units are pixels. */ itkSetMacro( Variance, VarianceArrayType ); - itkGetMacro( Variance, const VarianceArrayType ); + itkGetConstMacro( Variance, const VarianceArrayType ); itkSetVectorMacro( Variance, double, VarianceArrayType::Length ); /** Convenience method for setting the variance for all dimensions */ @@ -151,18 +151,18 @@ public: * Gaussian operator size. The value is clamped between 0.00001 and * 0.99999. */ itkSetClampMacro( MaximumError, double, 0.00001, 0.99999 ); - itkGetMacro( MaximumError, double ); + itkGetConstMacro( MaximumError, double ); /** Set/Get the flag for calculating scale-space normalized derivatives. * Normalized derivatives are obtained multiplying by the scale * parameter t. */ itkSetMacro( NormalizeAcrossScale, bool ); - itkGetMacro( NormalizeAcrossScale, bool ); + itkGetConstMacro( NormalizeAcrossScale, bool ); itkBooleanMacro( NormalizeAcrossScale ); /** Set/Get the flag for using image spacing when calculating derivatives. */ itkSetMacro( UseImageSpacing, bool ); - itkGetMacro( UseImageSpacing, bool ); + itkGetConstMacro( UseImageSpacing, bool ); itkBooleanMacro( UseImageSpacing ); /** Set/Get a limit for growth of the kernel. Small maximum error values with @@ -170,11 +170,11 @@ public: * used to truncate a kernel in such instances. A warning will be given on * truncation of the kernel. */ itkSetMacro( MaximumKernelWidth, unsigned int ); - itkGetMacro( MaximumKernelWidth, unsigned int ); + itkGetConstMacro( MaximumKernelWidth, unsigned int ); /** Set/Get the interpolation mode. */ itkSetMacro( InterpolationMode, InterpolationModeType ); - itkGetMacro( InterpolationMode, InterpolationModeType ); + itkGetConstMacro( InterpolationMode, InterpolationModeType ); /** Set the input image. * \warning this method caches BufferedRegion information. diff --git a/Utilities/ITK/Code/Review/itkExponentialDeformationFieldImageFilter.h b/Utilities/ITK/Code/Review/itkExponentialDeformationFieldImageFilter.h index 93340d5c5f..8bc799e95b 100755 --- a/Utilities/ITK/Code/Review/itkExponentialDeformationFieldImageFilter.h +++ b/Utilities/ITK/Code/Review/itkExponentialDeformationFieldImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExponentialDeformationFieldImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-20 17:34:50 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -91,14 +91,14 @@ public: /** Specify the maximum number of iteration. */ itkSetMacro(MaximumNumberOfIterations, unsigned int); - itkGetMacro(MaximumNumberOfIterations, unsigned int); + itkGetConstMacro(MaximumNumberOfIterations, unsigned int); /** If AutomaticNumberOfIterations is off, the number of iterations is * given by MaximumNumberOfIterations. If it is on, we try to get * the lowest good number (which may not be larger than * MaximumNumberOfIterations ) */ itkSetMacro( AutomaticNumberOfIterations, bool ); - itkGetMacro( AutomaticNumberOfIterations, bool ); + itkGetConstMacro( AutomaticNumberOfIterations, bool ); itkBooleanMacro(AutomaticNumberOfIterations); /** If ComputeInverse is on, the filter will compute the exponential @@ -107,7 +107,7 @@ public: * therefore represent spatial transformations that are inverses of * each other. */ itkSetMacro( ComputeInverse, bool ); - itkGetMacro( ComputeInverse, bool ); + itkGetConstMacro( ComputeInverse, bool ); itkBooleanMacro(ComputeInverse); /** Image dimension. */ diff --git a/Utilities/ITK/Code/Review/itkExponentialDeformationFieldImageFilter.txx b/Utilities/ITK/Code/Review/itkExponentialDeformationFieldImageFilter.txx index b38f3e4bee..28217a55e6 100755 --- a/Utilities/ITK/Code/Review/itkExponentialDeformationFieldImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkExponentialDeformationFieldImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExponentialDeformationFieldImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-20 17:45:32 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-29 18:56:44 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -115,7 +115,7 @@ ExponentialDeformationFieldImageFilter<TInputImage,TOutputImage> } // Divide the norm by the minimum pixel spacing - maxnorm2 /= minpixelspacing; + maxnorm2 /= vnl_math_sqr(minpixelspacing); InputPixelRealValueType numiterfloat = 2.0 + 0.5 * vcl_log(maxnorm2)/vnl_math::ln2; diff --git a/Utilities/ITK/Code/Review/itkFFTComplexToComplexImageFilter.h b/Utilities/ITK/Code/Review/itkFFTComplexToComplexImageFilter.h index ace7858d33..2795052afa 100644 --- a/Utilities/ITK/Code/Review/itkFFTComplexToComplexImageFilter.h +++ b/Utilities/ITK/Code/Review/itkFFTComplexToComplexImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFFTComplexToComplexImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:15:48 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -90,7 +90,7 @@ public: * By selecting INVERSE, this filter will perform an inverse Fourier Transform, */ itkSetMacro( TransformDirection, TransformDirectionType ); - itkGetMacro( TransformDirection, TransformDirectionType ); + itkGetConstMacro( TransformDirection, TransformDirectionType ); protected: FFTComplexToComplexImageFilter() {} diff --git a/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.h b/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.h index dc8ef1bf10..104dd9fa33 100644 --- a/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.h +++ b/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.h @@ -34,7 +34,7 @@ namespace itk * * \author Simon K. Warfield simon.warfield@childrens.harvard.edu * - * \note Attribution Notice. This research work was made possible by + * \note Attribution Notice. This research work was made possible by * Grant Number R01 RR021885 (PI Simon K. Warfield, Ph.D.) from * the National Center for Research Resources (NCRR), a component of the * National Institutes of Health (NIH). Its contents are solely the @@ -95,8 +95,8 @@ protected: fftwf_destroy_plan(m_Plan); } } - - /** + + /** * these methods should be defined in every FFT filter class */ virtual void GenerateData(); // generates output from input diff --git a/Utilities/ITK/Code/Review/itkFastApproximateRankImageFilter.h b/Utilities/ITK/Code/Review/itkFastApproximateRankImageFilter.h index 1c9612fa11..052728b9be 100644 --- a/Utilities/ITK/Code/Review/itkFastApproximateRankImageFilter.h +++ b/Utilities/ITK/Code/Review/itkFastApproximateRankImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFastApproximateRankImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-11 09:11:32 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -82,7 +82,7 @@ public: this->Modified(); } } - itkGetMacro(Rank, float); + itkGetConstMacro(Rank, float); protected: FastApproximateRankImageFilter() diff --git a/Utilities/ITK/Code/Review/itkFastSymmetricForcesDemonsRegistrationFilter.txx b/Utilities/ITK/Code/Review/itkFastSymmetricForcesDemonsRegistrationFilter.txx index 2436b4a11d..b52839f084 100644 --- a/Utilities/ITK/Code/Review/itkFastSymmetricForcesDemonsRegistrationFilter.txx +++ b/Utilities/ITK/Code/Review/itkFastSymmetricForcesDemonsRegistrationFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFastSymmetricForcesDemonsRegistrationFilter.txx,v $ Language: C++ - Date: $Date: 2008-11-07 19:39:44 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-05 23:09:19 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -232,8 +232,6 @@ void FastSymmetricForcesDemonsRegistrationFilter<TFixedImage,TMovingImage,TDeformationField> ::ApplyUpdate(TimeStepType dt) { - this->GetUpdateBuffer()->Modified(); - // If we smooth the update buffer before applying it, then the are // approximating a viscuous problem as opposed to an elastic problem if ( this->GetSmoothUpdateField() ) @@ -242,7 +240,7 @@ FastSymmetricForcesDemonsRegistrationFilter<TFixedImage,TMovingImage,TDeformatio } // use time step if necessary - if ( fabs(dt - 1.0)>1.0e-4 ) + if ( vcl_fabs(dt - 1.0)>1.0e-4 ) { itkDebugMacro( "Using timestep: " << dt ); m_Multiplier->SetConstant( dt ); diff --git a/Utilities/ITK/Code/Review/itkFlatStructuringElement.txx b/Utilities/ITK/Code/Review/itkFlatStructuringElement.txx index 2d83add09e..a55c72dcf4 100644 --- a/Utilities/ITK/Code/Review/itkFlatStructuringElement.txx +++ b/Utilities/ITK/Code/Review/itkFlatStructuringElement.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFlatStructuringElement.txx,v $ Language: C++ - Date: $Date: 2008-09-30 18:07:03 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-06 16:49:33 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -109,15 +109,15 @@ FlatStructuringElement<VDimension> FlatStructuringElement<VDimension> while (theta <= M_PI/2.0 + 0.0001) { LType O; - O[0] = k1 * cos(theta); - O[1] = k2 * sin(theta); + O[0] = k1 * vcl_cos(theta); + O[1] = k2 * vcl_sin(theta); if (!res.checkParallel(O, res.m_Lines)) { //std::cout << O << std::endl; res.m_Lines.push_back(O); } - O[0] = k1 * cos(-theta); - O[1] = k2 * sin(-theta); + O[0] = k1 * vcl_cos(-theta); + O[1] = k2 * vcl_sin(-theta); if (!res.checkParallel(O, res.m_Lines)) { //std::cout << O << std::endl; @@ -130,9 +130,9 @@ FlatStructuringElement<VDimension> FlatStructuringElement<VDimension> return(res); } -// O[0] = k1 * cos(phi) * cos(theta); -// O[1] = k2 * cos(phi) * sin(theta); -// O[2] = k3 * sin(theta); +// O[0] = k1 * vcl_cos(phi) * vcl_cos(theta); +// O[1] = k2 * vcl_cos(phi) * vcl_sin(theta); +// O[2] = k3 * vcl_sin(theta); template<unsigned int VDimension> FlatStructuringElement<VDimension> FlatStructuringElement<VDimension> @@ -153,7 +153,7 @@ FlatStructuringElement<VDimension> FlatStructuringElement<VDimension> case 12: { // dodecahedron - float phi = (1.0 + sqrt(5.0)) / 2.0; + float phi = (1.0 + vcl_sqrt(5.0)) / 2.0; float b = 1.0/phi; float c = 2.0 - phi; unsigned facets = 12; @@ -325,7 +325,7 @@ FlatStructuringElement<VDimension> FlatStructuringElement<VDimension> case 20: { // Icosahedron - float phi = (1.0 + sqrt(5.0)) / 2.0; + float phi = (1.0 + vcl_sqrt(5.0)) / 2.0; float a = 0.5; float b = 1.0/(2.0*phi); unsigned facets = 20; @@ -527,8 +527,8 @@ FlatStructuringElement<VDimension> FlatStructuringElement<VDimension> // create triangular facet approximation to a sphere - begin with // unit sphere // total number of facets is 8 * (4^iterations) - unsigned int facets = 8 * (int)pow((double)4, iterations); - float sqrt2 = sqrt(2.0); + unsigned int facets = 8 * (int)vcl_pow((double)4, iterations); + float sqrt2 = vcl_sqrt(2.0); // std::cout << facets << " facets" << std::endl; typedef std::vector<FacetType> FacetArrayType; FacetArrayType FacetArray; @@ -930,7 +930,7 @@ checkParallel(LType NewVec, DecompType Lines) LType LL = Lines[i]; LL.Normalize(); float L = NN*LL; - if ((1.0 - fabs(L)) < 0.000001) return(true); + if ((1.0 - vcl_fabs(L)) < 0.000001) return(true); } return(false); } diff --git a/Utilities/ITK/Code/Review/itkGaussianDerivativeOperator.txx b/Utilities/ITK/Code/Review/itkGaussianDerivativeOperator.txx index 9d0ef0f8a8..bb5100de5a 100644 --- a/Utilities/ITK/Code/Review/itkGaussianDerivativeOperator.txx +++ b/Utilities/ITK/Code/Review/itkGaussianDerivativeOperator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianDerivativeOperator.txx,v $ Language: C++ - Date: $Date: 2008-10-19 18:34:21 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-06 16:49:36 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -111,7 +111,7 @@ GaussianDerivativeOperator<TPixel,VDimension, TAllocator> int j; typename CoefficientVector::iterator it; - const double et = ::exp(-m_Variance); + const double et = vcl_exp(-m_Variance); const double cap = 1.0 - m_MaximumError; // Create the kernel coefficients as a std::vector @@ -140,7 +140,6 @@ GaussianDerivativeOperator<TPixel,VDimension, TAllocator> for (it = coeff.begin(); it < coeff.end(); ++it) { *it /= sum; - //*it /= pow( 2 * 3.141592654 * m_Variance, 0.5 ); } // Make symmetric @@ -234,7 +233,7 @@ GaussianDerivativeOperator<TPixel,VDimension, TAllocator> else { m=3.5/d; - accumulator =(::exp(d)/::sqrt(d))*(0.39894228+m*(0.1328592e-1 + accumulator =(vcl_exp(d)/vcl_sqrt(d))*(0.39894228+m*(0.1328592e-1 +m*(0.225319e-2+m*(-0.157565e-2+m*(0.916281e-2 +m*(-0.2057706e-1+m*(0.2635537e-1+m*(-0.1647633e-1 +m*0.392377e-2)))))))); @@ -266,7 +265,7 @@ GaussianDerivativeOperator<TPixel,VDimension, TAllocator> accumulator = 0.39894228+m*(-0.3988024e-1+m*(-0.362018e-2 +m*(0.163801e-2+m*(-0.1031555e-1+m*accumulator)))); - accumulator *= (::exp(d)/::sqrt(d)); + accumulator *= (vcl_exp(d)/vcl_sqrt(d)); } if (y<0.0) return -accumulator; @@ -294,12 +293,12 @@ GaussianDerivativeOperator<TPixel,VDimension, TAllocator> toy=2.0/vcl_fabs(y); qip=accumulator=0.0; qi=1.0; - for (j=2*(n+(int)::sqrt(ACCURACY*n)); j>0; j--) + for (j=2*(n+(int)vcl_sqrt(ACCURACY*n)); j>0; j--) { qim=qip+j*toy*qi; qip=qi; qi=qim; - if (fabs(qi) > 1.0e10) + if (vcl_fabs(qi) > 1.0e10) { accumulator *= 1.0e-10; qi *= 1.0e-10; diff --git a/Utilities/ITK/Code/Review/itkGreenColormapFunctor.h b/Utilities/ITK/Code/Review/itkGreenColormapFunctor.h new file mode 100644 index 0000000000..029f867cb9 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkGreenColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGreenColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:08:09 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkGreenColormapFunctor_h +#define __itkGreenColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class GreenColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT GreenColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef GreenColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + GreenColormapFunctor() {}; + ~GreenColormapFunctor() {}; + +private: + GreenColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkGreenColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkGreenColormapFunctor.txx b/Utilities/ITK/Code/Review/itkGreenColormapFunctor.txx new file mode 100644 index 0000000000..56a89661dc --- /dev/null +++ b/Utilities/ITK/Code/Review/itkGreenColormapFunctor.txx @@ -0,0 +1,49 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGreenColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkGreenColormapFunctor_txx +#define __itkGreenColormapFunctor_txx + +#include "itkGreenColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename GreenColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +GreenColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = 0; + pixel[1] = this->RescaleRGBComponentValue( value ); + pixel[2] = 0; + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkGreyColormapFunctor.h b/Utilities/ITK/Code/Review/itkGreyColormapFunctor.h new file mode 100644 index 0000000000..54666242cb --- /dev/null +++ b/Utilities/ITK/Code/Review/itkGreyColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGreyColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkGreyColormapFunctor_h +#define __itkGreyColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class GreyColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT GreyColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef GreyColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + GreyColormapFunctor() {}; + ~GreyColormapFunctor() {}; + +private: + GreyColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkGreyColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkGreyColormapFunctor.txx b/Utilities/ITK/Code/Review/itkGreyColormapFunctor.txx new file mode 100644 index 0000000000..59c50c010e --- /dev/null +++ b/Utilities/ITK/Code/Review/itkGreyColormapFunctor.txx @@ -0,0 +1,49 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGreyColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkGreyColormapFunctor_txx +#define __itkGreyColormapFunctor_txx + +#include "itkGreyColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename GreyColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +GreyColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( value ); + pixel[1] = pixel[0]; + pixel[2] = pixel[0]; + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.h b/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.h index 941c183f5d..4d99619e24 100644 --- a/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.h +++ b/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGridForwardWarpImageFilter.h,v $ Language: C++ - Date: $Date: 2008-07-04 23:16:43 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -97,13 +97,13 @@ public: itkSetMacro( BackgroundValue, PixelType ); /** Get the background value */ - itkGetMacro( BackgroundValue, PixelType ); + itkGetConstMacro( BackgroundValue, PixelType ); /** Set the foreground value */ itkSetMacro( ForegroundValue, PixelType ); /** Get the foreground value */ - itkGetMacro( ForegroundValue, PixelType ); + itkGetConstMacro( ForegroundValue, PixelType ); #ifdef ITK_USE_CONCEPT_CHECKING diff --git a/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.txx b/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.txx index 4f0f3f37f5..b76a5a1bd0 100644 --- a/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGridForwardWarpImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-07-05 00:35:59 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-05-26 23:45:04 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -129,7 +129,11 @@ GridForwardWarpImageFilter<TDeformationField,TOutputImage> inside = false; break; } +#ifdef ITK_USE_PORTABLE_ROUND + refIndex[j] = Math::Round(contindex[j]); +#else refIndex[j] = vnl_math_rnd(contindex[j]); +#endif } if( inside ) @@ -156,7 +160,11 @@ GridForwardWarpImageFilter<TDeformationField,TOutputImage> targetIn = false; break; } +#ifdef ITK_USE_PORTABLE_ROUND + targetIndex[j] = Math::Round(contindex[j]); +#else targetIndex[j] = vnl_math_rnd(contindex[j]); +#endif } if( targetIn ) diff --git a/Utilities/ITK/Code/Review/itkGridImageSource.h b/Utilities/ITK/Code/Review/itkGridImageSource.h new file mode 100644 index 0000000000..061c51966c --- /dev/null +++ b/Utilities/ITK/Code/Review/itkGridImageSource.h @@ -0,0 +1,179 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGridImageSource.h,v $ + Language: C++ + Date: $Date: 2009-05-14 21:12:03 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkGridImageSource_h +#define __itkGridImageSource_h + +#include "itkImageSource.h" +#include "itkFixedArray.h" +#include "itkKernelFunction.h" +#include "itkVectorContainer.h" + +#include "vnl/vnl_vector.h" + +namespace itk +{ + +/** \class GridImageSource + * \brief Generate an n-dimensional image of a grid. + * + * GridImageSource generates an image of a grid. + * From the abstract... + * "Certain classes of images find disparate use amongst members of the + * ITK community for such purposes as visualization, simulation, + * testing, etc. Currently there exists two derived classes from the + * ImageSource class used for generating specific images for various + * applications, viz. RandomImageSource and GaussianImageSource. We + * propose to add to this set with the class GridImageSource which, + * obviously enough, produces a grid image. Such images are useful for + * visualizing deformation when used in conjunction with the + * WarpImageFilter, simulating magnetic resonance tagging images, or + * creating optical illusions with which to amaze your friends." + * + * The output image may be of any dimension. + * + * \author Tustison N., Avants B., Gee J. University of Pennsylvania + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/475 + * + * \ingroup DataSources + */ +template <typename TOutputImage> +class ITK_EXPORT GridImageSource : public ImageSource<TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef GridImageSource Self; + typedef ImageSource<TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro( GridImageSource, ImageSource ); + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + typedef double RealType; + + /** Dimensionality of the output image */ + itkStaticConstMacro( ImageDimension, unsigned int, + TOutputImage::ImageDimension ); + + /** Typedef for the output image types. */ + typedef TOutputImage ImageType; + typedef typename TOutputImage::RegionType ImageRegionType; + typedef typename TOutputImage::PixelType PixelType; + typedef typename TOutputImage::SpacingType SpacingType; + typedef typename TOutputImage::PointType OriginType; + typedef typename TOutputImage::DirectionType DirectionType; + typedef typename TOutputImage::SizeType SizeType; + + /** Other convenient types. */ + typedef FixedArray<RealType, itkGetStaticConstMacro(ImageDimension)> + ArrayType; + typedef FixedArray<bool, itkGetStaticConstMacro(ImageDimension)> + BoolArrayType; + typedef vnl_vector<RealType> PixelArrayType; + typedef VectorContainer<unsigned long, PixelArrayType> PixelArrayContainerType; + + /** Gets and sets for the output image. */ + itkSetMacro( Spacing, SpacingType ); + itkGetConstReferenceMacro( Spacing, SpacingType ); + + itkSetMacro( Origin, OriginType ); + itkGetConstReferenceMacro( Origin, OriginType ); + + itkSetMacro( Direction, DirectionType ); + itkGetConstReferenceMacro( Direction, DirectionType ); + + itkSetMacro( Size, SizeType ); + itkGetConstReferenceMacro( Size, SizeType ); + + /** Gets and sets for grid parameters */ + itkSetObjectMacro( KernelFunction, KernelFunction ); + itkGetConstReferenceObjectMacro( KernelFunction, KernelFunction ); + + itkSetMacro( Sigma, ArrayType ); + itkGetConstReferenceMacro( Sigma, ArrayType ); + + itkSetMacro( GridSpacing, ArrayType ); + itkGetConstReferenceMacro( GridSpacing, ArrayType ); + + itkSetMacro( GridOffset, ArrayType ); + itkGetConstReferenceMacro( GridOffset, ArrayType ); + + itkSetMacro( WhichDimensions, BoolArrayType ); + itkGetConstReferenceMacro( WhichDimensions, BoolArrayType ); + + itkSetMacro( Scale, RealType ); + itkGetConstReferenceMacro( Scale, RealType ); + +protected: + GridImageSource(); + ~GridImageSource(){}; + void PrintSelf(std::ostream& os, Indent indent) const; + + virtual void + ThreadedGenerateData(const ImageRegionType& + outputRegionForThread, int threadId ); + virtual void BeforeThreadedGenerateData(); + virtual void GenerateOutputInformation(); + +private: + GridImageSource(const GridImageSource&); //purposely not implemented + void operator=(const GridImageSource&); //purposely not implemented + + /** Parameters for the output image. */ + + SizeType m_Size; //size + SpacingType m_Spacing; //spacing + OriginType m_Origin; //origin + DirectionType m_Direction; //direction + + /** Parameters for the grid. */ + + /** Internal variable to speed up the calculation of pixel values */ + typename PixelArrayContainerType::Pointer m_PixelArrays; + + /** The kernel function used to create the grid */ + typename KernelFunction::Pointer m_KernelFunction; + + /** The standard deviation of the gaussians + * or width of the box functions. */ + ArrayType m_Sigma; + + /** The grid spacing of the peaks. */ + ArrayType m_GridSpacing; + + /** The grid spacing of the peaks. */ + ArrayType m_GridOffset; + + /** Which dimensions which are gridded. */ + BoolArrayType m_WhichDimensions; + + /** A scale factor multiplied by the true value of the grid. */ + RealType m_Scale; +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkGridImageSource.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkGridImageSource.txx b/Utilities/ITK/Code/Review/itkGridImageSource.txx new file mode 100644 index 0000000000..1b1615b62c --- /dev/null +++ b/Utilities/ITK/Code/Review/itkGridImageSource.txx @@ -0,0 +1,167 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkGridImageSource.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 13:03:47 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkGridImageSource_txx +#define __itkGridImageSource_txx + +#include "itkGaussianKernelFunction.h" +#include "itkGridImageSource.h" +#include "itkImageLinearIteratorWithIndex.h" +#include "itkImageRegionIteratorWithIndex.h" +#include "itkProgressReporter.h" + +namespace itk +{ + +template <class TOutputImage> +GridImageSource<TOutputImage> +::GridImageSource() +{ + this->m_Size.Fill( 64 ); + this->m_Spacing.Fill( 1.0 ); + this->m_Origin.Fill( 0.0 ); + this->m_Direction.SetIdentity(); + + this->m_Sigma.Fill( 0.5 ); + this->m_GridSpacing.Fill( 4.0 ); + this->m_GridOffset.Fill( 0.0 ); + this->m_WhichDimensions.Fill( true ); + this->m_Scale = 255.0; + + this->m_KernelFunction = dynamic_cast<KernelFunction*>( + GaussianKernelFunction::New().GetPointer() ); +} + +template <typename TOutputImage> +void +GridImageSource<TOutputImage> +::BeforeThreadedGenerateData() +{ + typename ImageType::Pointer output = this->GetOutput( 0 ); + + this->m_PixelArrays = PixelArrayContainerType::New(); + m_PixelArrays->Initialize(); + + for ( unsigned int i = 0; i < ImageDimension; i++ ) + { + if ( this->m_GridOffset[i] > this->m_GridSpacing[i] ) + { + this->m_GridOffset[i] = this->m_GridSpacing[i]; + } + PixelArrayType pixels = m_PixelArrays->CreateElementAt( i ); + pixels.set_size( this->m_Size[i] ); + pixels.fill( 1 ); + if ( this->m_WhichDimensions[i] ) + { + ImageLinearIteratorWithIndex<ImageType> It( output, output->GetRequestedRegion() ); + It.SetDirection( i ); + + /** Add two extra functions in the front and one in the back to ensure coverage */ + unsigned int numberOfGaussians = static_cast<unsigned int>( + vcl_ceil( this->m_Size[i]*this->m_Spacing[i]/this->m_GridSpacing[i] ) + 4 ); + for ( It.GoToBegin(); !It.IsAtEndOfLine(); ++It ) + { + typename ImageType::IndexType index = It.GetIndex(); + typename ImageType::PointType point; + output->TransformIndexToPhysicalPoint( index, point ); + + RealType val = 0; + for ( unsigned int j = 0; j < numberOfGaussians; j++ ) + { + RealType num = point[i] - static_cast<RealType>( j-2 )*this->m_GridSpacing[i] + - this->m_Origin[i] - this->m_GridOffset[i]; + val += this->m_KernelFunction->Evaluate( num/this->m_Sigma[i] ); + } + pixels[index[i]] = val; + } + pixels = 1.0 - pixels/pixels.max_value(); + } + this->m_PixelArrays->SetElement( i, pixels ); + } +} + +template <typename TOutputImage> +void +GridImageSource<TOutputImage> +::ThreadedGenerateData( const ImageRegionType& outputRegionForThread, int threadId ) +{ + // Support progress methods/callbacks + ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); + typename ImageType::Pointer output = this->GetOutput( 0 ); + + ImageRegionIteratorWithIndex<ImageType> It( output, outputRegionForThread ); + + for ( It.GoToBegin(); !It.IsAtEnd(); ++It ) + { + RealType val = 1.0; + typename ImageType::IndexType index = It.GetIndex(); + for ( unsigned int i = 0; i < ImageDimension; i++ ) + { + val *= this->m_PixelArrays->GetElement( i )[index[i]]; + } + It.Set( this->m_Scale * val ); + progress.CompletedPixel(); + } +} + +template <class TOutputImage> +void +GridImageSource<TOutputImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Output image information: " << std::endl; + os << indent << " Size = " << this->GetSize() << std::endl; + os << indent << " Spacing = " << this->GetSpacing() << std::endl; + os << indent << " Origin = " << this->GetOrigin() << std::endl; + os << indent << " Direction = " << this->GetDirection() << std::endl; + os << indent << " Scale = " << this->GetScale() << std::endl; + + os << indent << "Grid information: " << std::endl; + os << indent << " WhichDimensions = " << this->GetWhichDimensions() << std::endl; + os << indent << " Kernel = " << this->GetKernelFunction() << std::endl; + os << indent << " Sigma = " << this->GetSigma() << std::endl; + os << indent << " Grid spacing = " << this->GetGridSpacing() << std::endl; + os << indent << " Grid offset = " << this->GetGridOffset() << std::endl; + +} + +//---------------------------------------------------------------------------- +template <typename TOutputImage> +void +GridImageSource<TOutputImage> +::GenerateOutputInformation() +{ + ImageType *output; + output = this->GetOutput( 0 ); + + typename ImageType::IndexType index; + index.Fill( 0 ); + + typename ImageType::RegionType largestPossibleRegion; + largestPossibleRegion.SetSize( this->m_Size ); + largestPossibleRegion.SetIndex( index ); + output->SetLargestPossibleRegion( largestPossibleRegion ); + + output->SetSpacing( this->m_Spacing ); + output->SetOrigin( this->m_Origin ); + output->SetDirection( this->m_Direction ); +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkHSVColormapFunctor.h b/Utilities/ITK/Code/Review/itkHSVColormapFunctor.h new file mode 100644 index 0000000000..214f62b819 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkHSVColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHSVColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkHSVColormapFunctor_h +#define __itkHSVColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class HSVColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT HSVColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef HSVColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + HSVColormapFunctor() {}; + ~HSVColormapFunctor() {}; + +private: + HSVColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkHSVColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkHSVColormapFunctor.txx b/Utilities/ITK/Code/Review/itkHSVColormapFunctor.txx new file mode 100644 index 0000000000..addee5d2eb --- /dev/null +++ b/Utilities/ITK/Code/Review/itkHSVColormapFunctor.txx @@ -0,0 +1,63 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHSVColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkHSVColormapFunctor_txx +#define __itkHSVColormapFunctor_txx + +#include "itkHSVColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename HSVColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +HSVColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color mapping. + // Apply the color mapping. + RealType red = vnl_math_abs( 5.0 * ( value - 0.5 ) ) - 5.0/6.0; + red = vnl_math_min( red, 1.0 ); + red = vnl_math_max( 0.0, red ); + + RealType green = -vnl_math_abs( 5.0 * ( value - 11.0/30.0 ) ) + 11.0/6.0; + green = vnl_math_min( green, 1.0 ); + green = vnl_math_max( 0.0, green ); + + RealType blue = -vnl_math_abs( 5.0 * ( value - 19.0/30.0 ) ) + 11.0/6.0; + blue = vnl_math_min( blue, 1.0 ); + blue = vnl_math_max( 0.0, blue ); + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkHeavisideStepFunction.h b/Utilities/ITK/Code/Review/itkHeavisideStepFunction.h new file mode 100644 index 0000000000..022f43729a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkHeavisideStepFunction.h @@ -0,0 +1,98 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHeavisideStepFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-09 21:06:28 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkHeavisideStepFunction_h +#define __itkHeavisideStepFunction_h + +#include "itkHeavisideStepFunctionBase.h" + +namespace itk +{ + +/** \class HeavisideStepFunction + * + * \brief Implementation of the classical Heaviside step function. + * + * The Heaviside Step function is a piece-wise function: + * + * http://en.wikipedia.org/wiki/Heaviside_step_function + * + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template< class TInput = float, class TOutput = double > +class HeavisideStepFunction : + public HeavisideStepFunctionBase< TInput, TOutput > +{ +public: + typedef HeavisideStepFunction Self; + typedef HeavisideStepFunctionBase< TInput, TOutput > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + itkNewMacro( Self ); + + itkTypeMacro( HeavisideStepFunction, HeavisideStepFunctionBase ); + + typedef typename Superclass::InputType InputType; + typedef typename Superclass::OutputType OutputType; + + /** Evaluate at the specified input position */ + virtual OutputType Evaluate( const InputType& input ) const + { + return ( input >= 0.0 ) ? 1.0 : 0.0; + } + + /** Evaluate the derivative at the specified input position */ + virtual OutputType EvaluateDerivative( const InputType& input ) const + { + return ( input == 0.0 ) ? 1.0 : 0.0; + } + +protected: + HeavisideStepFunction() {} + virtual ~HeavisideStepFunction() {} + +private: + HeavisideStepFunction(const Self& ); //purposely not implemented + void operator=(const Self& ); //purposely not implemented + +}; + +} + +#endif diff --git a/Utilities/ITK/Code/Review/itkHeavisideStepFunctionBase.h b/Utilities/ITK/Code/Review/itkHeavisideStepFunctionBase.h new file mode 100644 index 0000000000..199799c77a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkHeavisideStepFunctionBase.h @@ -0,0 +1,82 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHeavisideStepFunctionBase.h,v $ + Language: C++ + Date: $Date: 2009-05-09 21:06:28 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkHeavisideStepFunctionBase_h +#define __itkHeavisideStepFunctionBase_h + +#include "itkFunctionBase.h" + +namespace itk +{ + +/** \class HeavisideStepFunctionBase + * + * \brief Base class of the Heaviside function. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template< typename TInput = float, typename TOutput = double > +class HeavisideStepFunctionBase : public FunctionBase< TInput, TOutput > +{ +public: + typedef HeavisideStepFunctionBase Self; + typedef FunctionBase< TInput, TOutput > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::InputType InputType; + typedef typename Superclass::OutputType OutputType; + + /** Evaluate at the specified input position */ + virtual OutputType Evaluate( const InputType& input ) const = 0; + + /** Evaluate the derivative at the specified input position */ + virtual OutputType EvaluateDerivative( const InputType& input ) const = 0; + +protected: + HeavisideStepFunctionBase() {} + virtual ~HeavisideStepFunctionBase() {} + +private: + HeavisideStepFunctionBase(const Self& ); //purposely not implemented + void operator=(const Self& ); //purposely not implemented + +}; + +} + +#endif diff --git a/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.h b/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.h index dc45e75e0f..15b202cc9a 100644 --- a/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.h +++ b/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHessianToObjectnessMeasureImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-25 18:52:52 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -89,33 +89,33 @@ public: * (the ratio of the smallest eigenvalue that has to be large to the larger ones). * Smaller values lead to increased sensitivity to the object dimensionality. */ itkSetMacro(Alpha,double); - itkGetMacro(Alpha,double); + itkGetConstMacro(Alpha,double); /** Set/Get Beta, the weight corresponding to R_B * (the ratio of the largest eigenvalue that has to be small to the larger ones). * Smaller values lead to increased sensitivity to the object dimensionality. */ itkSetMacro(Beta,double); - itkGetMacro(Beta,double); + itkGetConstMacro(Beta,double); /** Set/Get Gamma, the weight corresponding to S * (the Frobenius norm of the Hessian matrix, or second-order structureness) */ itkSetMacro(Gamma,double); - itkGetMacro(Gamma,double); + itkGetConstMacro(Gamma,double); /** Toggle scaling the objectness measure with the magnitude of the largest absolute eigenvalue */ itkSetMacro(ScaleObjectnessMeasure,bool); - itkGetMacro(ScaleObjectnessMeasure,bool); + itkGetConstMacro(ScaleObjectnessMeasure,bool); itkBooleanMacro(ScaleObjectnessMeasure); /** Set/Get the dimensionality of the object (0: points (blobs), * 1: lines (vessels), 2: planes (plate-like structures), 3: hyper-planes. * ObjectDimension must be smaller than ImageDimension. */ - itkSetMacro(ObjectDimension,int); - itkGetMacro(ObjectDimension,int); + itkSetMacro(ObjectDimension,unsigned int); + itkGetConstMacro(ObjectDimension,unsigned int); /** Enhance bright structures on a dark background if true, the opposite if false. */ itkSetMacro(BrightObject,bool); - itkGetMacro(BrightObject,bool); + itkGetConstMacro(BrightObject,bool); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ @@ -140,7 +140,7 @@ private: double m_Alpha; double m_Beta; double m_Gamma; - int m_ObjectDimension; + unsigned int m_ObjectDimension; bool m_BrightObject; bool m_ScaleObjectnessMeasure; }; diff --git a/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.txx b/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.txx index 4d881522b0..34483da926 100644 --- a/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHessianToObjectnessMeasureImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-25 00:33:34 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-05-11 07:50:26 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -144,9 +144,9 @@ HessianToObjectnessMeasureImageFilter< TInputImage, TOutputImage> { rADenominatorBase *= sortedAbsEigenValues[j]; } - if (fabs(rADenominatorBase) > 0.0) + if (vcl_fabs(rADenominatorBase) > 0.0) { - rA /= pow(rADenominatorBase, 1.0 / (ImageDimension-m_ObjectDimension-1)); + rA /= vcl_pow(rADenominatorBase, 1.0 / (ImageDimension-m_ObjectDimension-1)); objectnessMeasure *= 1.0 - vcl_exp(- 0.5 * vnl_math_sqr(rA) / vnl_math_sqr(m_Alpha)); } else @@ -163,9 +163,9 @@ HessianToObjectnessMeasureImageFilter< TInputImage, TOutputImage> { rBDenominatorBase *= sortedAbsEigenValues[j]; } - if (fabs(rBDenominatorBase) > 0.0) + if (vcl_fabs(rBDenominatorBase) > 0.0) { - rB /= pow(rBDenominatorBase, 1.0 / (ImageDimension-m_ObjectDimension)); + rB /= vcl_pow(rBDenominatorBase, 1.0 / (ImageDimension-m_ObjectDimension)); objectnessMeasure *= vcl_exp(- 0.5 * vnl_math_sqr(rB) / vnl_math_sqr(m_Beta)); } else @@ -174,13 +174,12 @@ HessianToObjectnessMeasureImageFilter< TInputImage, TOutputImage> } } - double frobeniusNorm = 0.0; + double frobeniusNormSquared = 0.0; for (unsigned int i=0; i<ImageDimension; i++) { - frobeniusNorm += vnl_math_sqr(sortedAbsEigenValues[i]); + frobeniusNormSquared += vnl_math_sqr(sortedAbsEigenValues[i]); } - frobeniusNorm = vcl_sqrt(frobeniusNorm); - objectnessMeasure *= 1.0 - vcl_exp(- 0.5 * vnl_math_sqr(frobeniusNorm) / vnl_math_sqr(m_Gamma)); + objectnessMeasure *= 1.0 - vcl_exp(- 0.5 * frobeniusNormSquared / vnl_math_sqr(m_Gamma)); // in case, scale by largest absolute eigenvalue if (m_ScaleObjectnessMeasure) diff --git a/Utilities/ITK/Code/Review/itkHotColormapFunctor.h b/Utilities/ITK/Code/Review/itkHotColormapFunctor.h new file mode 100644 index 0000000000..41d7c5662e --- /dev/null +++ b/Utilities/ITK/Code/Review/itkHotColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHotColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkHotColormapFunctor_h +#define __itkHotColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class HotColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT HotColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef HotColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + HotColormapFunctor() {}; + ~HotColormapFunctor() {}; + +private: + HotColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkHotColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkHotColormapFunctor.txx b/Utilities/ITK/Code/Review/itkHotColormapFunctor.txx new file mode 100644 index 0000000000..8669fcca9e --- /dev/null +++ b/Utilities/ITK/Code/Review/itkHotColormapFunctor.txx @@ -0,0 +1,62 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkHotColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkHotColormapFunctor_txx +#define __itkHotColormapFunctor_txx + +#include "itkHotColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename HotColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +HotColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color mapping. + RealType red = 63.0/26.0 * value - 1.0/13.0; + red = vnl_math_max( 0.0, red ); + red = vnl_math_min( 1.0, red ); + + RealType green = 63.0/26.0 * value - 11.0/13.0; + green = vnl_math_max( 0.0, green ); + green = vnl_math_min( 1.0, green ); + + RealType blue = 4.5 * value - 3.5; + blue = vnl_math_max( 0.0, blue ); + blue = vnl_math_min( 1.0, blue ); + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkJetColormapFunctor.h b/Utilities/ITK/Code/Review/itkJetColormapFunctor.h new file mode 100644 index 0000000000..d7339becbe --- /dev/null +++ b/Utilities/ITK/Code/Review/itkJetColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkJetColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkJetColormapFunctor_h +#define __itkJetColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class JetColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT JetColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef JetColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + JetColormapFunctor() {}; + ~JetColormapFunctor() {}; + +private: + JetColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkJetColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkJetColormapFunctor.txx b/Utilities/ITK/Code/Review/itkJetColormapFunctor.txx new file mode 100644 index 0000000000..7559306d24 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkJetColormapFunctor.txx @@ -0,0 +1,62 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkJetColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkJetColormapFunctor_txx +#define __itkJetColormapFunctor_txx + +#include "itkJetColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename JetColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +JetColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color mapping. + RealType red = -vnl_math_abs( 3.75 * ( value - 0.75 ) ) + 1.625; + red = vnl_math_min( red, 1.0 ); + red = vnl_math_max( 0.0, red ); + + RealType green = -vnl_math_abs( 3.75 * ( value - 0.5 ) ) + 1.625; + green = vnl_math_min( green, 1.0 ); + green = vnl_math_max( 0.0, green ); + + RealType blue = -vnl_math_abs( 3.75 * ( value - 0.25 ) ) + 1.625; + blue = vnl_math_min( blue, 1.0 ); + blue = vnl_math_max( 0.0, blue ); + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkKappaSigmaThresholdImageCalculator.h b/Utilities/ITK/Code/Review/itkKappaSigmaThresholdImageCalculator.h index 749a28b552..51e7a951f1 100644 --- a/Utilities/ITK/Code/Review/itkKappaSigmaThresholdImageCalculator.h +++ b/Utilities/ITK/Code/Review/itkKappaSigmaThresholdImageCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKappaSigmaThresholdImageCalculator.h,v $ Language: C++ - Date: $Date: 2008-09-29 18:36:38 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -75,13 +75,13 @@ public: itkSetConstObjectMacro( Mask, MaskImageType ); itkSetMacro(MaskValue, MaskPixelType); - itkGetMacro(MaskValue, MaskPixelType); + itkGetConstMacro(MaskValue, MaskPixelType); itkSetMacro(SigmaFactor, double); - itkGetMacro(SigmaFactor, double); + itkGetConstMacro(SigmaFactor, double); itkSetMacro(NumberOfIterations, unsigned int); - itkGetMacro(NumberOfIterations, unsigned int); + itkGetConstMacro(NumberOfIterations, unsigned int); /** Compute moments of a new or modified image. * This method computes the moments of the image given as a diff --git a/Utilities/ITK/Code/Review/itkKappaSigmaThresholdImageFilter.h b/Utilities/ITK/Code/Review/itkKappaSigmaThresholdImageFilter.h index 23d1f62c65..9901bab199 100644 --- a/Utilities/ITK/Code/Review/itkKappaSigmaThresholdImageFilter.h +++ b/Utilities/ITK/Code/Review/itkKappaSigmaThresholdImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKappaSigmaThresholdImageFilter.h,v $ Language: C++ - Date: $Date: 2008-07-10 20:47:22 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -83,26 +83,26 @@ public: itkSetMacro(OutsideValue,OutputPixelType); /** Get the "outside" pixel value. */ - itkGetMacro(OutsideValue,OutputPixelType); + itkGetConstMacro(OutsideValue,OutputPixelType); /** Set the "inside" pixel value. The default value * NumericTraits<OutputPixelType>::max() */ itkSetMacro(InsideValue,OutputPixelType); /** Get the "inside" pixel value. */ - itkGetMacro(InsideValue,OutputPixelType); + itkGetConstMacro(InsideValue,OutputPixelType); /** Get the computed threshold. */ - itkGetMacro(Threshold,InputPixelType); + itkGetConstMacro(Threshold,InputPixelType); itkSetMacro(MaskValue, MaskPixelType); - itkGetMacro(MaskValue, MaskPixelType); + itkGetConstMacro(MaskValue, MaskPixelType); itkSetMacro(SigmaFactor, double); - itkGetMacro(SigmaFactor, double); + itkGetConstMacro(SigmaFactor, double); itkSetMacro(NumberOfIterations, unsigned int); - itkGetMacro(NumberOfIterations, unsigned int); + itkGetConstMacro(NumberOfIterations, unsigned int); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Review/itkLabelContourImageFilter.h b/Utilities/ITK/Code/Review/itkLabelContourImageFilter.h index e6e0ebfb86..0ea2f29e8f 100644 --- a/Utilities/ITK/Code/Review/itkLabelContourImageFilter.h +++ b/Utilities/ITK/Code/Review/itkLabelContourImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelContourImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-14 22:00:53 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -135,7 +135,7 @@ public: * pixels not on the border of the objects. */ itkSetMacro(BackgroundValue, OutputImagePixelType); - itkGetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); protected: LabelContourImageFilter() diff --git a/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.h b/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.h new file mode 100644 index 0000000000..31d5eccc50 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.h @@ -0,0 +1,119 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelImageToLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-14 21:08:43 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelImageToLabelMapFilter_h +#define __itkLabelImageToLabelMapFilter_h + +#include "itkImageToImageFilter.h" +#include "itkLabelMap.h" +#include "itkLabelObject.h" + +namespace itk { + +/** \class LabelImageToLabelMapFilter + * \brief convert a labeled image to a label collection image + * + * LabelImageToLabelMapFilter converts a label image to a label collection image. + * The labels are the same in the input and the output image. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa BinaryImageToLabelMapFilter, LabelMapToLabelImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TOutputImage=LabelMap< LabelObject< typename TInputImage::PixelType, ::itk::GetImageDimension<TInputImage>::ImageDimension::ImageDimension > > > +class ITK_EXPORT LabelImageToLabelMapFilter : + public ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelImageToLabelMapFilter Self; + typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::IndexType IndexType; + + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + typedef typename OutputImageType::LabelObjectType LabelObjectType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TOutputImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelImageToLabelMapFilter, + ImageToImageFilter); + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + +protected: + LabelImageToLabelMapFilter(); + ~LabelImageToLabelMapFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** LabelImageToLabelMapFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** LabelImageToLabelMapFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + virtual void BeforeThreadedGenerateData(); + + virtual void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); + + virtual void AfterThreadedGenerateData(); + + +private: + LabelImageToLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + + typename std::vector< OutputImagePointer > m_TemporaryImages; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelImageToLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.txx new file mode 100644 index 0000000000..13e78a3bf4 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.txx @@ -0,0 +1,187 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelImageToLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-14 19:31:40 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelImageToLabelMapFilter_txx +#define __itkLabelImageToLabelMapFilter_txx + +#include "itkLabelImageToLabelMapFilter.h" +#include "itkNumericTraits.h" +#include "itkProgressReporter.h" +#include "itkImageLinearConstIteratorWithIndex.h" + +namespace itk { + +template <class TInputImage, class TOutputImage> +LabelImageToLabelMapFilter<TInputImage, TOutputImage> +::LabelImageToLabelMapFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); +} + +template <class TInputImage, class TOutputImage> +void +LabelImageToLabelMapFilter<TInputImage, TOutputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if ( !input ) + { return; } + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); +} + + +template <class TInputImage, class TOutputImage> +void +LabelImageToLabelMapFilter<TInputImage, TOutputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TOutputImage> +void +LabelImageToLabelMapFilter<TInputImage, TOutputImage> +::BeforeThreadedGenerateData() +{ + // init the temp images - one per thread + m_TemporaryImages.resize( this->GetNumberOfThreads() ); + + for( int i=0; i<this->GetNumberOfThreads(); i++ ) + { + if( i == 0 ) + { + // the first one is the output image + m_TemporaryImages[0] = this->GetOutput(); + } + else + { + // the other must be created + m_TemporaryImages[i] = OutputImageType::New(); + } + + // set the minimum data needed to create the objects properly + m_TemporaryImages[i]->SetBackgroundValue( m_BackgroundValue ); + + } +} + + +template<class TInputImage, class TOutputImage> +void +LabelImageToLabelMapFilter<TInputImage, TOutputImage> +::ThreadedGenerateData( const OutputImageRegionType& regionForThread, int threadId ) +{ + ProgressReporter progress( this, threadId, regionForThread.GetNumberOfPixels() ); + + typedef ImageLinearConstIteratorWithIndex< InputImageType > InputLineIteratorType; + InputLineIteratorType it( this->GetInput(), regionForThread ); + it.SetDirection(0); + + for( it.GoToBegin(); !it.IsAtEnd(); it.NextLine() ) + { + + it.GoToBeginOfLine(); + + while( !it.IsAtEndOfLine() ) + { + const InputImagePixelType & v = it.Get(); + + if( v != m_BackgroundValue ) + { + // We've hit the start of a run + IndexType idx = it.GetIndex(); + long length=1; + ++it; + while( !it.IsAtEndOfLine() && it.Get() == v ) + { + ++length; + ++it; + } + // create the run length object to go in the vector + m_TemporaryImages[threadId]->SetLine( idx, length, v ); + } + else + { + // go the the next pixel + ++it; + } + } + + } + +} + + +template<class TInputImage, class TOutputImage> +void +LabelImageToLabelMapFilter<TInputImage, TOutputImage> +::AfterThreadedGenerateData() +{ + + OutputImageType * output = this->GetOutput(); + + // merge the lines from the temporary images in the output image + // don't use the first image - that's the output image + for( int i=1; i<this->GetNumberOfThreads(); i++ ) + { + typedef typename OutputImageType::LabelObjectContainerType LabelObjectContainerType; + const LabelObjectContainerType & labelObjectContainer = m_TemporaryImages[i]->GetLabelObjectContainer(); + + for( typename LabelObjectContainerType::const_iterator it = labelObjectContainer.begin(); + it != labelObjectContainer.end(); + it++ ) + { + LabelObjectType * labelObject = it->second; + if( output->HasLabel( labelObject->GetLabel() ) ) + { + // merge the lines in the output's object + typename LabelObjectType::LineContainerType & src = labelObject->GetLineContainer(); + typename LabelObjectType::LineContainerType & dest = output->GetLabelObject( labelObject->GetLabel() )->GetLineContainer(); + dest.insert( dest.end(), src.begin(), src.end() ); + } + else + { + // simply take the object + output->AddLabelObject( labelObject ); + } + } + + } + + // release the data in the temp images + m_TemporaryImages.clear(); + +} + + +template<class TInputImage, class TOutputImage> +void +LabelImageToLabelMapFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelMap.h b/Utilities/ITK/Code/Review/itkLabelMap.h new file mode 100644 index 0000000000..fe7170c53a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelMap.h @@ -0,0 +1,291 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelMap.h,v $ + Language: C++ + Date: $Date: 2009-05-14 21:08:43 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelMap_h +#define __itkLabelMap_h + +#include "itkImageBase.h" +#include "itkImageRegion.h" +#include "itkFixedArray.h" +#include "itkWeakPointer.h" +#include <map> + +namespace itk +{ +/** \class LabelMap + * \brief Templated n-dimensional image to store labeled objects. + * + * LabelMap is an image class specialized in storing the labeled + * images. It represent the image in a different way than itk::Image. + * Instead of storing the content of the image in an array of pixels values, + * it store the a collection of labeled objects, and a background + * value. + * This way of storing the content of the image allow an easy and efficient + * manipulation of the objects in the image. + * + * The LabelMap shares a lot of methods with the itk::Image class. + * it make it usable as input or output of the itk::ImageToImageFilter for example. + * However the methods don't have the same complexity in the 2 classes, because + * of the different way to store the data. GetPixel() is run in constant time + * for example in itk::Image, but have a worst case complexity of O(L), where + * L is the number of lines in the image (imageSize[1] * imageSize[2] for a 3D + * image). + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \ingroup ImageObjects + * \ingroup LabeledImageObject + */ +template <class TLabelObject > +class ITK_EXPORT LabelMap : public ImageBase< ::itk::GetImageDimension<TLabelObject>::ImageDimension> +{ +public: + /** Standard class typedefs */ + typedef LabelMap Self; + typedef ImageBase< ::itk::GetImageDimension<TLabelObject>::ImageDimension> + Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef WeakPointer<const Self> ConstWeakPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(LabelMap, ImageBase); + + typedef TLabelObject LabelObjectType; + + typedef typename LabelObjectType::Pointer LabelObjectPointerType; + + /** Dimension of the image. This constant is used by functions that are + * templated over image type (as opposed to being templated over pixel type + * and dimension) when they need compile time access to the dimension of + * the image. */ + itkStaticConstMacro(ImageDimension, unsigned int, LabelObjectType::ImageDimension); + + /** Label typedef support. */ + typedef typename LabelObjectType::LabelType LabelType; + typedef LabelType PixelType; + + /** the LabelObject container type */ + typedef std::map< LabelType, LabelObjectPointerType > LabelObjectContainerType; + + /** types used to expose labels only and label objects only */ + typedef std::vector< LabelType > LabelVectorType; + typedef std::vector< LabelObjectPointerType > LabelObjectVectorType; + + /** Index typedef support. An index is used to access pixel values. */ + typedef typename Superclass::IndexType IndexType; + + /** Offset typedef support. An offset is used to access pixel values. */ + typedef typename Superclass::OffsetType OffsetType; + + /** Size typedef support. A size is used to define region bounds. */ + typedef typename Superclass::SizeType SizeType; + + /** Direction typedef support. A matrix of direction cosines. */ + typedef typename Superclass::DirectionType DirectionType; + + /** Region typedef support. A region is used to specify a subset of an image. */ + typedef typename Superclass::RegionType RegionType; + + /** Spacing typedef support. Spacing holds the size of a pixel. The + * spacing is the geometric distance between image samples. */ + typedef typename Superclass::SpacingType SpacingType; + + /** Origin typedef support. The origin is the geometric coordinates + * of the index (0,0). */ + typedef typename Superclass::PointType PointType; + + /** Offset typedef (relative position between indices) */ + typedef typename Superclass::OffsetValueType OffsetValueType; + + /** Convenience methods to set the LargestPossibleRegion, + * BufferedRegion and RequestedRegion. Allocate must still be called. + */ + void SetRegions( const RegionType & region ) + { + this->SetLargestPossibleRegion(region); + this->SetBufferedRegion(region); + this->SetRequestedRegion(region); + } + + void SetRegions( const SizeType & size ) + { + RegionType region; region.SetSize(size); + this->SetLargestPossibleRegion(region); + this->SetBufferedRegion(region); + this->SetRequestedRegion(region); + } + + /** Restore the data object to its initial state. This means releasing + * memory. */ + virtual void Initialize(); + + /** */ + virtual void Allocate(); + + virtual void Graft(const DataObject *data); + + /** + * Return the LabelObject with the label given in parameter. + * This method thorws an exception if the label doesn't exist in this image, + * or if the label is the background one. + */ + LabelObjectType * GetLabelObject( const LabelType & label ); + + const LabelObjectType * GetLabelObject( const LabelType & label ) const; + + /** + * Return true is the image contains the label given in parameter and false + * otherwise. If the label is the background one, true is also returned, so + * this method may not be a good enough test before calling GetLabelObject(). + */ + bool HasLabel( const LabelType label ) const; + + /** + * Return the LabelObject with at the position given in parameter. + * This method can be useful when the labels are not consecutives, but is quite + * inefficient. + * This method thorws an exception if the index doesn't exist in this image. + */ + LabelObjectType * GetNthLabelObject( const unsigned long & pos ); + + const LabelObjectType * GetNthLabelObject( const unsigned long & pos ) const; + + /** + * Return the pixel value at a given index in the image. This method + * has a worst case complexity of O(L) where L is the number of lines in the + * image - use it with care. + */ + const LabelType & GetPixel( const IndexType & idx ) const; + + /** + * Set the pixel value at a given index in the image. + * If no label object has this pixel value, a new label object is created. If + * a label object already exist, the index is added to it. + * The worst case complexity of this method is O(L) where L is the number of + * lines in the image. However, the execution time will be quite low if the + * pixels are set in the image in raster mode. + */ + void SetPixel( const IndexType & idx, const LabelType & label ); + + /** + * Set a full line in the image. If no label object has this label in the image, + * a new object is created. If a label object already exist with that label, the + * line is added to it WITHOUT any check - it means that if the label object may + * contain several time the same pixel after have run that method. + * This method runs in constant time. + */ + void SetLine( const IndexType & idx, const unsigned long & length, const LabelType & label ); + + /** + * Return the label object at a given index. This method + * has a worst case complexity of O(L) where L is the number of lines in the + * image - use it with care. + */ + LabelObjectType * GetLabelObject( const IndexType & idx ) const; + + /** + * Add a label object to the image. If a label object already has the label, + * it is overiden. + */ + void AddLabelObject( LabelObjectType * labelObject ); + + /** + * Add a label object to the image. The label of the label object is + * ignored, and a new label is given to the label object. + */ + void PushLabelObject( LabelObjectType * labelObject ); + + /** + * Remove a label object. + */ + void RemoveLabelObject( LabelObjectType * labelObject ); + + /** + * Remove a label object. + */ + void RemoveLabel( const LabelType & label ); + + /** + * Remove all the labels in the image + */ + void ClearLabels(); + + /** + * Return the label object container + */ + const LabelObjectContainerType & GetLabelObjectContainer() const; + LabelObjectContainerType & GetLabelObjectContainer(); + + /** + * Return the numbner of label objects in the image + */ + unsigned long GetNumberOfLabelObjects() const; + + /** + * Return the labels of the label objects available in the label map + */ + LabelVectorType GetLabels() const; + + /** + * Return the the label objects available in the label map + */ + LabelObjectVectorType GetLabelObjects() const; + + /** + * Set/Get the background label + */ + itkGetConstMacro(BackgroundValue, LabelType); + itkSetMacro(BackgroundValue, LabelType); + + /** + * Print all the objects stored in that collection - a convenient method + * for prototyping. + */ + void PrintLabelObjects(std::ostream& os) const; + void PrintLabelObjects() const + { + this->PrintLabelObjects( std::cerr ); + } + +protected: + LabelMap(); + virtual ~LabelMap() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + LabelMap(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + LabelObjectContainerType m_LabelObjectContainer; + LabelType m_BackgroundValue; +}; + +} // end namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +# include "itkLabelMap.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelMap.txx b/Utilities/ITK/Code/Review/itkLabelMap.txx new file mode 100644 index 0000000000..0671040d64 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelMap.txx @@ -0,0 +1,507 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelMap.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 17:47:34 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelMap_txx +#define __itkLabelMap_txx + +#include "itkLabelMap.h" +#include "itkProcessObject.h" + +namespace itk +{ + +/** + * + */ +template<class TLabelObject > +LabelMap<TLabelObject> +::LabelMap() +{ + m_BackgroundValue = NumericTraits< LabelType >::Zero; + this->Initialize(); +} + + +/** + * + */ +template<class TLabelObject > +void +LabelMap<TLabelObject> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<LabelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "LabelObjectContainer: " << & m_LabelObjectContainer << std::endl; +} + + +/** + * + */ +template<class TLabelObject > +void +LabelMap<TLabelObject> +::Initialize() +{ + m_LabelObjectContainer.clear(); +} + + +/** + * + */ +template<class TLabelObject > +void +LabelMap<TLabelObject> +::Allocate() +{ + this->Initialize(); +} + +template<class TLabelObject > +void +LabelMap<TLabelObject> +::Graft(const DataObject *data) +{ + // call the superclass' implementation + Superclass::Graft( data ); + + if ( data ) + { + // Attempt to cast data to an Image + const Self * imgData; + + try + { + imgData = dynamic_cast<const Self *>( data ); + } + catch( ... ) + { + return; + } + + + if ( imgData ) + { + // Now copy anything remaining that is needed + m_LabelObjectContainer = imgData->m_LabelObjectContainer; + m_BackgroundValue = imgData->m_BackgroundValue; + } + else + { + // pointer could not be cast back down + itkExceptionMacro( << "itk::Image::Graft() cannot cast " + << typeid(data).name() << " to " + << typeid(const Self *).name() ); + } + } +} + + +template<class TLabelObject > +typename LabelMap<TLabelObject>::LabelObjectType * +LabelMap<TLabelObject> +::GetLabelObject( const LabelType & label ) +{ + if( ! this->HasLabel( label ) ) + { + itkExceptionMacro( << "No label object with label " + << static_cast<typename NumericTraits< LabelType >::PrintType>(label) + << "." ); + } + if( m_BackgroundValue == label ) + { + itkExceptionMacro( << "Label " + << static_cast<typename NumericTraits< LabelType >::PrintType>(label) + << " is the background label." ); + } + return m_LabelObjectContainer[label].GetPointer(); +} + + +template<class TLabelObject > +const typename LabelMap<TLabelObject>::LabelObjectType * +LabelMap<TLabelObject> +::GetLabelObject( const LabelType & label ) const +{ + if( ! this->HasLabel( label ) ) + { + itkExceptionMacro( << "No label object with label " + << static_cast<typename NumericTraits< LabelType >::PrintType>(label) + << "." ); + } + if( m_BackgroundValue == label ) + { + itkExceptionMacro( << "Label " + << static_cast<typename NumericTraits< LabelType >::PrintType>(label) + << " is the background label." ); + } + return m_LabelObjectContainer.find( label )->second.GetPointer(); +} + + +template<class TLabelObject > +bool +LabelMap<TLabelObject> +::HasLabel( const LabelType label ) const +{ + if( label == m_BackgroundValue ) + { + return true; + } + return m_LabelObjectContainer.find( label ) != m_LabelObjectContainer.end(); +} + + +template<class TLabelObject > +const typename LabelMap<TLabelObject>::LabelType & +LabelMap<TLabelObject> +::GetPixel( const IndexType & idx ) const +{ + for( typename LabelObjectContainerType::const_iterator it = m_LabelObjectContainer.begin(); + it != m_LabelObjectContainer.end(); + it++ ) + { + if( it->second->HasIndex( idx ) ) + { + return it->second->GetLabel(); + } + } + return m_BackgroundValue; +} + + +template<class TLabelObject > +typename LabelMap<TLabelObject>::LabelObjectType * +LabelMap<TLabelObject> +::GetNthLabelObject( const unsigned long & pos ) +{ + unsigned long i = 0; + for( typename LabelObjectContainerType::iterator it = m_LabelObjectContainer.begin(); + it != m_LabelObjectContainer.end(); + it++ ) + { + if( i == pos ) + { + return it->second; + } + i++; + } + itkExceptionMacro( << "Can't access to label object at position " + << pos + << ". The label map has only " + << this->GetNumberOfLabelObjects() + << " label objects registered." ); +} + + +template<class TLabelObject > +const typename LabelMap<TLabelObject>::LabelObjectType * +LabelMap<TLabelObject> +::GetNthLabelObject( const unsigned long & pos ) const +{ + unsigned long i = 0; + for( typename LabelObjectContainerType::const_iterator it = m_LabelObjectContainer.begin(); + it != m_LabelObjectContainer.end(); + it++ ) + { + if( i == pos ) + { + return it->second; + } + i++; + } + itkExceptionMacro( << "Can't access to label object at position " + << pos + << ". The label map has only " + << this->GetNumberOfLabelObjects() + << " label objects registered." ); +} + + +template<class TLabelObject > +void +LabelMap<TLabelObject> +::SetPixel( const IndexType & idx, const LabelType & label ) +{ + if( label == m_BackgroundValue ) + { + // just do nothing + return; + } + + typename LabelObjectContainerType::iterator it = m_LabelObjectContainer.find( label ); + + if( it != m_LabelObjectContainer.end() ) + { + // the label already exist - add the pixel to it + (*it).second->AddIndex( idx ); + } + else + { + // the label does not exist yet - create a new one + LabelObjectPointerType labelObject = LabelObjectType::New(); + labelObject->SetLabel( label ); + labelObject->AddIndex( idx ); + this->AddLabelObject( labelObject ); +// std::cout<< m_LabelObjectContainer.size() << std::endl; + } + +} + + +template<class TLabelObject > +void +LabelMap<TLabelObject> +::SetLine( const IndexType & idx, const unsigned long & length, const LabelType & label ) +{ + if( label == m_BackgroundValue ) + { + // just do nothing + return; + } + + typename LabelObjectContainerType::iterator it = m_LabelObjectContainer.find( label ); + + if( it != m_LabelObjectContainer.end() ) + { + // the label already exist - add the pixel to it + (*it).second->AddLine( idx, length ); + } + else + { + // the label does not exist yet - create a new one + LabelObjectPointerType labelObject = LabelObjectType::New(); + labelObject->SetLabel( label ); + labelObject->AddLine( idx, length ); + this->AddLabelObject( labelObject ); +// std::cout<< m_LabelObjectContainer.size() << std::endl; + } +} + + +template<class TLabelObject > +typename LabelMap<TLabelObject>::LabelObjectType * +LabelMap<TLabelObject> +::GetLabelObject( const IndexType & idx ) const +{ + for( typename LabelObjectContainerType::const_iterator it = m_LabelObjectContainer.begin(); + it != m_LabelObjectContainer.end(); + it++ ) + { + if( it->second->HasIndex( idx ) ) + { + return it->second.GetPointer(); + } + } + itkExceptionMacro( << "No label object at index " << idx << "." ); +// return NULL; +} + + +template<class TLabelObject > +void +LabelMap<TLabelObject> +::AddLabelObject( LabelObjectType * labelObject ) +{ + itkAssertOrThrowMacro( (labelObject != NULL), "LabelObject Null" ); + itkAssertOrThrowMacro( (!this->HasLabel( labelObject->GetLabel() )), "Label Not Found" ); + + m_LabelObjectContainer[ labelObject->GetLabel() ] = labelObject; +} + + +template<class TLabelObject > +void +LabelMap<TLabelObject> +::PushLabelObject( LabelObjectType * labelObject ) +{ + itkAssertOrThrowMacro( (labelObject != NULL), "LabelObject Null" ); + + if( m_LabelObjectContainer.empty() ) + { + if( m_BackgroundValue == 0 ) + { + labelObject->SetLabel( 1 ); + } + else + { + labelObject->SetLabel( 0 ); + } + } + else + { + LabelType lastLabel = m_LabelObjectContainer.rbegin()->first; + LabelType firstLabel = m_LabelObjectContainer.begin()->first; + if( lastLabel != NumericTraits< LabelType >::max() && lastLabel + 1 != m_BackgroundValue ) + { + labelObject->SetLabel( lastLabel + 1 ); + } + else if( lastLabel != NumericTraits< LabelType >::max() && lastLabel + 1 != NumericTraits< LabelType >::max() && lastLabel + 2 != m_BackgroundValue ) + { + labelObject->SetLabel( lastLabel + 2 ); + } + else if( firstLabel != NumericTraits< LabelType >::NonpositiveMin() && firstLabel - 1 != m_BackgroundValue ) + { + labelObject->SetLabel( firstLabel - 1 ); + } + else + { + // search for an unused label + LabelType label = firstLabel; + typename LabelObjectContainerType::const_iterator it; + for( it = m_LabelObjectContainer.begin(); + it != m_LabelObjectContainer.end(); + it++, label++ ) + { + itkAssertOrThrowMacro( (it->second.IsNotNull()), "Null label" ); + if( label == m_BackgroundValue ) + { + label++; + } + if( label != it->first ) + { + labelObject->SetLabel( label ); + break; + } + } + if( label == lastLabel ) + { + itkExceptionMacro( << "Can't push the label object: the label map is full." ); + } + } + } + this->AddLabelObject( labelObject ); +} + + +template<class TLabelObject > +void +LabelMap<TLabelObject> +::RemoveLabelObject( LabelObjectType * labelObject ) +{ + itkAssertOrThrowMacro( (labelObject != NULL), "LabelObject Null" ); + this->RemoveLabel( labelObject->GetLabel() ); +} + + +template<class TLabelObject > +void +LabelMap<TLabelObject> +::RemoveLabel( const LabelType & label ) +{ + if( label == m_BackgroundValue ) + { + // just do nothing + return; + } + m_LabelObjectContainer.erase( label ); +} + + +template<class TLabelObject > +void +LabelMap<TLabelObject> +::ClearLabels() +{ + m_LabelObjectContainer.clear(); +} + + +template<class TLabelObject > +const typename LabelMap<TLabelObject>::LabelObjectContainerType & +LabelMap<TLabelObject> +::GetLabelObjectContainer() const +{ + return m_LabelObjectContainer; +} + + +template<class TLabelObject > +typename LabelMap<TLabelObject>::LabelObjectContainerType & +LabelMap<TLabelObject> +::GetLabelObjectContainer() +{ + return m_LabelObjectContainer; +} + + +template<class TLabelObject > +unsigned long +LabelMap<TLabelObject> +::GetNumberOfLabelObjects() const +{ + return m_LabelObjectContainer.size(); +} + + +template<class TLabelObject > +typename LabelMap<TLabelObject>::LabelVectorType +LabelMap<TLabelObject> +::GetLabels() const +{ + LabelVectorType res; + res.reserve( this->GetNumberOfLabelObjects() ); + for( typename LabelObjectContainerType::const_iterator it = m_LabelObjectContainer.begin(); + it != m_LabelObjectContainer.end(); + it++ ) + { + res.push_back( it->first ); + } + return res; +} + + +template<class TLabelObject > +typename LabelMap<TLabelObject>::LabelObjectVectorType +LabelMap<TLabelObject> +::GetLabelObjects() const +{ + LabelObjectVectorType res; + res.reserve( this->GetNumberOfLabelObjects() ); + for( typename LabelObjectContainerType::const_iterator it = m_LabelObjectContainer.begin(); + it != m_LabelObjectContainer.end(); + it++ ) + { + res.push_back( it->second ); + } + return res; +} + + +template<class TLabelObject > +void +LabelMap<TLabelObject> +::PrintLabelObjects(std::ostream& os) const +{ + for( typename LabelObjectContainerType::const_iterator it = m_LabelObjectContainer.begin(); + it != m_LabelObjectContainer.end(); + it++ ) + { + itkAssertOrThrowMacro( (it->second.IsNotNull()), "Null label" ); + it->second->Print( os ); + os << std::endl; + } +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelMapFilter.h b/Utilities/ITK/Code/Review/itkLabelMapFilter.h new file mode 100644 index 0000000000..1d0dfa55a9 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelMapFilter.h @@ -0,0 +1,132 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-16 22:19:30 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelMapFilter_h +#define __itkLabelMapFilter_h + +#include "itkImageToImageFilter.h" +#include "itkProgressReporter.h" + +namespace itk +{ + +/** \class LabelMapFilter + * \brief Base class for filters that take an image as input and overwrite that image as the output + * + * LabelMapFilter is the base class for all process objects whose + * are using a LabelMapFilter as input. It manage several threads, + * and run a method ThreadedGenerateData() for each object in the LabelMapFilter. + * With that class, the developer doesn't need to take care of iterating over all the objects in + * the image, or to manage by hand the threads. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa LabelMapToBinaryImageFilter, LabelMapToLabelImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + * \ingroup LabeledImageFilters + */ +template <class TInputImage, class TOutputImage> +class ITK_EXPORT LabelMapFilter : public ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelMapFilter Self; + typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + + /** Run-time type information (and related methods). */ + itkTypeMacro(LabelMapFilter,ImageToImageFilter); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::LabelObjectType LabelObjectType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TOutputImage::ImageDimension); + + /** LabelMapFilter requires the entire input to be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** LabelMapFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + +protected: + LabelMapFilter(); + ~LabelMapFilter(); + + virtual void BeforeThreadedGenerateData(); + + virtual void AfterThreadedGenerateData(); + + virtual void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); + + virtual void ThreadedProcessLabelObject( LabelObjectType * labelObject ); + + /** + * Return the label collection image to use. This method may be overloaded + * if the label collection image to use is not the input image. + */ + virtual InputImageType * GetLabelMap() + { + return static_cast<InputImageType*>(const_cast<DataObject *>(this->ProcessObject::GetInput(0))); + } + + typename FastMutexLock::Pointer m_LabelObjectContainerLock; + +private: + LabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + typename InputImageType::LabelObjectContainerType::const_iterator m_LabelObjectIterator; + + ProgressReporter * m_Progress; + +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkLabelMapFilter.txx new file mode 100644 index 0000000000..24f570568f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelMapFilter.txx @@ -0,0 +1,160 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-16 22:19:31 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelMapFilter_txx +#define __itkLabelMapFilter_txx +#include "itkLabelMapFilter.h" +#include "itkProgressReporter.h" + + +namespace itk +{ + +/** + * + */ +template <class TInputImage, class TOutputImage> +LabelMapFilter<TInputImage, TOutputImage> +::LabelMapFilter() +{ + m_Progress = NULL; +} + +/** + * + */ +template <class TInputImage, class TOutputImage> +LabelMapFilter<TInputImage, TOutputImage> +::~LabelMapFilter() +{ + // be sure that the progress reporter has been destroyed + if( m_Progress != NULL ) + { + delete m_Progress; + } +} + + +template <class TInputImage, class TOutputImage> +void +LabelMapFilter<TInputImage, TOutputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + + if ( !input ) + { return; } + + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); +} + + +template <class TInputImage, class TOutputImage> +void +LabelMapFilter<TInputImage, TOutputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template <class TInputImage, class TOutputImage> +void +LabelMapFilter<TInputImage, TOutputImage> +::BeforeThreadedGenerateData() +{ + // initialize the iterator + m_LabelObjectIterator = this->GetLabelMap()->GetLabelObjectContainer().begin(); + + // and the mutex + m_LabelObjectContainerLock = FastMutexLock::New(); + + // be sure that the previous progress reporter has been destroyed + if( m_Progress != NULL ) + { + delete m_Progress; + } + // initialize the progress reporter + m_Progress = new ProgressReporter(this, 0, this->GetLabelMap()->GetNumberOfLabelObjects()); +} + + +template <class TInputImage, class TOutputImage> +void +LabelMapFilter<TInputImage, TOutputImage> +::AfterThreadedGenerateData() +{ + // destroy progress reporter + delete m_Progress; + m_Progress = NULL; +} + + +template <class TInputImage, class TOutputImage> +void +LabelMapFilter<TInputImage, TOutputImage> +::ThreadedGenerateData( const OutputImageRegionType&, int itkNotUsed(threadId) ) +{ + while( true ) + { + // first lock the mutex + m_LabelObjectContainerLock->Lock(); + + if( m_LabelObjectIterator == this->GetLabelMap()->GetLabelObjectContainer().end() ) + { + // no more objects. Release the lock and return + m_LabelObjectContainerLock->Unlock(); + return; + } + + // get the label object + LabelObjectType * labelObject = m_LabelObjectIterator->second; + + // increment the iterator now, so it will not be invalidated if the object is destroyed + m_LabelObjectIterator++; + + // pretend one more object is processed, even if it will be done later, to simplify the lock management + m_Progress->CompletedPixel(); + + // unlock the mutex, so the other threads can get an object + m_LabelObjectContainerLock->Unlock(); + + // and run the user defined method for that object + this->ThreadedProcessLabelObject( labelObject ); + } +} + + +template <class TInputImage, class TOutputImage> +void +LabelMapFilter<TInputImage, TOutputImage> +::ThreadedProcessLabelObject( LabelObjectType * itkNotUsed(labelObject) ) +{ + // do nothing + // the subclass should override this method +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.h b/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.h new file mode 100644 index 0000000000..377a2edbea --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.h @@ -0,0 +1,98 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelMapToLabelImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-16 22:19:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelMapToLabelImageFilter_h +#define __itkLabelMapToLabelImageFilter_h + +#include "itkLabelMapFilter.h" + +namespace itk { + +/** \class LabelMapToLabelImageFilter + * \brief Convert a LabelMap to a labeled image + * + * LabelMapToBinaryImageFilter to a label image. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa LabelMapToBinaryImageFilter, LabelMapMaskImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + * \ingroup LabeledImageFilters + */ +template<class TInputImage, class TOutputImage> +class ITK_EXPORT LabelMapToLabelImageFilter : + public LabelMapFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelMapToLabelImageFilter Self; + typedef LabelMapFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::LabelObjectType LabelObjectType; + + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + typedef typename OutputImageType::IndexType IndexType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TOutputImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelMapToLabelImageFilter, + ImageToImageFilter); + +protected: + LabelMapToLabelImageFilter(); + ~LabelMapToLabelImageFilter() {}; + + virtual void BeforeThreadedGenerateData(); + + virtual void ThreadedProcessLabelObject( LabelObjectType * labelObject ); + +private: + LabelMapToLabelImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelMapToLabelImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.txx b/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.txx new file mode 100644 index 0000000000..017e92f850 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.txx @@ -0,0 +1,72 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelMapToLabelImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-16 22:19:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelMapToLabelImageFilter_txx +#define __itkLabelMapToLabelImageFilter_txx + +#include "itkLabelMapToLabelImageFilter.h" +#include "itkNumericTraits.h" +#include "itkProgressReporter.h" +#include "itkImageRegionConstIteratorWithIndex.h" + +namespace itk { + +template <class TInputImage, class TOutputImage> +LabelMapToLabelImageFilter<TInputImage, TOutputImage> +::LabelMapToLabelImageFilter() +{ +} + + +template<class TInputImage, class TOutputImage> +void +LabelMapToLabelImageFilter<TInputImage, TOutputImage> +::BeforeThreadedGenerateData() +{ + OutputImageType * output = this->GetOutput(); + const InputImageType * input = this->GetInput(); + + output->FillBuffer( input->GetBackgroundValue() ); + + Superclass::BeforeThreadedGenerateData(); + +} + + +template<class TInputImage, class TOutputImage> +void +LabelMapToLabelImageFilter<TInputImage, TOutputImage> +::ThreadedProcessLabelObject( LabelObjectType * labelObject ) +{ + const typename LabelObjectType::LabelType & label = labelObject->GetLabel(); + + typename InputImageType::LabelObjectType::LineContainerType::const_iterator lit; + typename InputImageType::LabelObjectType::LineContainerType & lineContainer = labelObject->GetLineContainer(); + + for( lit = lineContainer.begin(); lit != lineContainer.end(); lit++ ) + { + IndexType idx = lit->GetIndex(); + unsigned long length = lit->GetLength(); + for( unsigned int i=0; i<length; i++) + { + this->GetOutput()->SetPixel( idx, label ); + idx[0]++; + } + } +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelObject.h b/Utilities/ITK/Code/Review/itkLabelObject.h new file mode 100644 index 0000000000..57d79dc911 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelObject.h @@ -0,0 +1,163 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelObject.h,v $ + Language: C++ + Date: $Date: 2009-05-23 19:04:36 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelObject_h +#define __itkLabelObject_h + +#include <deque> +#include "itkLightObject.h" +#include "itkLabelObjectLine.h" +#include "itkWeakPointer.h" +#include "itkObjectFactory.h" + +namespace itk +{ + +/** \class LabelObject + * \brief The base class for the representation of an labeled binary object in an image + * + * LabelObject is the base class to represent a labeled object in an image. + * It should be used associated with the LabelMap. + * + * LabelObject store mainly 2 things: the label of the object, and a set of lines + * which are part of the object. + * No attribute is available in that class, so this class can be used as a base class + * to implement a label object with attribute, or when no attribute is needed (see the + * reconstruction filters for an example. If a simple attribute is needed, + * AttributeLabelObject can be used directly. + * + * All the subclasses of LabelObject have to reinplement the CopyAttributesFrom() method. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa LabelMapFilter, AttributeLabelObject + * \ingroup DataRepresentation + * \ingroup LabeledImageObject + */ +template < class TLabel, unsigned int VImageDimension > +class ITK_EXPORT LabelObject : public LightObject +{ +public: + /** Standard class typedefs */ + typedef LabelObject Self; + typedef LightObject Superclass; + typedef Self LabelObjectType; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef WeakPointer<const Self> ConstWeakPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(LabelObject, LightObject); + + itkStaticConstMacro(ImageDimension, unsigned int, VImageDimension); + + typedef Index< VImageDimension > IndexType; + typedef TLabel LabelType; + typedef LabelObjectLine< VImageDimension > LineType; + typedef typename LineType::LengthType LengthType; + typedef typename std::deque< LineType > LineContainerType; + typedef unsigned int AttributeType; + + enum + { + LABEL = 0 + }; + + static AttributeType GetAttributeFromName( const std::string & s ); + static std::string GetNameFromAttribute( const AttributeType & a ); + + /** + * Set/Get the label associated with the object. + */ + const LabelType & GetLabel() const; + void SetLabel( const LabelType & label ); + + /** + * Return true if the object contain the given index and false otherwise. + * Worst case complexity is O(L) where L is the number of lines in the object. + */ + bool HasIndex( const IndexType & idx ) const; + + /** + * Add an index to the object. If the index is already in the object, the index can + * be found several time in the object. + */ + void AddIndex( const IndexType & idx ); + + /** + * Add a new line to the object, without any check. + */ + void AddLine( const IndexType & idx, const LengthType & length ); + + /** + * Add a new line to the object, without any check. + */ + void AddLine( const LineType & line ); + + /** Return the line container of this object */ + const LineContainerType & GetLineContainer() const; + + LineContainerType & GetLineContainer(); + + void SetLineContainer( const LineContainerType & lineContainer ); + + int GetNumberOfLines() const; + + const LineType & GetLine( int i ) const; + + LineType & GetLine( int i ); + + int Size() const; + + IndexType GetIndex( int offset ) const; + + /** Copy the attributes of another node to this one */ + virtual void CopyAttributesFrom( const Self * src ); + + /** Copy the lines, the label and the attributes from another node. */ + void CopyAllFrom( const Self * src ); + + /** Reorder the lines, merge the touching lines and ensure that no + * pixel is covered by two lines + */ + void Optimize(); + +protected: + LabelObject(); + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + LabelObject(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + LineContainerType m_LineContainer; + LabelType m_Label; +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelObject.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelObject.txx b/Utilities/ITK/Code/Review/itkLabelObject.txx new file mode 100644 index 0000000000..1ae75e654b --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelObject.txx @@ -0,0 +1,327 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelObject.txx,v $ + Language: C++ + Date: $Date: 2009-05-23 23:52:55 $ + Version: $Revision: 1.7 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelObject_txx +#define __itkLabelObject_txx + +#include "itkLabelObject.h" +#include "itkLabelObjectLineComparator.h" +#include "vnl/vnl_math.h" +#include <algorithm> + +namespace itk +{ + +template < class TLabel, unsigned int VImageDimension > +LabelObject<TLabel, VImageDimension>::LabelObject() +{ + m_Label = NumericTraits<LabelType>::Zero; + m_LineContainer.clear(); +} + +template < class TLabel, unsigned int VImageDimension > +typename LabelObject<TLabel, VImageDimension>::AttributeType +LabelObject<TLabel, VImageDimension>::GetAttributeFromName( const std::string & s ) +{ + if( s == "Label" ) + { + return LABEL; + } + // can't recognize the name + throw std::runtime_error("Unknown attribute."); +} + +template < class TLabel, unsigned int VImageDimension > +std::string +LabelObject<TLabel, VImageDimension> +::GetNameFromAttribute( const AttributeType & a ) +{ + switch( a ) + { + case LABEL: + return "Label"; + break; + } + // can't recognize the namespace + throw std::runtime_error("Unknown attribute."); +} + +/** + * Set/Get the label associated with that object. + */ +template < class TLabel, unsigned int VImageDimension > +const typename LabelObject<TLabel, VImageDimension>::LabelType & +LabelObject<TLabel, VImageDimension>::GetLabel() const +{ + return m_Label; +} + +template < class TLabel, unsigned int VImageDimension > +void +LabelObject<TLabel, VImageDimension>::SetLabel( const LabelType & label ) +{ + m_Label = label; +} + +/** + * Return true if the object contain the given index and false otherwise. + * Worst case complexity is O(L) where L is the number of lines in the object. + */ +template < class TLabel, unsigned int VImageDimension > +bool +LabelObject<TLabel, VImageDimension>:: +HasIndex( const IndexType & idx ) const +{ + for( typename LineContainerType::const_iterator it=m_LineContainer.begin(); + it != m_LineContainer.end(); + it++ ) + { + if( it->HasIndex( idx ) ) + { + return true; + } + } + return false; +} + +/** + * Add an index to the object. If the index is already in the object, the index can + * be found several time in the object. + */ +template < class TLabel, unsigned int VImageDimension > +void +LabelObject<TLabel, VImageDimension>:: +AddIndex( const IndexType & idx ) +{ + itkAssertOrThrowMacro( (!this->HasIndex( idx )), "Index out of range" ); + + if( !m_LineContainer.empty() ) + { + // can we use the last line to add that index ? + LineType & lastLine = * m_LineContainer.rbegin(); + if( lastLine.IsNextIndex( idx ) ) + { + lastLine.SetLength( lastLine.GetLength() + 1 ); + return; + } + } + // create a new line + this->AddLine( idx, 1 ); +} + +/** + * Add a new line to the object, without any check. + */ +template < class TLabel, unsigned int VImageDimension > +void +LabelObject<TLabel, VImageDimension>:: +AddLine( const IndexType & idx, const LengthType & length ) +{ + LineType line( idx, length ); + this->AddLine( line ); +} + +/** + * Add a new line to the object, without any check. + */ +template < class TLabel, unsigned int VImageDimension > +void +LabelObject<TLabel, VImageDimension>:: +AddLine( const LineType & line ) +{ + // TODO: add an assert to be sure that some indexes in the line are not already stored here + m_LineContainer.push_back( line ); +} + +/** Return the line container of this object */ +template < class TLabel, unsigned int VImageDimension > +const +typename LabelObject<TLabel, VImageDimension>::LineContainerType & +LabelObject<TLabel, VImageDimension>::GetLineContainer() const +{ + return m_LineContainer; +} + +template < class TLabel, unsigned int VImageDimension > +typename LabelObject<TLabel, VImageDimension>::LineContainerType & +LabelObject<TLabel, VImageDimension>::GetLineContainer() +{ + return m_LineContainer; +} + +template < class TLabel, unsigned int VImageDimension > +void +LabelObject<TLabel, VImageDimension>::SetLineContainer( const LineContainerType & lineContainer ) +{ + m_LineContainer = lineContainer; +} + +template < class TLabel, unsigned int VImageDimension > +int +LabelObject<TLabel, VImageDimension>::GetNumberOfLines() const +{ + return m_LineContainer.size(); +} + +template < class TLabel, unsigned int VImageDimension > +const +typename LabelObject<TLabel, VImageDimension>::LineType & +LabelObject<TLabel, VImageDimension>::GetLine( int i ) const +{ + return m_LineContainer[i]; +} + +template < class TLabel, unsigned int VImageDimension > +typename LabelObject<TLabel, VImageDimension>::LineType & +LabelObject<TLabel, VImageDimension>::GetLine( int i ) +{ + return m_LineContainer[i]; +} + +template < class TLabel, unsigned int VImageDimension > +int +LabelObject<TLabel, VImageDimension>::Size() const +{ + int size = 0; + for( typename LineContainerType::const_iterator it=m_LineContainer.begin(); + it != m_LineContainer.end(); + it++ ) + { + size += it->GetLength(); + } + return size; +} + +template < class TLabel, unsigned int VImageDimension > +typename LabelObject<TLabel, VImageDimension>::IndexType +LabelObject<TLabel, VImageDimension>::GetIndex( int offset ) const +{ + int o = offset; + for( typename LineContainerType::const_iterator it=m_LineContainer.begin(); + it != m_LineContainer.end(); + it++ ) + { + int size = it->GetLength(); + if( o > size) + { + o -= size; + } + else + { + IndexType idx = it->GetIndex(); + idx[0] += o; + return idx; + } + } + itkGenericExceptionMacro(<< "Invalid offset: " << offset); +} + +/** Copy the attributes of another node to this one */ +template < class TLabel, unsigned int VImageDimension > +void +LabelObject<TLabel, VImageDimension>::CopyAttributesFrom( const Self * src ) +{ + itkAssertOrThrowMacro ( (src != NULL), "Null Pointer" ); + // nothing to do here - this class has no attribute +} + +/** Copy the lines, the label and the attributes from another node. */ +template < class TLabel, unsigned int VImageDimension > +void +LabelObject<TLabel, VImageDimension>::CopyAllFrom( const Self * src ) +{ + itkAssertOrThrowMacro ( (src != NULL), "Null Pointer" ); + m_LineContainer = src->m_LineContainer; + m_Label = src->m_Label; + // also copy the attributes + this->CopyAttributesFrom( src ); +} + +/** Reorder the lines, merge the touching lines and ensure that no + * pixel is covered by two lines + */ +template < class TLabel, unsigned int VImageDimension > +void +LabelObject<TLabel, VImageDimension>::Optimize() +{ + if( ! m_LineContainer.empty() ) + { + // first copy the lines in another container and clear the current one + LineContainerType lineContainer = m_LineContainer; + m_LineContainer.clear(); + + // reorder the lines + typename Functor::LabelObjectLineComparator< LineType > comparator; + std::sort( lineContainer.begin(), lineContainer.end(), comparator ); + + // then check the lines consistancy + // we'll proceed line index by line index + IndexType currentIdx = lineContainer.begin()->GetIndex(); + long int currentLength = lineContainer.begin()->GetLength(); + + for( typename LineContainerType::const_iterator it=lineContainer.begin(); + it != lineContainer.end(); + it++ ) + { + const LineType & line = *it; + IndexType idx = line.GetIndex(); + unsigned long length = line.GetLength(); + + // check the index to be sure that we are still in the same line idx + bool sameIdx = true; + for( int i=1; i<ImageDimension; i++ ) + { + if( currentIdx[i] != idx[i] ) + { + sameIdx = false; + } + } + + // try to extend the current line idx, or create a new line + if( sameIdx && currentIdx[0] + currentLength >= idx[0] ) + { + // we may expand the line + long int newLength = idx[0] + length - currentIdx[0]; + currentLength = vnl_math_max( newLength, currentLength ); + } + else + { + // add the previous line to the new line container and use the new line index and size + // std::cout << currentIdx << " " << currentLength << std::endl; + this->AddLine( currentIdx, currentLength ); + currentIdx = idx; + currentLength = length; + } + // std::cout << line.GetIndex() << " " << line.GetLength() << std::endl; + } + // complete the last line + // std::cout << currentIdx << " " << currentLength << std::endl; + this->AddLine( currentIdx, currentLength ); + } +} + +template < class TLabel, unsigned int VImageDimension > +void +LabelObject<TLabel, VImageDimension>::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf( os, indent ); + os << indent << "LineContainer: " << & m_LineContainer << std::endl; + os << indent << "Label: " << static_cast<typename NumericTraits<LabelType>::PrintType>(m_Label) << std::endl; +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelObjectLine.h b/Utilities/ITK/Code/Review/itkLabelObjectLine.h new file mode 100644 index 0000000000..85c81dd0e3 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelObjectLine.h @@ -0,0 +1,96 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelObjectLine.h,v $ + Language: C++ + Date: $Date: 2009-05-13 19:05:59 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelObjectLine_h +#define __itkLabelObjectLine_h + +#include "itkIndex.h" +#include "itkIndent.h" + +namespace itk +{ + +/** \class LabelObjectLine + * LabelObjectLine is the line object used in the LabelObject class + * to store the line which are part of the object. + * A line is formed of and index and a length in the dimension 0. + * It is used in a run-length encoding + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \ingroup LabeledImageObject + */ +template < unsigned int VImageDimension > +class LabelObjectLine +{ +public: + itkStaticConstMacro(ImageDimension, unsigned int, VImageDimension); + + typedef Index< VImageDimension > IndexType; + typedef unsigned long LengthType; + + LabelObjectLine() {}; + virtual ~LabelObjectLine() {}; + LabelObjectLine( const IndexType & idx, const LengthType & length ); + + // + // Set/Get Index + // + void SetIndex( const IndexType & idx ); + IndexType & GetIndex(); + const IndexType & GetIndex() const; + + // + // SetGet Length + // + void SetLength( const LengthType length ); + LengthType & GetLength(); + const LengthType & GetLength() const; + + // + // Check for index + // + bool HasIndex( const IndexType idx ) const; + bool IsNextIndex( const IndexType & idx ) const; + + /** Cause the object to print itself out. */ + void Print(std::ostream& os, Indent indent=0) const; + +protected: + /** Methods invoked by Print() to print information about the object + * including superclasses. Typically not called by the user (use Print() + * instead) but used in the hierarchical print process to combine the + * output of several classes. */ + virtual void PrintSelf(std::ostream& os, Indent indent) const; + virtual void PrintHeader(std::ostream& os, Indent indent) const; + virtual void PrintTrailer(std::ostream& os, Indent indent) const; + +private: + IndexType m_Index; + LengthType m_Length; +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelObjectLine.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelObjectLine.txx b/Utilities/ITK/Code/Review/itkLabelObjectLine.txx new file mode 100644 index 0000000000..230f1bb826 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelObjectLine.txx @@ -0,0 +1,152 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelObjectLine.txx,v $ + Language: C++ + Date: $Date: 2009-05-13 14:48:22 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelObjectLine_txx +#define __itkLabelObjectLine_txx + +#include "itkLabelObjectLine.h" + +namespace itk +{ + +template < unsigned int VImageDimension > +LabelObjectLine<VImageDimension>:: +LabelObjectLine( const IndexType & idx, const LengthType & length ) +{ + this->SetIndex( idx ); + this->SetLength( length ); +} + +template < unsigned int VImageDimension > +void LabelObjectLine<VImageDimension>::SetIndex( const IndexType & idx ) +{ + m_Index = idx; +} + +template < unsigned int VImageDimension > +typename LabelObjectLine<VImageDimension>::IndexType & +LabelObjectLine<VImageDimension>::GetIndex() +{ + return m_Index; +} + +template < unsigned int VImageDimension > +const typename LabelObjectLine<VImageDimension>::IndexType & +LabelObjectLine<VImageDimension>::GetIndex() const +{ + return m_Index; +} + +template < unsigned int VImageDimension > +void LabelObjectLine<VImageDimension>::SetLength( const LengthType length ) +{ + m_Length = length; +} + +template < unsigned int VImageDimension > +typename LabelObjectLine<VImageDimension>::LengthType & +LabelObjectLine<VImageDimension>::GetLength() +{ + return m_Length; +} + +template < unsigned int VImageDimension > +const typename LabelObjectLine<VImageDimension>::LengthType & +LabelObjectLine<VImageDimension>::GetLength() const +{ + return m_Length; +} + +template < unsigned int VImageDimension > +bool LabelObjectLine<VImageDimension>::HasIndex( const IndexType idx ) const +{ + // are we talking about the right line ? + for( int i=1; i<ImageDimension; i++ ) + { + if( m_Index[i] != idx[i] ) + { + return false; + } + } + return ( idx[0] >= m_Index[0] && idx[0] < m_Index[0] + (long)m_Length ); +} + +template < unsigned int VImageDimension > +bool LabelObjectLine<VImageDimension>::IsNextIndex( const IndexType & idx ) const +{ + // are we talking about the right line ? + for( int i=1; i<ImageDimension; i++ ) + { + if( m_Index[i] != idx[i] ) + { + return false; + } + } + return idx[0] == m_Index[0] + (long)m_Length; +} + +/** + * This function just calls the + * header/self/trailer virtual print methods, which can be overriden by + * subclasses. + */ +template < unsigned int VImageDimension > +void +LabelObjectLine<VImageDimension> +::Print(std::ostream& os, Indent indent) const +{ + this->PrintHeader(os, indent); + this->PrintSelf(os, indent.GetNextIndent()); + this->PrintTrailer(os, indent); +} + +/** + * Define a default print header for all objects. + */ +template < unsigned int VImageDimension > +void +LabelObjectLine<VImageDimension> +::PrintHeader(std::ostream& os, Indent indent) const +{ + os << indent << " (" << this << ")\n"; +} + +/** + * Define a default print body for all objects. + */ +template < unsigned int VImageDimension > +void +LabelObjectLine<VImageDimension> +::PrintSelf(std::ostream& os, Indent indent) const +{ + os << indent << "Index: " << this->m_Index << std::endl; + os << indent << "Length: " << this->m_Length << std::endl; +} + + +/** + * Define a default print trailer for all objects. + */ +template < unsigned int VImageDimension > +void +LabelObjectLine<VImageDimension> +::PrintTrailer(std::ostream& itkNotUsed(os), Indent itkNotUsed(indent)) const +{ +} + +} // namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelObjectLineComparator.h b/Utilities/ITK/Code/Review/itkLabelObjectLineComparator.h new file mode 100644 index 0000000000..dd3f04a1ee --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelObjectLineComparator.h @@ -0,0 +1,66 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelObjectLineComparator.h,v $ + Language: C++ + Date: $Date: 2009-05-13 15:32:52 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelObjectLineComparator_h +#define __itkLabelObjectLineComparator_h + +namespace itk +{ + +/** \class LabelObjectLineComparator + * \brief Performs a comparison of l1 < l2. Returns true if l1 is strictly less + * than l2. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa LabelObjectLine + * \ingroup LabeledImageObject + */ +namespace Functor { + +template< class TLabelObjectLine > +class LabelObjectLineComparator +{ +public: + bool operator()(TLabelObjectLine const& l1, TLabelObjectLine const& l2) const + { + const typename TLabelObjectLine::IndexType & idx1 = l1.GetIndex(); + const typename TLabelObjectLine::IndexType & idx2 = l2.GetIndex(); + + for(int i=TLabelObjectLine::ImageDimension - 1; i>=0; i--) + { + if(idx1[i] < idx2[i]) + { + return true; + } + else if(idx1[i] > idx2[i]) + { + return false; + } + } + return l1.GetLength() < l2.GetLength(); + } +}; + +} + +} + +#endif diff --git a/Utilities/ITK/Code/Review/itkMaskedMovingHistogramImageFilter.h b/Utilities/ITK/Code/Review/itkMaskedMovingHistogramImageFilter.h index 8818a14142..cce61927f8 100644 --- a/Utilities/ITK/Code/Review/itkMaskedMovingHistogramImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMaskedMovingHistogramImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskedMovingHistogramImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-08 04:33:27 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-23 03:43:41 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -117,16 +117,16 @@ public: DataObject::Pointer MakeOutput(unsigned int idx); itkSetMacro(FillValue, OutputPixelType); - itkGetMacro(FillValue, OutputPixelType); + itkGetConstMacro(FillValue, OutputPixelType); itkSetMacro(MaskValue, MaskPixelType); - itkGetMacro(MaskValue, MaskPixelType); + itkGetConstMacro(MaskValue, MaskPixelType); itkSetMacro(BackgroundMaskValue, MaskPixelType); - itkGetMacro(BackgroundMaskValue, MaskPixelType); + itkGetConstMacro(BackgroundMaskValue, MaskPixelType); void SetGenerateOutputMask( bool ); - itkGetMacro(GenerateOutputMask, bool); + itkGetConstMacro(GenerateOutputMask, bool); // itkBooleanMacro(GenerateOutputMask); protected: diff --git a/Utilities/ITK/Code/Review/itkMaskedRankHistogram.h b/Utilities/ITK/Code/Review/itkMaskedRankHistogram.h index 2e5b71de8e..13b55bde63 100644 --- a/Utilities/ITK/Code/Review/itkMaskedRankHistogram.h +++ b/Utilities/ITK/Code/Review/itkMaskedRankHistogram.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskedRankHistogram.h,v $ Language: C++ - Date: $Date: 2008-09-29 18:36:38 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-13 22:17:41 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -412,10 +412,12 @@ public: void RemovePixel(const TInputPixel &p) { - assert(p - NumericTraits< TInputPixel >::NonpositiveMin() >= 0); - assert(p - NumericTraits< TInputPixel >::NonpositiveMin() < (int)m_Vec.size()); - assert(m_Entries >= 1); - m_Vec[ (long unsigned int)(p - NumericTraits< TInputPixel >::NonpositiveMin()) ]--; + const long int q = p - NumericTraits< TInputPixel >::NonpositiveMin(); + itkAssertOrThrowMacro( ( q >= 0 ), "Input pixel value is out of range"); + itkAssertOrThrowMacro( ( q < (int)m_Vec.size() ), "Input pixel value is out of range"); + itkAssertOrThrowMacro( (m_Entries >= 1), "Insufficient entries"); + + m_Vec[ static_cast<long unsigned int>(q) ]--; --m_Entries; if (m_Compare(p, m_RankValue) || p == m_RankValue) diff --git a/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.h b/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.h index 6a56463872..bcdb746e6b 100644 --- a/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskedRankImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-09 12:09:54 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -98,7 +98,7 @@ public: typedef typename KernelType::SizeType RadiusType; itkSetMacro(Rank, float) - itkGetMacro(Rank, float) + itkGetConstMacro(Rank, float) protected: MaskedRankImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkMatlabTransformIO.cxx b/Utilities/ITK/Code/Review/itkMatlabTransformIO.cxx index 2564136fe1..8f49673e8e 100644 --- a/Utilities/ITK/Code/Review/itkMatlabTransformIO.cxx +++ b/Utilities/ITK/Code/Review/itkMatlabTransformIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMatlabTransformIO.cxx,v $ Language: C++ - Date: $Date: 2008-02-07 15:07:57 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-05-11 16:37:29 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,13 +73,13 @@ void MatlabTransformIO:: Read() { - std::ifstream matfile(this->m_FileName.c_str(), + std::ifstream matfile(this->GetFileName(), std::ios::in|std::ios::binary); if(matfile.fail()) { matfile.close(); itkExceptionMacro("The file could not be opened for read access " - << std::endl << "Filename: \"" << m_FileName << "\""); + << std::endl << "Filename: \"" << this->GetFileName() << "\""); } while(!matfile.eof()) { @@ -100,7 +100,7 @@ Read() // create transform based on name of first vector TransformPointer transform; this->CreateTransform(transform,classname); - this->m_ReadTransformList.push_back(transform); + this->GetReadTransformList().push_back(transform); vnl_matlab_readhdr mathdr2(matfile); if(mathdr2.cols() != 1) { @@ -120,11 +120,11 @@ void MatlabTransformIO:: Write() { - ConstTransformListType::iterator it = m_WriteTransformList.begin(); + ConstTransformListType::iterator it = this->GetWriteTransformList().begin(); vnl_vector<double> TempArray; std::ofstream out; this->OpenStream(out,true); - while(it != m_WriteTransformList.end()) + while(it != this->GetWriteTransformList().end()) { std::string xfrmType((*it)->GetTransformTypeAsString()); TempArray = (*it)->GetParameters(); diff --git a/Utilities/ITK/Code/Review/itkMorphologicalWatershedImageFilter.h b/Utilities/ITK/Code/Review/itkMorphologicalWatershedImageFilter.h index a41ada85c0..a45368f350 100644 --- a/Utilities/ITK/Code/Review/itkMorphologicalWatershedImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMorphologicalWatershedImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMorphologicalWatershedImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -99,7 +99,7 @@ public: /** */ itkSetMacro(Level, InputImagePixelType); - itkGetMacro(Level, InputImagePixelType); + itkGetConstMacro(Level, InputImagePixelType); protected: MorphologicalWatershedImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkMovingHistogramImageFilterBase.h b/Utilities/ITK/Code/Review/itkMovingHistogramImageFilterBase.h index fed3f89c48..a40fdb7037 100644 --- a/Utilities/ITK/Code/Review/itkMovingHistogramImageFilterBase.h +++ b/Utilities/ITK/Code/Review/itkMovingHistogramImageFilterBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMovingHistogramImageFilterBase.h,v $ Language: C++ - Date: $Date: 2008-08-09 09:53:47 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -136,7 +136,7 @@ public: /** Set kernel (structuring element). */ void SetKernel( const KernelType& kernel ); - itkGetMacro(PixelsPerTranslation, unsigned long); + itkGetConstMacro(PixelsPerTranslation, unsigned long); protected: MovingHistogramImageFilterBase(); diff --git a/Utilities/ITK/Code/Review/itkMovingHistogramMorphologyImageFilter.h b/Utilities/ITK/Code/Review/itkMovingHistogramMorphologyImageFilter.h index c972657c3d..3fb7d26e81 100644 --- a/Utilities/ITK/Code/Review/itkMovingHistogramMorphologyImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMovingHistogramMorphologyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMovingHistogramMorphologyImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-27 13:14:18 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -272,7 +272,7 @@ public: /** Set/Get the boundary value. */ itkSetMacro(Boundary, PixelType); - itkGetMacro(Boundary, PixelType); + itkGetConstMacro(Boundary, PixelType); /** Return true if the vector based algorithm is used, and * false if the map based algorithm is used */ diff --git a/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.h b/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.h index ab772f7d98..34bc2003cc 100644 --- a/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiScaleHessianBasedMeasureImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-25 22:25:50 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -75,31 +75,40 @@ public: typedef typename TInputImage::PixelType InputPixelType; typedef typename TOutputImage::PixelType OutputPixelType; - + typedef typename TOutputImage::RegionType OutputRegionType; + /** Image dimension. */ itkStaticConstMacro(ImageDimension, unsigned int, ::itk::GetImageDimension<InputImageType>::ImageDimension); - + + /** Types for Scales image */ + typedef float ScalesPixelType; + typedef Image<ScalesPixelType, itkGetStaticConstMacro(ImageDimension)> ScalesImageType; + /** Hessian computation filter. */ typedef HessianRecursiveGaussianImageFilter< InputImageType, HessianImageType> HessianFilterType; - /** Update image buffer that holds the best objectness response */ + /** Update image buffer that holds the best objectness response. This is not redundant from + the output image because the latter may not be of float type, which is required for the comparisons + between responses at different scales. */ typedef Image< double, itkGetStaticConstMacro(ImageDimension) > UpdateBufferType; typedef typename UpdateBufferType::ValueType BufferValueType; - + + typedef typename Superclass::DataObjectPointer DataObjectPointer; + /** Method for creation through the object factory. */ itkNewMacro(Self); /** Set/Get macros for SigmaMin */ itkSetMacro(SigmaMinimum, double); - itkGetMacro(SigmaMinimum, double); + itkGetConstMacro(SigmaMinimum, double); /** Set/Get macros for SigmaMax */ itkSetMacro(SigmaMaximum, double); - itkGetMacro(SigmaMaximum, double); + itkGetConstMacro(SigmaMaximum, double); /** Set/Get macros for Number of Scales */ - itkSetMacro(NumberOfSigmaSteps, int); - itkGetMacro(NumberOfSigmaSteps, int); + itkSetMacro(NumberOfSigmaSteps, unsigned int); + itkGetConstMacro(NumberOfSigmaSteps, unsigned int); /** Set/Get HessianToMeasureFilter. This will be a filter that takes Hessian input image and produces enhanced output scalar image. The filter must derive from @@ -107,6 +116,15 @@ public: itkSetObjectMacro( HessianToMeasureFilter, HessianToMeasureFilterType); itkGetObjectMacro( HessianToMeasureFilter, HessianToMeasureFilterType); + /** Methods to turn on/off flag to inform the filter that the Hessian-based measure + is non-negative (classical measures like Sato's and Frangi's are), hence it has a minimum + at zero. In this case, the update buffer is initialized at zero, and the output scale and Hessian + are zero in case the Hessian-based measure returns zero for all scales. Otherwise, the minimum + output scale and Hessian are the ones obtained at scale SigmaMinimum. On by default. + */ + itkSetMacro(NonNegativeHessianBasedMeasure,bool); + itkGetConstMacro(NonNegativeHessianBasedMeasure,bool); + itkBooleanMacro(NonNegativeHessianBasedMeasure); typedef enum { EquispacedSigmaSteps = 0, LogarithmicSigmaSteps = 1 } SigmaStepMethodType; @@ -114,42 +132,38 @@ public: /** Set/Get the method used to generate scale sequence (Equispaced * or Logarithmic) */ itkSetMacro(SigmaStepMethod, SigmaStepMethodType); - itkGetMacro(SigmaStepMethod, SigmaStepMethodType); - void SetSigmaStepMethodToEquispaced() - { - this->SetSigmaStepMethod(Self::EquispacedSigmaSteps); - } - - void SetSigmaStepMethodToLogarithmic() - { - this->SetSigmaStepMethod(Self::LogarithmicSigmaSteps); - } - - /** FIX ME: MOVE this to implementation file */ + itkGetConstMacro(SigmaStepMethod, SigmaStepMethodType); + + /**Set equispaced sigma step method */ + void SetSigmaStepMethodToEquispaced(); + + /**Set logartihmic sigma step method */ + void SetSigmaStepMethodToLogarithmic(); + /** Get the image containing the Hessian computed at the best * response scale */ - const HessianImageType* GetHessianOutput() const - { - return static_cast<const HessianImageType*>(this->ProcessObject::GetOutput(2)); - } + const HessianImageType* GetHessianOutput() const; /** Get the image containing the scales at which each pixel gave the * best response */ - const OutputImageType* GetScalesOutput() const - { - return static_cast<const OutputImageType*>(this->ProcessObject::GetOutput(1)); - } + const ScalesImageType* GetScalesOutput() const; + + void EnlargeOutputRequestedRegion (DataObject *); - /** FIX ME : ADD DOCUMENTATION */ + /** Methods to turn on/off flag to generate an image with scale values at + * each pixel for the best vesselness response */ itkSetMacro(GenerateScalesOutput,bool); - itkGetMacro(GenerateScalesOutput,bool); + itkGetConstMacro(GenerateScalesOutput,bool); itkBooleanMacro(GenerateScalesOutput); - /** FIX ME : ADD DOCUMENTATION */ + /** Methods to turn on/off flag to generate an image with hessian values at + * each pixel for the best vesselness response */ itkSetMacro(GenerateHessianOutput,bool); - itkGetMacro(GenerateHessianOutput,bool); + itkGetConstMacro(GenerateHessianOutput,bool); itkBooleanMacro(GenerateHessianOutput); + /** This is overloaded to create the Scales and Hessian output images */ + virtual DataObjectPointer MakeOutput(unsigned int idx); protected: MultiScaleHessianBasedMeasureImageFilter(); @@ -161,7 +175,6 @@ protected: private: void UpdateMaximumResponse(double sigma); - double ComputeSigmaValue(int scaleLevel); void AllocateUpdateBuffer(); @@ -170,10 +183,12 @@ private: MultiScaleHessianBasedMeasureImageFilter(const Self&); void operator=(const Self&); //purposely not implemented + bool m_NonNegativeHessianBasedMeasure; + double m_SigmaMinimum; double m_SigmaMaximum; - int m_NumberOfSigmaSteps; + unsigned int m_NumberOfSigmaSteps; SigmaStepMethodType m_SigmaStepMethod; typename HessianToMeasureFilterType::Pointer m_HessianToMeasureFilter; diff --git a/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.txx b/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.txx index 2e6362264a..049b366fd8 100644 --- a/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiScaleHessianBasedMeasureImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-25 22:04:19 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-20 12:54:12 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,6 +35,8 @@ MultiScaleHessianBasedMeasureImageFilter <TInputImage,THessianImage,TOutputImage> ::MultiScaleHessianBasedMeasureImageFilter() { + m_NonNegativeHessianBasedMeasure = true; + m_SigmaMinimum = 0.2; m_SigmaMaximum = 2.0; @@ -50,13 +52,46 @@ MultiScaleHessianBasedMeasureImageFilter m_GenerateScalesOutput = false; m_GenerateHessianOutput = false; - typename OutputImageType::Pointer scalesImage = OutputImageType::New(); + typename ScalesImageType::Pointer scalesImage = ScalesImageType::New(); typename HessianImageType::Pointer hessianImage = HessianImageType::New(); this->ProcessObject::SetNumberOfRequiredOutputs(3); this->ProcessObject::SetNthOutput(1,scalesImage.GetPointer()); this->ProcessObject::SetNthOutput(2,hessianImage.GetPointer()); } +template <typename TInputImage, + typename THessianImage, + typename TOutputImage> +void +MultiScaleHessianBasedMeasureImageFilter +<TInputImage,THessianImage,TOutputImage> +::EnlargeOutputRequestedRegion (DataObject *output) +{ + // currently this filter can not stream so we must set the outputs + // requested region to the largest + output->SetRequestedRegionToLargestPossibleRegion(); +} + +template <typename TInputImage, + typename THessianImage, + typename TOutputImage> +typename MultiScaleHessianBasedMeasureImageFilter + <TInputImage,THessianImage,TOutputImage>::DataObjectPointer +MultiScaleHessianBasedMeasureImageFilter +<TInputImage,THessianImage,TOutputImage> +::MakeOutput(unsigned int idx) +{ + if (idx == 1) + { + return static_cast<DataObject*>(ScalesImageType::New().GetPointer()); + } + if (idx == 2) + { + return static_cast<DataObject*>(HessianImageType::New().GetPointer()); + } + return Superclass::MakeOutput(idx); +} + template <typename TInputImage, typename THessianImage, typename TOutputImage> @@ -70,16 +105,24 @@ MultiScaleHessianBasedMeasureImageFilter typename TOutputImage::Pointer output = this->GetOutput(); - m_UpdateBuffer->SetSpacing(output->GetSpacing()); - m_UpdateBuffer->SetOrigin(output->GetOrigin()); - m_UpdateBuffer->SetLargestPossibleRegion(output->GetLargestPossibleRegion()); + // this copies meta data describing the output such as origin, + // spacing and the largest region + m_UpdateBuffer->CopyInformation(output); + m_UpdateBuffer->SetRequestedRegion(output->GetRequestedRegion()); m_UpdateBuffer->SetBufferedRegion(output->GetBufferedRegion()); m_UpdateBuffer->Allocate(); // Update buffer is used for > comparisons so make it really really small, // just to be sure. Thanks to Hauke Heibel. - m_UpdateBuffer->FillBuffer( itk::NumericTraits< BufferValueType >::NonpositiveMin() ); + if (m_NonNegativeHessianBasedMeasure) + { + m_UpdateBuffer->FillBuffer( itk::NumericTraits< BufferValueType >::Zero ); + } + else + { + m_UpdateBuffer->FillBuffer( itk::NumericTraits< BufferValueType >::NonpositiveMin() ); + } } template <typename TInputImage, @@ -90,9 +133,10 @@ MultiScaleHessianBasedMeasureImageFilter <TInputImage,THessianImage,TOutputImage> ::GenerateData() { + // TODO: Move the allocation to a derived AllocateOutputs method // Allocate the output - this->GetOutput(0)->SetBufferedRegion(this->GetOutput(0)->GetRequestedRegion()); - this->GetOutput(0)->Allocate(); + this->GetOutput()->SetBufferedRegion(this->GetOutput()->GetRequestedRegion()); + this->GetOutput()->Allocate(); if( m_HessianToMeasureFilter.IsNull() ) { @@ -101,15 +145,25 @@ MultiScaleHessianBasedMeasureImageFilter if (m_GenerateScalesOutput) { - this->GetOutput(1)->SetBufferedRegion(this->GetOutput(1)->GetRequestedRegion()); - this->GetOutput(1)->Allocate(); - this->GetOutput(1)->FillBuffer(0); + typename ScalesImageType::Pointer scalesImage = + dynamic_cast<ScalesImageType*>(this->ProcessObject::GetOutput(1)); + + scalesImage->SetBufferedRegion(scalesImage->GetRequestedRegion()); + scalesImage->Allocate(); + scalesImage->FillBuffer(0); } if (m_GenerateHessianOutput) { - this->GetOutput(2)->SetBufferedRegion(this->GetOutput(2)->GetRequestedRegion()); - this->GetOutput(2)->Allocate(); + typename HessianImageType::Pointer hessianImage = + dynamic_cast<HessianImageType*>(this->ProcessObject::GetOutput(2)); + + hessianImage->SetBufferedRegion(hessianImage->GetRequestedRegion()); + hessianImage->Allocate(); + // SymmetricSecondRankTensor is already filled with zero elements at construction. + // No strict need of filling the buffer, but we do it explicitly here to make sure. + typename HessianImageType::PixelType zeroTensor(0.0); + hessianImage->FillBuffer(zeroTensor); } // Allocate the buffer @@ -127,6 +181,7 @@ MultiScaleHessianBasedMeasureImageFilter while (sigma <= m_SigmaMaximum) { + // TODO: change the to debug output std::cout << "Computing measure for scale with sigma = " << sigma << std::endl; @@ -143,11 +198,14 @@ MultiScaleHessianBasedMeasureImageFilter scaleLevel++; } - //Write out the best response to the output image - ImageRegionIterator<UpdateBufferType> it(m_UpdateBuffer,m_UpdateBuffer->GetLargestPossibleRegion()); + // Write out the best response to the output image + // we can assume that the meta-data should match between these two + // image, therefore we iterate over the desired output region + OutputRegionType outputRegion = this->GetOutput()->GetBufferedRegion(); + ImageRegionIterator<UpdateBufferType> it( m_UpdateBuffer, outputRegion ); it.GoToBegin(); - ImageRegionIterator<TOutputImage> oit(this->GetOutput(0),this->GetOutput(0)->GetLargestPossibleRegion()); + ImageRegionIterator<TOutputImage> oit( this->GetOutput(), outputRegion ); oit.GoToBegin(); while(!oit.IsAtEnd()) @@ -156,6 +214,9 @@ MultiScaleHessianBasedMeasureImageFilter ++oit; ++it; } + + // Release data from the update buffer. + m_UpdateBuffer->ReleaseData(); } template <typename TInputImage, @@ -166,13 +227,16 @@ MultiScaleHessianBasedMeasureImageFilter <TInputImage,THessianImage,TOutputImage> ::UpdateMaximumResponse(double sigma) { - ImageRegionIterator<UpdateBufferType> oit(m_UpdateBuffer,m_UpdateBuffer->GetLargestPossibleRegion()); + // the meta-data should match between these images, therefore we + // iterate over the desired output region + OutputRegionType outputRegion = this->GetOutput()->GetBufferedRegion(); + ImageRegionIterator<UpdateBufferType> oit( m_UpdateBuffer, outputRegion ); - typename OutputImageType::Pointer scalesImage = static_cast<OutputImageType*>(this->ProcessObject::GetOutput(1)); - ImageRegionIterator<OutputImageType> osit(scalesImage,scalesImage->GetLargestPossibleRegion()); + typename ScalesImageType::Pointer scalesImage = static_cast<ScalesImageType*>(this->ProcessObject::GetOutput(1)); + ImageRegionIterator<ScalesImageType> osit (scalesImage, outputRegion ); typename HessianImageType::Pointer hessianImage = static_cast<HessianImageType*>(this->ProcessObject::GetOutput(2)); - ImageRegionIterator<HessianImageType> ohit(hessianImage,hessianImage->GetLargestPossibleRegion()); + ImageRegionIterator<HessianImageType> ohit( hessianImage, outputRegion ); oit.GoToBegin(); if (m_GenerateScalesOutput) @@ -186,10 +250,8 @@ MultiScaleHessianBasedMeasureImageFilter typedef typename HessianToMeasureFilterType::OutputImageType HessianToMeasureOutputImageType; - ImageRegionIterator<HessianToMeasureOutputImageType> it(m_HessianToMeasureFilter->GetOutput(), - this->m_HessianToMeasureFilter->GetOutput()->GetLargestPossibleRegion()); - ImageRegionIterator<HessianImageType> hit(m_HessianFilter->GetOutput(), - this->m_HessianFilter->GetOutput()->GetLargestPossibleRegion()); + ImageRegionIterator<HessianToMeasureOutputImageType> it( m_HessianToMeasureFilter->GetOutput(), outputRegion ); + ImageRegionIterator<HessianImageType> hit( m_HessianFilter->GetOutput(), outputRegion ); it.GoToBegin(); hit.GoToBegin(); @@ -201,7 +263,7 @@ MultiScaleHessianBasedMeasureImageFilter oit.Value() = it.Value(); if (m_GenerateScalesOutput) { - osit.Value() = static_cast< OutputPixelType >( sigma ); + osit.Value() = static_cast< ScalesPixelType >( sigma ); } if (m_GenerateHessianOutput) { @@ -221,6 +283,7 @@ MultiScaleHessianBasedMeasureImageFilter } } } + template <typename TInputImage, typename THessianImage, typename TOutputImage> @@ -258,6 +321,56 @@ MultiScaleHessianBasedMeasureImageFilter return sigmaValue; } +template <typename TInputImage, + typename THessianImage, + typename TOutputImage> +void +MultiScaleHessianBasedMeasureImageFilter +<TInputImage,THessianImage,TOutputImage> +::SetSigmaStepMethodToEquispaced() +{ + this->SetSigmaStepMethod(Self::EquispacedSigmaSteps); +} + +template <typename TInputImage, + typename THessianImage, + typename TOutputImage> +void +MultiScaleHessianBasedMeasureImageFilter +<TInputImage,THessianImage,TOutputImage> +::SetSigmaStepMethodToLogarithmic() +{ + this->SetSigmaStepMethod(Self::LogarithmicSigmaSteps); +} + +/** Get the image containing the Hessian at which each pixel gave the + * best response */ +template <typename TInputImage, + typename THessianImage, + typename TOutputImage> +const +typename MultiScaleHessianBasedMeasureImageFilter<TInputImage,THessianImage,TOutputImage>::HessianImageType * +MultiScaleHessianBasedMeasureImageFilter +<TInputImage,THessianImage,TOutputImage> +::GetHessianOutput() const +{ + return static_cast<const HessianImageType*>(this->ProcessObject::GetOutput(2)); +} + +/** Get the image containing the scales at which each pixel gave the + * best response */ +template <typename TInputImage, + typename THessianImage, + typename TOutputImage> +const +typename MultiScaleHessianBasedMeasureImageFilter<TInputImage,THessianImage,TOutputImage>::ScalesImageType * +MultiScaleHessianBasedMeasureImageFilter +<TInputImage,THessianImage,TOutputImage> +::GetScalesOutput() const +{ + return static_cast<const ScalesImageType*>(this->ProcessObject::GetOutput(1)); +} + template <typename TInputImage, typename THessianImage, typename TOutputImage> @@ -273,6 +386,7 @@ MultiScaleHessianBasedMeasureImageFilter os << indent << "NumberOfSigmaSteps: " << m_NumberOfSigmaSteps << std::endl; os << indent << "SigmaStepMethod: " << m_SigmaStepMethod << std::endl; os << indent << "HessianToMeasureFilter: " << m_HessianToMeasureFilter << std::endl; + os << indent << "NonNegativeHessianBasedMeasure: " << m_NonNegativeHessianBasedMeasure << std::endl; os << indent << "GenerateScalesOutput: " << m_GenerateScalesOutput << std::endl; os << indent << "GenerateHessianOutput: " << m_GenerateHessianOutput << std::endl; } diff --git a/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.h b/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.h new file mode 100644 index 0000000000..3f08d724a9 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.h @@ -0,0 +1,231 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMultiphaseDenseFiniteDifferenceImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-15 17:44:18 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkMultiphaseDenseFiniteDifferenceImageFilter_h +#define __itkMultiphaseDenseFiniteDifferenceImageFilter_h + +#include "itkMultiphaseFiniteDifferenceImageFilter.h" +#include "itkBinaryThresholdImageFilter.h" +#include "itkSignedMaurerDistanceMapImageFilter.h" +#include "itkImageRegionConstIterator.h" +#include "itkImageRegionIterator.h" +#include "itkNumericTraits.h" +#include "itkNeighborhoodAlgorithm.h" + +#include <list> + + +namespace itk { + +/** + * \class MultiphaseDenseFiniteDifferenceImageFilter + * + * This filter implements a layer of the finite difference solver hierarchy that + * performs ``dense'' iteration, ie. iteration over all pixels in the input and + * output at each change calculation and update step. Dense iteration is in + * contrast to a ``sparse'' iteration over a subset of the pixels. See + * documentation for FiniteDifferenceImageFilter for an overview of the + * iterative finite difference algorithm: + * + * \par + * \f$u_{\mathbf{i}}^{n+1}=u^n_{\mathbf{i}}+\Delta u^n_{\mathbf{i}}\Delta t\f$ + * + * \par + * The generic code for performing iterations and updates at each time + * step is inherited from the parent class. This class defines an update + * buffer for \f$ \Delta \f$ and the methods CalculateChange() and + * ApplyUpdate(). These methods are designed to automatically thread their + * execution. \f$ \Delta \f$ is defined as an image of identical size and type + * as the output image. + * + * \par + * As we descend through each layer in the hierarchy, we know more and more + * about the specific application of our filter. At this level, we + * have committed to iteration over each pixel in an image. We take advantage + * of that knowledge to multithread the iteration and update methods. + * + * \par Inputs and Outputs + * This is an image to image filter. The specific types of the images are not + * fixed at this level in the hierarchy. + * + * \par How to use this class + * This filter is only one layer in a branch the finite difference solver + * hierarchy. It does not define the function used in the CalculateChange() and + * it does not define the stopping criteria (Halt method). To use this class, + * subclass it to a specific instance that supplies a function and Halt() + * method. + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + * \ingroup ImageFilters + * \sa FiniteDifferenceImageFilter */ +template < class TInputImage, + class TOutputImage, + class TFunction, + typename TIdCell = unsigned int > +class ITK_EXPORT MultiphaseDenseFiniteDifferenceImageFilter + : public MultiphaseFiniteDifferenceImageFilter<TInputImage, + TOutputImage, + TFunction, + TIdCell > +{ +public: + /** Standard class typedefs */ + typedef MultiphaseDenseFiniteDifferenceImageFilter Self; + typedef MultiphaseFiniteDifferenceImageFilter< + TInputImage, TOutputImage, TFunction > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro( MultiphaseDenseFiniteDifferenceImageFilter, ImageToImageFilter ); + + /** Convenient typedefs */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::InputSizeType InputSizeType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputRegionType InputRegionType; + typedef typename Superclass::InputSpacingType InputSpacingType; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::InputPixelType InputPixelType; + + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputRegionType OutputRegionType; + typedef typename Superclass::OutputSizeType OutputSizeType; + typedef typename Superclass::OutputSizeValueType SizeValueType; + typedef typename Superclass::OutputIndexType OutputIndexType; + typedef typename Superclass::OutputIndexValueType OutputIndexValueType; + typedef typename OutputImageType::PixelType OutputPixelType; + + typedef typename Superclass::IdCellType IdCellType; + + typedef OutputImageType UpdateBufferType; + typedef OutputImagePointer UpdateBufferPointer; + + /** The type of region used for multithreading */ + typedef typename UpdateBufferType::RegionType ThreadRegionType; + + typedef BinaryThresholdImageFilter< OutputImageType, OutputImageType > ThresholdFilterType; + typedef typename ThresholdFilterType::Pointer ThresholdFilterPointer; + + typedef SignedMaurerDistanceMapImageFilter< OutputImageType, OutputImageType > MaurerType; + typedef typename MaurerType::Pointer MaurerPointer; + + typedef ImageRegionIterator<UpdateBufferType> UpdateIteratorType; + + typedef typename Superclass::FiniteDifferenceFunctionType FiniteDifferenceFunctionType; + typedef typename Superclass::FiniteDifferenceFunctionPointer FiniteDifferenceFunctionPointer; + typedef typename FiniteDifferenceFunctionType::NeighborhoodType NeighborhoodIteratorType; + + /** Dimensionality of input and output data is assumed to be the same. + * It is inherited from the superclass. */ + itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + + /** The value type of a time step. Inherited from the superclass. */ + typedef typename Superclass::TimeStepType TimeStepType; + + + typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< OutputImageType > FaceCalculatorType; + typedef typename FaceCalculatorType::FaceListType FaceListType; + + void SetFunctionCount( const IdCellType& n ); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(OutputTimesDoubleCheck, + (Concept::MultiplyOperator<OutputPixelType, double>)); + itkConceptMacro(OutputAdditiveOperatorsCheck, + (Concept::AdditiveOperators<OutputPixelType>)); + itkConceptMacro(InputConvertibleToOutputCheck, + (Concept::Convertible<InputPixelType, OutputPixelType>)); + /** End concept checking */ +#endif + +protected: + MultiphaseDenseFiniteDifferenceImageFilter() + { + this->m_ReinitializeCounter = 1; // FIXME: Should this be a bool ? + this->m_UpdateCounter = 0; // FIXME: Should this be a bool ? + } + + ~MultiphaseDenseFiniteDifferenceImageFilter() {} + + /** A simple method to copy the data from the input to the output. ( Supports + * "read-only" image adaptors in the case where the input image type converts + * to a different output image type. ) */ + virtual void CopyInputToOutput(); + virtual void PostProcessOutput(); + + /** This method applies changes from the m_UpdateBuffer to the output using + * the ThreadedApplyUpdate() method and a multithreading mechanism. "dt" is + * the time step to use for the update of each pixel. */ + virtual void ApplyUpdate(TimeStepType dt); + + unsigned int m_ReinitializeCounter; // FIXME: Should this be a boolean ? + unsigned int m_UpdateCounter; // FIXME: Should this be a boolean ? + +private: + MultiphaseDenseFiniteDifferenceImageFilter(const Self&); + void operator=(const Self&); //purposely not implemented + + /** This method allocates storage in m_UpdateBuffer. It is called from + * Superclass::GenerateData(). */ + virtual void AllocateUpdateBuffer(); + + /** This method populates an update buffer with changes for each pixel in the + * output using the ThreadedCalculateChange() method and a multithreading + * mechanism. Returns value is a time step to be used for the update. */ + virtual TimeStepType CalculateChange(); + + /** The buffer that holds the updates for an iteration of the algorithm. */ + std::vector< UpdateBufferPointer > m_UpdateBuffers; +}; + + +}// end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkMultiphaseDenseFiniteDifferenceImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.txx b/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.txx new file mode 100644 index 0000000000..cb84671a64 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.txx @@ -0,0 +1,297 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMultiphaseDenseFiniteDifferenceImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-21 22:03:29 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkMultiphaseDenseFiniteDifferenceImageFilter_txx +#define __itkMultiphaseDenseFiniteDifferenceImageFilter_txx + +#include "itkMultiphaseDenseFiniteDifferenceImageFilter.h" + +namespace itk +{ + +template < class TInputImage, + class TOutputImage, + class TFunction, + typename TIdCell > +void +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, TFunction, TIdCell > +::CopyInputToOutput() +{ + OutputImagePointer output = this->GetOutput(); + + for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + InputImagePointer input = this->m_LevelSet[i]; + InputPointType origin = input->GetOrigin(); + InputSpacingType spacing = input->GetSpacing(); + InputSizeType size = input->GetLargestPossibleRegion().GetSize(); + + OutputIndexType start; + + // FIXME: Review pixel centering policy here !!! + // Probably the PhysicalPointToIndex method should be used here... + // + for ( unsigned int j = 0; j < ImageDimension; j++ ) + { + start[j] = static_cast<OutputIndexValueType>( origin[j]/spacing[j] ); + } + + OutputRegionType region; + region.SetSize( size ); + region.SetIndex( start ); + + if ( !input || !output ) + { + itkExceptionMacro ( << "Either input and/or output is NULL." ); + } + + ImageRegionIterator< InputImageType > in( input, input->GetLargestPossibleRegion() ); + ImageRegionIterator< OutputImageType > out( output, region ); + + // Fill the output pointer + OutputPixelType p = static_cast<OutputPixelType> ( this->m_Lookup[i] ); + + in.GoToBegin(); + out.GoToBegin(); + + while( !out.IsAtEnd() ) + { + if( in.Get() < 0 ) + { + out.Value() = p; + } + else + { + out.Value() = 0; + } + ++in; + ++out; + } + } +} + +template < class TInputImage, + class TOutputImage, + class TFunction, + typename TIdCell > +void +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, TFunction, TIdCell > +::AllocateUpdateBuffer() +{ + for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + InputImagePointer input = this->m_LevelSet[i]; + InputRegionType region = input->GetLargestPossibleRegion(); + + m_UpdateBuffers[i]->CopyInformation( input ); + m_UpdateBuffers[i]->SetRegions( region ); + m_UpdateBuffers[i]->Allocate(); + } +} + +template < class TInputImage, + class TOutputImage, + class TFunction, + typename TIdCell > +typename +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, TFunction, TIdCell >::TimeStepType +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, TFunction, TIdCell > +::CalculateChange() +{ + TimeStepType timeStep = NumericTraits< TimeStepType >::max(); + + for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + OutputImagePointer levelset = this->m_LevelSet[i]; + + // Get the FiniteDifferenceFunction to use in calculations. + const FiniteDifferenceFunctionPointer df = this->m_DifferenceFunctions[i]; + + const OutputSizeType radius = df->GetRadius(); + + // Break the input into a series of regions. The first region is free + // of boundary conditions, the rest with boundary conditions. We operate + // on the levelset region because input has been copied to output. + FaceCalculatorType faceCalculator; + FaceListType faceList = + faceCalculator ( levelset, levelset->GetLargestPossibleRegion(), radius ); + + void *globalData; + + // Ask the function object for a pointer to a data structure it + // will use to manage any global values it needs. We'll pass this + // back to the function object at each calculation and then + // again so that the function object can use it to determine a + // time step for this iteration. + globalData = df->GetGlobalDataPointer(); + + typename FaceListType::iterator fIt; + for ( fIt = faceList.begin(); fIt != faceList.end(); ++fIt ) + { + // Process the non-boundary region. + NeighborhoodIteratorType nD ( radius, levelset, *fIt ); + UpdateIteratorType nU ( m_UpdateBuffers[i], *fIt ); + + nD.GoToBegin(); + nU.GoToBegin(); + + while( !nD.IsAtEnd() ) + { + nU.Value() = df->ComputeUpdate ( nD, globalData ); + ++nD; + ++nU; + } + } + + // Ask the finite difference function to compute the time step for + // this iteration. We give it the global data pointer to use, then + // ask it to free the global data memory. + TimeStepType dt = df->ComputeGlobalTimeStep ( globalData ); + df->ReleaseGlobalDataPointer ( globalData ); + + if ( dt < timeStep ) + { + timeStep = dt; + } + } + + timeStep = 0.08; // FIXME !!! After all this work, assign a constant !!! Why ?? + + return timeStep; +} + +template< class TInputImage, + class TOutputImage, + class TFunction, + typename TIdCell > +void +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, TFunction, TIdCell > +::SetFunctionCount( const IdCellType& n ) +{ + this->Superclass::SetFunctionCount( n ); + + this->m_UpdateBuffers.resize( n, 0 ); + + for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_UpdateBuffers[i] = UpdateBufferType::New(); + } +} + +template< class TInputImage, + class TOutputImage, + class TFunction, + typename TIdCell > +void +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, TFunction, TIdCell > +::ApplyUpdate ( TimeStepType dt ) +{ + double rms_change_accumulator = 0; + double den = 0; + IdCellType i; + + for( i = 0; i < this->m_FunctionCount; i++ ) + { + const double img_size = this->m_LevelSet[i]->GetLargestPossibleRegion().GetNumberOfPixels(); + den += img_size; + } + + // this must never occur! + if( den < vnl_math::eps ) + { + itkExceptionMacro( "den = 0." ); + } + + // Updating the output image + for ( i = 0; i < this->m_FunctionCount; i++ ) + { + //NOTE: here this->m_LevelSet[i]->GetRequestedRegion() is used and previously + // it is this->m_LevelSet[i]->GetLargestPossibleRegion() + InputRegionType region = this->m_LevelSet[i]->GetRequestedRegion(); + + ImageRegionIterator<UpdateBufferType> u ( m_UpdateBuffers[i], region ); + ImageRegionIterator<OutputImageType> o ( this->m_LevelSet[i], region ); + + u.GoToBegin(); + o.GoToBegin(); + + while( !u.IsAtEnd() ) + { + u.Set( o.Value() + static_cast<OutputPixelType> ( dt ) * u.Get() ); + ++u; + ++o; + } + + if ( this->GetElapsedIterations() % this->m_ReinitializeCounter == 0 ) + { + ThresholdFilterPointer thresh = ThresholdFilterType::New(); + thresh->SetLowerThreshold( NumericTraits< OutputPixelType >::NonpositiveMin() ); + thresh->SetUpperThreshold( 0 ); + thresh->SetInsideValue( 1 ); + thresh->SetOutsideValue( 0 ); + thresh->SetInput( m_UpdateBuffers[i] ); + thresh->Update(); + + MaurerPointer maurer = MaurerType::New(); + maurer->SetInput( thresh->GetOutput() ); + maurer->SetSquaredDistance( 0 ); + maurer->SetUseImageSpacing( this->m_UseImageSpacing ); + maurer->SetInsideIsPositive( 0 ); + maurer->Update(); + + ImageRegionIterator< OutputImageType > it ( maurer->GetOutput(), region ); + + o.GoToBegin(); + it.GoToBegin(); + + OutputPixelType val; + + while( !o.IsAtEnd() ) + { + val = it.Value(); + rms_change_accumulator += static_cast<double> ( vnl_math_sqr( o.Value() - val ) ); + o.Set( val ); + ++o; + ++it; + } + } + } + + this->SetRMSChange( vcl_sqrt(rms_change_accumulator / den ) ); +} + +template< class TInputImage, + class TOutputImage, + class TFunction, + typename TIdCell > +void +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, TFunction, TIdCell > +::PostProcessOutput() +{ + this->CopyInputToOutput(); +} + +}// end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.h b/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.h new file mode 100644 index 0000000000..ec0db2c8dc --- /dev/null +++ b/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.h @@ -0,0 +1,520 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMultiphaseFiniteDifferenceImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-16 12:35:48 $ + Version: $Revision: 1.5 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkMultiphaseFiniteDifferenceImageFilter_h +#define __itkMultiphaseFiniteDifferenceImageFilter_h + +#include "itkArray.h" +#include "itkInPlaceImageFilter.h" +#include "itkFiniteDifferenceFunction.h" +#include <vnl/vnl_vector.h> +#include "itkImageRegionIterator.h" + +#include "itkVector.h" +#include "itkListSample.h" +#include "itkKdTree.h" +#include "itkKdTreeGenerator.h" + +namespace itk { + +/** + * \class MultiphaseFiniteDifferenceImageFilter + * + * \par The Finite Difference Solver Hierarchy + * + * This is an alternate version of the ITK finite difference solver (FDS) + * framework, supporting the solution of multiple functions, simultaneously. + * The FDS framework is a set of classes for creating filters to solve partial + * differential equations on images using an iterative, finite difference + * update scheme. + * + * \par + * The high-level algorithm implemented by the framework can be described by + * the following pseudocode. + * + * \code + * WHILE NOT convergence: + * FOR ALL pixels i + * FOR ALL functions f + * min_time_step = min(min_time_step, calculate_change(f, i)) + * FOR ALL functions f + * update(f, i, time_step) + * \endcode + * + * \par + * The following equation describes update \f$n+1\f$ at pixel \f$i\f$ on + * discrete image \f$ u \f$ : + * + * \par + * \f$u_{\mathbf{i}}^{n+1}=u^n_{\mathbf{i}}+\Delta u^n_{\mathbf{i}}\Delta t\f$ + * + * \par Component objects + * The FDS hierarchy is comprised of two component object types, variations of + * which are designed to be plugged together to create filters for different + * applications. At the process level are the ``solver'' objects, which are + * subclasses of MultiphaseFiniteDifferenceImageFilter. Solver objects are filters that + * take image inputs and produce image outputs. Solver objects require a + * ``finite difference function'' object to perform the calculation at each + * image pixel during iteration. These specialized function objects are + * subclasses of FiniteDifferenceFunction. FiniteDifferenceFunctions take a + * neighborhood of pixels as input (in the form of an + * itk::NeighborhoodIterator) and produce a scalar valued result. + * + * \par + * Filters for different applications are created by defining a function object + * to handle the numerical calculations and choosing (or creating) a solver + * object that reflects the requirements and constraints of the application. + * For example, anisotropic diffusion filters are created by plugging + * anisotropic diffusion functions into the DenseFiniteDifferenceImageFilter2. + * The separation between function object and solver object allows us to + * create, for example, sparse-field, dense-field, and narrow-band + * implementations of a level-set surface evolution filter can all be + * constructed by plugging the same function object into three different, + * specialized solvers. + * + * \par Creating new filters in this hierarchy + * The procedure for creating a filter within the FDS hierarchy is to identify + * all the virtual methods that need to be defined for your particular + * application. In the simplest case, a filter needs only to instantiate a + * specific function object and define some halting criteria. For more + * complicated applications, you may need to define a specialized type of + * iteration scheme or updating procedure in a higher-level solver object. + * + * \par + * Some simple examples are the specific subclasses of + * AnisotropicDiffusionImageFilter. The leaves of the anisotropic diffusion + * filter tree only define the function object they use for their particular + * flavor of diffusion. See CurvatureAnisotropicDiffusionImageFilter and + * GradientAnisotropicDiffusionImageFilter for details. + * + * \par FiniteDifferenceImageFilter2 + * This class defines the generic solver API at the top level of the FDS + * framework. FiniteDifferenceImageFilter2 is an abstract class that implements + * the generic, high-level algorithm (described above). + * + * \par Inputs and Outputs + * This filter is an Image to Image filter. Depending on the specific + * subclass implementation, finite difference image filters may process a + * variety of image types. The input to the filter is the initial + * value of \f$ u \f$ and the output of the filter is the solution to the + * p.d.e. + * + * \par How to use this class + * GenerateData() relies on several virtual methods that must be defined by a + * subclass. Specifically: \em AllocateUpdateBuffer \em ApplyUpdate + * \em CalculateChange and \em Halt. To create a finite difference solver, + * implement a subclass to define these methods. + * + * \par + * Note that there is no fixed container type for the buffer used to hold the + * update \f$ \Delta \f$. The container might be another image, or simply a + * list of values. AllocateUpdateBuffer is responsible for creating the \f$ + * \Delta \f$ container. CalculateChange populates this buffer and ApplyUpdate + * adds the buffer values to the output image (solution). The boolean Halt() + * (or ThreadedHalt) method returns a true value to stop iteration. + * + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + * \ingroup ImageFilter + * \ingroup LevelSetSegmentation + * \sa DenseFiniteDifferenceImageFilter2 */ + template < class TInputImage, + class TOutputImage, + class TFiniteDifferenceFunction = FiniteDifferenceFunction<TOutputImage>, + typename TIdCell = unsigned int > +class ITK_EXPORT MultiphaseFiniteDifferenceImageFilter + : public InPlaceImageFilter< TInputImage, TOutputImage > +{ +public: + /** Standard class typedefs. */ + typedef MultiphaseFiniteDifferenceImageFilter Self; + typedef InPlaceImageFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods) */ + itkTypeMacro( MultiphaseFiniteDifferenceImageFilter, InPlaceImageFilter ); + + /** Input and output image types. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::RegionType InputRegionType; + typedef typename InputImageType::SizeType InputSizeType; + typedef typename InputImageType::SpacingType InputSpacingType; + typedef typename InputImageType::PointType InputPointType; + typedef typename InputImageType::PixelType InputPixelType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename OutputImageType::RegionType OutputRegionType; + typedef typename OutputImageType::SizeType OutputSizeType; + typedef typename OutputImageType::SizeValueType OutputSizeValueType; + typedef typename OutputImageType::IndexType OutputIndexType; + typedef typename OutputImageType::IndexValueType OutputIndexValueType; + + typedef TIdCell IdCellType; + typedef std::vector< IdCellType > VectorIdCellType; + + /** Dimensionality of input and output data is assumed to be the same. */ + itkStaticConstMacro(ImageDimension, unsigned int, OutputImageType::ImageDimension); + + /** The value type of the time step. This is distinct from PixelType + * because PixelType may often be a vector value, while the TimeStep is + * a scalar value. */ + typedef TFiniteDifferenceFunction FiniteDifferenceFunctionType; + typedef typename FiniteDifferenceFunctionType::Pointer FiniteDifferenceFunctionPointer; + typedef typename FiniteDifferenceFunctionType::TimeStepType TimeStepType; + typedef typename std::vector< TimeStepType > TimeStepVectorType; + typedef typename FiniteDifferenceFunctionType::RadiusType RadiusType; + + typedef Vector< float, itkGetStaticConstMacro(ImageDimension) > + CentroidVectorType; + typedef Statistics::ListSample< CentroidVectorType > SampleType; + typedef Statistics::KdTreeGenerator< SampleType > KdTreeGeneratorType; + typedef typename KdTreeGeneratorType::Pointer KdTreeGeneratorPointer; + typedef typename KdTreeGeneratorType::KdTreeType KdTreeType; + typedef typename KdTreeType::Pointer KdTreePointer; + + /** This method returns a pointer to a FiniteDifferenceFunction object that + * will be used by the filter to calculate updates at image pixels. + * \param functionIndex Index of difference function to return. + * \returns A FiniteDifferenceObject pointer. */ + virtual const FiniteDifferenceFunctionPointer GetDifferenceFunction( + const IdCellType& functionIndex ) const + { + if( functionIndex < m_FunctionCount ) + { + return ( this->m_DifferenceFunctions[functionIndex] ); + } + else + { + return 0; + } + } + + /** This method sets the pointer to a FiniteDifferenceFunction object that + * will be used by the filter to calculate updates at image pixels. + * \param functionIndex Index of difference function to set. + * \param function Pointer to difference function to set. */ + virtual void SetDifferenceFunction( const IdCellType& functionIndex, + FiniteDifferenceFunctionPointer function) + { + if( functionIndex < m_FunctionCount ) + { + this->m_DifferenceFunctions[functionIndex] = function; + } + } + + /** Set/Get the number of iterations that the filter will run. */ + itkSetMacro(NumberOfIterations, unsigned int); + itkGetConstReferenceMacro(NumberOfIterations, unsigned int); + + /** Use the image spacing information in calculations. Use this option if you + * want derivatives in physical space. Default is UseImageSpacingOff. */ + itkSetMacro(UseImageSpacing,bool); + itkBooleanMacro(UseImageSpacing); + itkGetConstReferenceMacro(UseImageSpacing, bool); + + /** Set/Get the maximum error allowed in the solution. This may not be + * defined for all solvers and its meaning may change with the application. */ + itkSetMacro(MaximumRMSError, double); + itkGetConstReferenceMacro(MaximumRMSError, double); + + /** Set/Get the root mean squared change of the previous iteration. May not + be used by all solvers. */ + itkSetMacro(RMSChange, double); + itkGetConstReferenceMacro(RMSChange, double); + + /** Set/Get the state of the filter. */ + itkSetMacro( InitializedState, bool ); + itkGetConstReferenceMacro( InitializedState, bool ); + itkBooleanMacro( InitializedState ); + + /** Require the filter to be manually reinitialized (by calling + SetInitializedStateOff() */ + itkSetMacro( ManualReinitialization, bool ); + itkGetConstReferenceMacro( ManualReinitialization, bool ); + itkBooleanMacro( ManualReinitialization ); + + /** Set the number of elapsed iterations of the filter. */ + itkSetMacro( ElapsedIterations, unsigned int ); + + /** Get the number of elapsed iterations of the filter. */ + itkGetConstReferenceMacro( ElapsedIterations, unsigned int ); + + void SetLevelSet( const IdCellType & i, const InputImageType * levelSet ) + { + m_LevelSet[i] = InputImageType::New(); + m_LevelSet[i]->SetRequestedRegion( levelSet->GetRequestedRegion() ); + m_LevelSet[i]->SetBufferedRegion( levelSet->GetBufferedRegion() ); + m_LevelSet[i]->SetLargestPossibleRegion( levelSet->GetLargestPossibleRegion() ); + m_LevelSet[i]->Allocate(); + m_LevelSet[i]->CopyInformation( levelSet ); + + ImageRegionConstIterator< InputImageType > in ( levelSet, levelSet->GetBufferedRegion()); + ImageRegionIterator< InputImageType > cp ( m_LevelSet[i], levelSet->GetBufferedRegion() ); + + in.GoToBegin(); + cp.GoToBegin(); + + while( !in.IsAtEnd() ) + { + cp.Set( in.Get() ); + ++in; + ++cp; + } + } + + InputImagePointer GetLevelSet( const IdCellType& i ) + { + if( i >= m_FunctionCount ) + { + itkExceptionMacro("Request for level set #" << i + << " but there are only " << m_FunctionCount ); + } + else + { + return m_LevelSet[i]; + } + } + + void SetLookup ( VectorIdCellType lookup ) + { + this->m_Lookup = lookup; + } + + void SetKdTree( KdTreeType * kdtree ) + { + this->m_KdTree = kdtree; + } + + void SetFunctionCount( const IdCellType& n ) + { + m_FunctionCount = n; + + m_DifferenceFunctions.resize( m_FunctionCount, 0 ); + + RadiusType radius; + radius.Fill( 1 ); + + for( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_DifferenceFunctions[i] = FiniteDifferenceFunctionType::New(); + this->m_DifferenceFunctions[i]->Initialize(radius); + } + + // Initialize the images + m_LevelSet.resize( m_FunctionCount, 0 ); + + // Initialize the lookup table + this->m_Lookup.resize( m_FunctionCount ); + + IdCellType k = 1; + + typedef typename std::vector< IdCellType >::iterator VectorIteratorType; + + VectorIteratorType it = this->m_Lookup.begin(); + + while( it != this->m_Lookup.end() ) + { + *it = k; + ++it; + ++k; + } + } + +protected: + MultiphaseFiniteDifferenceImageFilter() + { + this->m_KdTree = 0; + this->m_ElapsedIterations = 0; + this->m_MaximumRMSError = vnl_math::eps; + this->m_RMSChange = 100.0; + this->m_UseImageSpacing = true; + this->m_ManualReinitialization = false; + this->m_InitializedState = false; + this->m_NumberOfIterations = NumericTraits<unsigned int>::max(); + this->m_FunctionCount = 0; + this->InPlaceOn(); + } + + ~MultiphaseFiniteDifferenceImageFilter(){} + + IdCellType m_FunctionCount; + std::vector< InputImagePointer > m_LevelSet; + VectorIdCellType m_Lookup; + KdTreePointer m_KdTree; + + unsigned int m_ElapsedIterations; + double m_MaximumRMSError; + double m_RMSChange; + unsigned int m_NumberOfIterations; + + /** The function that will be used in calculating updates for each pixel. */ + std::vector< FiniteDifferenceFunctionPointer > m_DifferenceFunctions; + + /** Control whether derivatives use spacing of the input image in its + * calculation. */ + bool m_UseImageSpacing; + + void PrintSelf(std::ostream& os, Indent indent) const; + + /** This method allocates a temporary update container in the subclass. */ + virtual void AllocateUpdateBuffer() = 0; + + /** This method is defined by a subclass to apply changes to the output + * from an update buffer and a time step value "dt". + * \param dt Time step value. */ + virtual void ApplyUpdate(TimeStepType dt) = 0; + + /** This method is defined by a subclass to populate an update buffer + * with changes for the pixels in the output. It returns a time + * step value to be used for the update. + * \returns A time step to use in updating the output with the changes + * calculated from this method. */ + virtual TimeStepType CalculateChange() = 0; + + /** This method can be defined in subclasses as needed to copy the input + * to the output. See DenseFiniteDifferenceImageFilter2 for an + * implementation. */ + virtual void CopyInputToOutput() = 0; + + /** This is the default, high-level algorithm for calculating finite + * difference solutions. It calls virtual methods in its subclasses + * to implement the major steps of the algorithm. */ + virtual void GenerateData(); + + /** FiniteDifferenceImageFilter2 needs a larger input requested region than + * the output requested region. As such, we need to provide + * an implementation for GenerateInputRequestedRegion() in order to inform + * the pipeline execution model. + * + * \par + * The filter will ask for a padded region to perform its neighborhood + * calculations. If no such region is available, the boundaries will be + * handled as described in the FiniteDifferenceFunction defined by the + * subclass. + * \sa ProcessObject::GenerateInputRequestedRegion() */ + virtual void GenerateInputRequestedRegion(); + + /** This method returns true when the current iterative solution of the + * equation has met the criteria to stop solving. Defined by a subclass. */ + virtual bool Halt(); + + /** This method is similar to Halt(), and its default implementation in this + * class is simply to call Halt(). However, this method takes as a parameter a + * void pointer to the MultiThreader::ThreadInfoStruct structure. If you + * override this method instead of overriding Halt, you will be able to get the + * current thread ID and handle the Halt method accordingly. This is useful if + * you are doing a lot of processing in Halt that you don't want parallelized. + * Notice that ThreadedHalt is only called by the multithreaded filters, so you + * still should implement Halt, just in case a non-threaded filter is used. + */ + virtual bool ThreadedHalt(void *itkNotUsed(threadInfo)) + { + return this->Halt(); + } + + /** This method is optionally defined by a subclass and is called before + * the loop of iterations of calculate_change & upate. It does the global + * initialization, i.e. in the SparseFieldLevelSetImageFilter, initialize + * the list of layers. + * */ + virtual void Initialize() { }; + + /** This method is optionally defined by a subclass and is called immediately + * prior to each iterative CalculateChange-ApplyUpdate cycle. It can be + * used to set global variables needed for the next iteration (ie. average + * gradient magnitude of the image in anisotropic diffusion functions), or + * otherwise prepare for the next iteration. + * */ + virtual void InitializeIteration() + { + for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_DifferenceFunctions[i]->InitializeIteration(); + } + } + + /** Virtual method for resolving a single time step from a set of time steps + * returned from processing threads. + * \return Time step (dt) for the iteration update based on a list + * of time steps generated from the threaded calculated change method (one + * for each region processed). + * + * \param timeStepList The set of time changes compiled from all the threaded + * calls to ThreadedGenerateData. + * + * \param valid The set of flags indicating which of "list" elements are valid + * \param size The size of "list" and "valid" + * + * The default is to return the minimum value in the list. */ + inline TimeStepType ResolveTimeStep(const TimeStepVectorType& timeStepList, + const std::vector< bool >& valid ); + + /** This method is called after the solution has been generated to allow + * subclasses to apply some further processing to the output. */ + virtual void PostProcessOutput() {} + + +private: + MultiphaseFiniteDifferenceImageFilter(const Self&); + //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Indicates whether the filter automatically resets to UNINITIALIZED state + after completing, or whether filter must be manually reset */ + bool m_ManualReinitialization; + + /** State that the filter is in, i.e. UNINITIALIZED or INITIALIZED */ + bool m_InitializedState; +}; + +}// end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkMultiphaseFiniteDifferenceImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.txx b/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.txx new file mode 100644 index 0000000000..980944f62a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.txx @@ -0,0 +1,319 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMultiphaseFiniteDifferenceImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-20 22:03:45 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkMultiphaseFiniteDifferenceImageFilter_txx +#define __itkMultiphaseFiniteDifferenceImageFilter_txx + +#include "itkMultiphaseFiniteDifferenceImageFilter.h" +#include "itkImageRegionIterator.h" +#include "itkImageRegionConstIterator.h" +#include "itkExceptionObject.h" +#include "itkEventObject.h" + +namespace itk { + +template < class TInputImage, + class TOutputImage, + class TFiniteDifferenceFunction, + typename TIdCell > +void +MultiphaseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFiniteDifferenceFunction, + TIdCell > +::GenerateData() +{ + if( ! this->m_FunctionCount ) + { + itkExceptionMacro("Number of level set functions not specified. " + << "Please set using SetFunctionCount()" ); + } + + if( ! this->m_InitializedState ) + { + // Set the coefficients for the deriviatives + double coeffs[ImageDimension]; + unsigned int i; + if (m_UseImageSpacing) + { + for (i = 0; i < ImageDimension; i++) + { + coeffs[i] = 1.0 / m_LevelSet[0]->GetSpacing()[i]; + } + } + else + { + for (i = 0; i < ImageDimension; i++) + { + coeffs[i] = 1.0; + } + } + + for( IdCellType id = 0; id < this->m_FunctionCount; id++ ) + { + this->m_DifferenceFunctions[id]->SetScaleCoefficients(coeffs); + } + + // Allocate the output image -- inherited + this->AllocateOutputs(); + + // Copy the input image to the output image. Algorithms will operate + // directly on the output image and the update buffer. + this->CopyInputToOutput(); + + // Perform any other necessary pre-iteration initialization. + this->Initialize(); + + // Allocate the internal update buffer. This takes place entirely within + // the subclass, since this class cannot define an update buffer type. + this->AllocateUpdateBuffer(); + + this->SetInitializedState(true); + + this->m_ElapsedIterations = 0; + } + + // Iterative algorithm + TimeStepType dt; + + while ( ! this->Halt() ) + { + /* An optional method for precalculating global values, or setting + up for the next iteration*/ + this->InitializeIteration(); + + dt = this->CalculateChange(); + + this->ApplyUpdate( dt ); + this->m_ElapsedIterations++; + + // Invoke the iteration event. + this->InvokeEvent( IterationEvent() ); + + if( this->GetAbortGenerateData() ) + { + this->InvokeEvent( IterationEvent() ); + this->ResetPipeline(); + throw ProcessAborted(__FILE__,__LINE__); + } + } + + // Reset the state once execution is completed + if( !this->m_ManualReinitialization ) + { + this->SetInitializedState(true); + } + + // Any further processing of the solution can be done here. + this->PostProcessOutput(); +} + +/** + * + */ +template < class TInputImage, + class TOutputImage, + class TFiniteDifferenceFunction, + typename TIdCell > +void +MultiphaseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFiniteDifferenceFunction, + TIdCell > +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + // copy the output requested region to the input requested region + Superclass::GenerateInputRequestedRegion(); + + // get pointers to the input + InputImagePointer inputPtr = + const_cast< InputImageType* >( this->GetInput(0) ); + + if ( inputPtr.IsNull() ) + { + return; + } + + if( this->m_DifferenceFunctions[0].IsNull() ) + { + return; + } + + // Get the size of the neighborhood on which we are going to operate. This + // radius is supplied by the difference function we are using. + RadiusType radius = this->m_DifferenceFunctions[0]->GetRadius(); + + // Try to set up a buffered region that will accommodate our + // neighborhood operations. This may not be possible and we + // need to be careful not to request a region outside the largest + // possible region, because the pipeline will give us whatever we + // ask for. + + // get a copy of the input requested region (should equal the output + // requested region) + InputRegionType inputRequestedRegion; + inputRequestedRegion = inputPtr->GetRequestedRegion(); + + // pad the input requested region by the operator radius + inputRequestedRegion.PadByRadius( radius ); + + // crop the input requested region at the input's largest possible region + if ( inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() ) ) + { + inputPtr->SetRequestedRegion( inputRequestedRegion ); + return; + } + else + { + // Couldn't crop the region (requested region is outside the largest + // possible region). Throw an exception. + + // store what we tried to request (prior to trying to crop) + inputPtr->SetRequestedRegion( inputRequestedRegion ); + + // build an exception + InvalidRequestedRegionError e(__FILE__, __LINE__); + e.SetLocation(ITK_LOCATION); + e.SetDescription("Requested region is (at least partially) outside the " + "largest possible region."); + e.SetDataObject(inputPtr); + throw e; + } +} + +template < class TInputImage, + class TOutputImage, + class TFiniteDifferenceFunction, + typename TIdCell > +typename MultiphaseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, TFiniteDifferenceFunction, TIdCell >::TimeStepType +MultiphaseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFiniteDifferenceFunction, + TIdCell > +::ResolveTimeStep( const TimeStepVectorType &timeStepList, + const std::vector< bool >& valid ) +{ + TimeStepType oMin = NumericTraits<TimeStepType>::Zero; + size_t size = timeStepList.size(); + + if( size == valid.size() ) + { + bool flag = false; + size_t k = 0; + size_t i; + + for( i = 0; i < size; ++i) + { + if (valid[i]) + { + oMin = timeStepList[i]; + k = i; + flag = true; + break; + } + } + + if( !flag ) + { + itkExceptionMacro("No Values"); + } + + // find minimum value + for ( i = k; i < size; ++i) + { + if ( valid[i] && (timeStepList[i] < oMin) ) + { + oMin = timeStepList[i]; + } + } + } + + return oMin; +} + +template < class TInputImage, + class TOutputImage, + class TFiniteDifferenceFunction, + typename TIdCell > +bool +MultiphaseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFiniteDifferenceFunction, + TIdCell > +::Halt() +{ + float progress = 0.; + + if( this->m_NumberOfIterations != 0 ) + { + progress = static_cast<float>( this->GetElapsedIterations() ) + / static_cast<float>( this->m_NumberOfIterations ); + } + this->UpdateProgress( progress ); + + return ( (this->GetElapsedIterations() >= this->m_NumberOfIterations) || + ( this->GetMaximumRMSError() >= m_RMSChange ) ); +} + + +template < class TInputImage, + class TOutputImage, + class TFiniteDifferenceFunction, + typename TIdCell > +void +MultiphaseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFiniteDifferenceFunction, + TIdCell > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "ElapsedIterations: " << this->m_ElapsedIterations << std::endl; + os << indent << "UseImageSpacing: " << (m_UseImageSpacing ? "On" : "Off") << std::endl; + os << indent << "State: " << this->m_InitializedState << std::endl; + os << indent << "MaximumRMSError: " << m_MaximumRMSError << std::endl; + os << indent << "NumberOfIterations: " << this->m_NumberOfIterations << std::endl; + os << indent << "ManualReinitialization: " << this->m_ManualReinitialization << std::endl; + os << indent << "RMSChange: " << m_RMSChange << std::endl; + os << std::endl; + + if ( this->m_FunctionCount ) + { + if( this->m_DifferenceFunctions[0] ) + { + os << indent << "DifferenceFunction: " << std::endl; + for( IdCellType i = 0; i < this->m_FunctionCount; ++i ) + { + this->m_DifferenceFunctions[i]->Print(os,indent.GetNextIndent()); + } + } + } + else + { + os << indent << "DifferenceFunction: " << "(None)" << std::endl; + } + + os << std::endl; +} + + +}// end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.h b/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.h new file mode 100644 index 0000000000..87044694b9 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.h @@ -0,0 +1,530 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMultiphaseSparseFiniteDifferenceImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-15 20:43:38 $ + Version: $Revision: 1.7 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkMultiphaseSparseFiniteDifferenceImageFilter_h +#define __itkMultiphaseSparseFiniteDifferenceImageFilter_h + +#include "itkMultiphaseFiniteDifferenceImageFilter.h" +#include "itkMultiThreader.h" +#include "itkSparseFieldLayer.h" +#include "itkObjectStore.h" +#include "itkNeighborhoodIterator.h" +#include "itkZeroCrossingImageFilter.h" +#include "itkImageRegionIterator.h" +#include "itkImageRegionConstIterator.h" +#include "itkShiftScaleImageFilter.h" +#include "itkNeighborhoodAlgorithm.h" +#include "itkSparseFieldLevelSetImageFilter.h" + +#include <vector> + +namespace itk { +/** + * \class MultiphaseSparseFiniteDifferenceImageFilter + * + * \brief This class implements a finite difference partial differential + * equation solver for evolving surfaces embedded in volumes as level-sets. + * + * \par + * The "sparse field" approach to the level-set model is a logical extension + * of the classical narrow band technique, which seeks to minimize + * computational effort by restricting calculations to those pixels in a + * region of interest around the moving surface (the \f$k\f$-level curve). The + * sparse field method uses a narrow band that is exactly the width needed to + * calculate changes on the level curve for the next time step. Because the + * band of grid points under consideration is so sparse, this approach has + * several advantages: the algorithm does exactly the number of calculations + * needed to determine the next position of the \f$k\f$-level curve, and the + * distance transform around the level curve can be recomputed at each + * iteration. + * + * \par + * The sparse field algorithm works by constructing a linked list of indices + * that are adjacent to the \f$k\f$-level set. These indices are called the + * "active set". The values at these active set indices define the + * position of the \f$k\f$-level curve. The active set indices are shifted + * to follow the distance transform embedding of the \f$k\f$-level curve as + * their values move in and out of a fixed numerical range about \f$k\f$. In + * this way, the active set is maintained as only those pixels adjacent to the + * evolving surface. Calculations are then done only at indices contained in + * the active set. + * + * \par + * The city-block neighborhoods of the active set indices are maintained as + * separate lists called ``layers''. At each iteration, the values at the + * layers are reinitialized as the distance transform from the active set. + * The number of layers can be adjusted according to the footprint needed for + * the calculations on the level curve. + * + * \par + * Briefly, the sparse field solver algorithm is as follows: + * + * \par + * 1. For each active layer index \f$x_j\f$: Compute the change at + * \f$u_{x_j}\f$, the grid point in the embedding, based on local + * geometry and external forces and using a stable numerical scheme. + * + * 2. For each active layer index \f$x_j\f$, add the change to the grid point + * value and redefine the active set indices and those of its layers based on + * any value changes which have moved outside of the numerical range allowed + * for the active set. + * + * 3. Starting with the first layers adjacent to the active set and moving + * outwards, reconstruct the distance transform by setting values in the + * layers according to their neighbors. At the very outer layers, add or + * remove indices which have come into or moved out of the sparse field. + * + * \par HOW TO USE THIS CLASS + * Typically, this class should be subclassed with additional functionality + * for specific applications. It is possible, however to use this solver as a + * filter directly by instantiating it and supplying it with an appropriate + * LevelSetFunction object via the SetDifferenceFunction method. See the + * subclasses and their associated documentation for more information on using + * this class. Also see the FiniteDifferenceImageFilter2 documentation for a + * general overview of this class of solvers. + * + * \par INPUTS + * This filter takes an itk::Image as input. The appropriate type of input + * image is entirely determined by the application. As a rule, however, the + * input type is immediately converted to the output type before processing. + * This is because the input is not assumed to be a real value type and must be + * converted to signed, real values for the calculations. The input values + * will also be shifted by the \f$k\f$ isosurface value so that the algorithm + * only needs to consider the zero level set. + * + * \par OUTPUTS + * The output of the filter is the distance transform embedding of the + * isosurface as the zero level set. Values INSIDE the surface will be + * NEGATIVE and values OUTSIDE the surface will be POSITIVE. The distance + * transform only holds for those indices in layers around the active layer. + * Elsewhere, the values are a fixed positive or negative that is one greater + * than the layer of greatest magnitude. In other words, if there are three + * layers, then inside values reach a minimum of -4.0 and outside values a + * maximum of 4.0.IndexType + *this->SetNumberOfLayers(5); + * \par PARAMETERS + * The NumberOfLayers parameter controls the number of layers inside and + * outside of the active set (see description above). The sparse field will + * contain 2*NumberOfLayers+1 lists of indices: the active set and city block + * neighbors inside and outside the active set. It is important to + * specify enough layers to cover the footprint of your calculations. + * Curvature calculations in three dimensions, for example, require 3 layers. + * In two dimensions, a minimum of 2 layers is probably required. Higher order + * derivatives and other geometrical measures may require more layers. If too + * few layers are specified, then the calculations will pull values from the + * background, which may consist of arbitrary or random values. + * + * \par + * The IsoSurfaceValue indicates which value in the input represents the + * interface of interest. By default, this value is zero. When the solver + * initializes, it will subtract the IsoSurfaceValue from all values, in the + * input, shifting the isosurface of interest to zero in the output. + * + * \par IMPORTANT! + * Read the documentation for FiniteDifferenceImageFilter2 before attempting to + * use this filter. The solver requires that you specify a + * FiniteDifferenceFunction to use for calculations. This is set using the + * method SetDifferenceFunction in the parent class. + * + * \par REFERENCES + * Whitaker, Ross. A Level-Set Approach to 3D Reconstruction from Range Data. + * International Journal of Computer Vision. V. 29 No. 3, 203-231. 1998. + * + * \par + * Sethian, J.A. Level Set Methods. Cambridge University Press. 1996. + * + * + * + * This code was adapted from the paper + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + */ +template < class TInputImage, class TOutputImage, class TFunction, + typename TIdCell = unsigned int > +class ITK_EXPORT MultiphaseSparseFiniteDifferenceImageFilter : + public MultiphaseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +{ +public: + /** Standard class typedefs */ + typedef MultiphaseSparseFiniteDifferenceImageFilter Self; + typedef MultiphaseFiniteDifferenceImageFilter< + TInputImage, TOutputImage, TFunction, TIdCell > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro( MultiphaseSparseFiniteDifferenceImageFilter, MultiphaseFiniteDifferenceImageFilter ); + + /**Typedefs from the superclass */ + typedef typename Superclass::TimeStepType TimeStepType; + + /** Information derived from the image types. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::InputSizeType InputSizeType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputRegionType InputRegionType; + typedef typename Superclass::InputSpacingType InputSpacingType; + typedef typename Superclass::InputPointType InputPointType; + + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputRegionType OutputRegionType; + typedef typename Superclass::OutputSizeType OutputSizeType; + typedef typename Superclass::OutputSizeValueType SizeValueType; + typedef typename OutputImageType::ValueType ValueType; + typedef typename Superclass::OutputIndexType OutputIndexType; + typedef typename Superclass::OutputIndexValueType OutputIndexValueType; + typedef typename Superclass::OutputPixelType OutputPixelType; + + typedef typename Superclass::IdCellType IdCellType; + + + itkStaticConstMacro( ImageDimension, unsigned int, TOutputImage::ImageDimension ); + + typedef typename Superclass::FiniteDifferenceFunctionType + FiniteDifferenceFunctionType; + typedef typename Superclass::FiniteDifferenceFunctionPointer + FiniteDifferenceFunctionPointer; + typedef typename FiniteDifferenceFunctionType::FloatOffsetType + FiniteDifferenceFunctionFloatOffsetType; + + /** Node type used in sparse field layer lists. */ + typedef SparseFieldLevelSetNode< OutputIndexType > LayerNodeType; + + /** A list type used in the algorithm. */ + typedef SparseFieldLayer< LayerNodeType > LayerType; + typedef typename LayerType::Pointer LayerPointerType; + typedef typename LayerType::Iterator LayerIterator; + typedef typename LayerType::ConstIterator LayerConstIterator; + + /** A type for a list of LayerPointerTypes */ + typedef std::vector< LayerPointerType > LayerListType; + typedef typename LayerListType::iterator LayerListIterator; + typedef typename LayerListType::const_iterator LayerListConstIterator; + + + /** Type used for storing status information */ + typedef signed char StatusType; + + /** The type of the image used to index status information. Necessary for + * the internals of the algorithm. */ + typedef Image< StatusType, itkGetStaticConstMacro(ImageDimension) > + StatusImageType; + typedef typename StatusImageType::Pointer StatusImagePointer; + + typedef ZeroCrossingImageFilter<OutputImageType, OutputImageType> + ZeroCrossingFilterType; + typedef typename ZeroCrossingFilterType::Pointer + ZeroCrossingFilterPointer; + + /** Memory pre-allocator used to manage layer nodes in a multi-threaded + * environment. */ + typedef ObjectStore< LayerNodeType > LayerNodeStorageType; + typedef typename LayerNodeStorageType::Pointer LayerNodeStoragePointer; + + /** Container type used to store updates to the active layer. */ + typedef std::vector< ValueType > UpdateBufferType; + typedef typename UpdateBufferType::const_iterator UpdateBufferConstIterator; + + /** Set/Get the number of layers to use in the sparse field. Argument is the + * number of layers on ONE side of the active layer, so the total layers in + * the sparse field is 2 * NumberOfLayers +1 */ + itkSetMacro( NumberOfLayers, unsigned int ); + itkGetConstMacro( NumberOfLayers, unsigned int ); + + /** Set/Get the value of the isosurface to use in the input image. */ + itkSetMacro( IsoSurfaceValue, ValueType ); + itkGetConstMacro( IsoSurfaceValue, ValueType ); + + /** Get/Set the value of the InterpolateSurfaceLocation flag. This flag + * tells the solver whether or not to interpolate for the surface location + * when calculating change at a voxel location. Turned on by default. Some + * 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 ); } + + void SetFunctionCount( const IdCellType& n ) + { + this->Superclass::SetFunctionCount( n ); + + m_SparseData.resize( this->m_FunctionCount, 0 ); + + for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + m_SparseData[i] = new SparseDataStruct( i ); + } + } + + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(OutputEqualityComparableCheck, + (Concept::EqualityComparable<typename TOutputImage::PixelType>)); + itkConceptMacro(DoubleConvertibleToOutputCheck, + (Concept::Convertible<double, typename TOutputImage::PixelType>)); + itkConceptMacro(OutputOStreamWritableCheck, + (Concept::OStreamWritable<typename TOutputImage::PixelType>)); + /** End concept checking */ +#endif + +protected: + MultiphaseSparseFiniteDifferenceImageFilter(); + ~MultiphaseSparseFiniteDifferenceImageFilter() + { + while( !m_SparseData.empty() ) + { + if( m_SparseData.back() ) + { + delete m_SparseData.back(); + } + m_SparseData.pop_back(); + } + } + + virtual void PrintSelf(std::ostream& os, Indent indent) const; + + // This data structure is created for each phase + struct SparseDataStruct + { + SparseDataStruct( const IdCellType& index ) + { + m_LayerNodeStore = LayerNodeStorageType::New(); + m_LayerNodeStore->SetGrowthStrategyToExponential(); + m_Index = index; + } + + /** Connectivity information for examining neighbor pixels. */ + SparseFieldCityBlockNeighborList< NeighborhoodIterator<OutputImageType> > + m_NeighborList; + + /** An array which contains all of the layers needed in the sparse + * field. Layers are organized as follows: m_Layer[0] = active layer, + * m_Layer[i:odd] = inside layer (i+1)/2, m_Layer[i:even] = outside layer i/2 + */ + LayerListType m_Layers; + + /** An image of status values used internally by the algorithm. */ + StatusImagePointer m_StatusImage; + + OutputImagePointer m_ShiftedImage; + + /** Storage for layer node objects. */ + LayerNodeStoragePointer m_LayerNodeStore; + + /** The update buffer used to store change values computed in + * CalculateChange. */ + UpdateBufferType m_UpdateBuffer; + + IdCellType m_Index; + }; + + /**This function allows a subclass to override the way in which updates to + * output values are applied during each iteration. The default simply + * follows the standard finite difference scheme of scaling the change by the + * timestep and adding to the value of the previous iteration. */ + inline virtual ValueType CalculateUpdateValue( + const OutputIndexType &itkNotUsed(idx), + const TimeStepType &dt, + const ValueType &value, + const ValueType &change) + { + return (value + dt * change); + } + + /**This method packages the output(s) into a consistent format. The default + * implementation produces a volume with the final solution values in the + * sparse field, and inside and outside values elsewhere as appropriate. */ + virtual void PostProcessOutput(); + + /**This method pre-processes pixels inside and outside the sparse field + * layers. The default is to set them to positive and negative values, + * respectively. This is not necessary as part of the calculations, but + * produces a more intuitive output for the user. */ + virtual void InitializeBackgroundPixels(); + + /** Constructs the sparse field layers and initializes their values. */ + void Initialize(); + + /** Copies the input to the output image. Processing occurs on the output + * image, so the data type of the output image determines the precision of + * the calculations (i.e. double or float). This method overrides the + * parent class method to do some additional processing. */ + void CopyInputToOutput(); + + /** Reserves memory in the update buffer. Called before each iteration. */ + void AllocateUpdateBuffer(); + + /** Applies the update buffer values to the active layer and reconstructs the + * sparse field layers for the next iteration. */ + void ApplyUpdate(TimeStepType dt); + + /** Traverses the active layer list and calculates the change at these + * indicies to be applied in the current iteration. */ + TimeStepType CalculateChange(); + + /** Initializes a layer of the sparse field using a previously initialized + * layer. Builds the list of nodes in m_Layer[to] using m_Layer[from]. + * Marks values in the m_StatusImage. */ + void ConstructLayer(SparseDataStruct *sparsePtr, StatusType from, StatusType +to); + + /** Constructs the active layer and initialize the first layers inside and + * outside of the active layer. The active layer defines the position of the + * zero level set by its values, which are constrained within a range around + * zero. */ + void ConstructActiveLayer(); + + /** Initializes the values of the active layer set. */ + void InitializeActiveLayerValues(); + + /** Adjusts the values in a single layer "to" using values in a neighboring + * layer "from". The list of indicies in "to" are traversed and assigned + * new values appropriately. Any indicies in "to" without neighbors in + * "from" are moved into the "promote" layer (or deleted if "promote" is + * greater than the number of layers). "InOrOut" == 1 indicates this + * propagation is inwards (more negative). "InOrOut" == 2 indicates this + * propagation is outwards (more positive). */ + void PropagateLayerValues(SparseDataStruct *sparsePtr, StatusType from, + StatusType to, StatusType promote, int InOrOut); + + /** Adjusts the values associated with all the index layers of the sparse + * field by propagating out one layer at a time from the active set. This + * method also takes care of deleting nodes from the layers which have been + * marked in the status image as having been moved to other layers. */ + void PropagateAllLayerValues(); + + void PropagateFunctionLayerValues( unsigned int functionIndex ); + + /** Updates the active layer values using m_UpdateBuffer. Also creates an + * "up" and "down" list for promotion/demotion of indicies leaving the + * active set. */ + void UpdateActiveLayerValues( TimeStepType dt, LayerType *StatusUpList, + LayerType *StatusDownList ); + + /** */ + void ProcessStatusList( LayerType *InputList, LayerType *OutputList, + StatusType ChangeToStatus, StatusType SearchForStatus); + + /** */ + void ProcessOutsideList(LayerType *OutsideList, StatusType ChangeToStatus); + + void InitializeIteration(); + + virtual void UpdatePixel(unsigned int itkNotUsed(functionIndex), unsigned int itkNotUsed(idx), + NeighborhoodIterator<OutputImageType> & itkNotUsed(iterator), ValueType & itkNotUsed(newValue), + bool & itkNotUsed(status) ){}; + + itkGetConstMacro( ValueZero, ValueType ); + itkGetConstMacro( ValueOne, ValueType ); + + /** The constant gradient to maintain between isosurfaces in the + sparse-field of the level-set image. This value defaults to 1.0 */ + static double m_ConstantGradientValue; + + /** Multiplicative identity of the ValueType. */ + static const ValueType m_ValueOne; + + /** Additive identity of the ValueType. */ + static const ValueType m_ValueZero; + + /** Special status value which indicates pending change to another sparse + * field layer. */ + static const StatusType m_StatusChanging; + + /** Special status value which indicates a pending change to a more positive + * sparse field. */ + static const StatusType m_StatusActiveChangingUp; + + /** Special status value which indicates a pending change to a more negative + * sparse field. */ + static const StatusType m_StatusActiveChangingDown; + + /** Special status value which indicates a pixel is on the boundary of the + * image */ + static const StatusType m_StatusBoundaryPixel; + + /** Special status value used as a default for indicies which have no + meaningful status. */ + static const StatusType m_StatusNull; + + std::vector< SparseDataStruct* > m_SparseData; + + /** The number of layers to use in the sparse field. Sparse field will + * consist of m_NumberOfLayers layers on both sides of a single active layer. + * This active layer is the interface of interest, i.e. the zero level set. */ + unsigned int m_NumberOfLayers; + + /** The value in the input which represents the isosurface of interest. */ + ValueType m_IsoSurfaceValue; + + /** This flag tells the solver whether or not to interpolate for the actual + surface location when calculating change at each active layer node. By + default this is turned on. Subclasses which do not sample propagation + (speed), advection, or curvature terms should turn this flag off. */ + bool m_InterpolateSurfaceLocation; + +private: + MultiphaseSparseFiniteDifferenceImageFilter(const Self&); + void operator=(const Self&); //purposely not implemented + + unsigned int m_CurrentFunctionIndex; + + /** This flag is true when methods need to check boundary conditions and + false when methods do not need to check for boundary conditions. */ + bool m_BoundsCheckingActive; +}; + + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkMultiphaseSparseFiniteDifferenceImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.txx b/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.txx new file mode 100644 index 0000000000..5e21f40f97 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.txx @@ -0,0 +1,1363 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMultiphaseSparseFiniteDifferenceImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 20:41:19 $ + Version: $Revision: 1.5 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkMultiphaseSparseFiniteDifferenceImageFilter_txx +#define __itkMultiphaseSparseFiniteDifferenceImageFilter_txx + +#include "itkMultiphaseSparseFiniteDifferenceImageFilter.h" + +namespace itk +{ +template < class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +typename MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +TOutputImage, TFunction, TIdCell >::TimeStepType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::CalculateChange() +{ + TimeStepType minTimeStep = NumericTraits< TimeStepType >::max(); + + for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_CurrentFunctionIndex = i; + + const FiniteDifferenceFunctionPointer df = this->m_DifferenceFunctions[i]; + + SparseDataStruct *sparsePtr = this->m_SparseData[i]; + + FiniteDifferenceFunctionFloatOffsetType offset; + ValueType norm_grad_phi_squared, dx_forward, dx_backward, forwardValue, + backwardValue, centerValue; + const ValueType MIN_NORM = 1.0e-6; + void *globalData = df->GetGlobalDataPointer(); + + NeighborhoodIterator<OutputImageType> outputIt ( df->GetRadius(), + this->m_LevelSet[this->m_CurrentFunctionIndex], + this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); + TimeStepType timeStep; + + if( m_BoundsCheckingActive == false ) + { + outputIt.NeedToUseBoundaryConditionOff(); + } + + sparsePtr->m_UpdateBuffer.clear(); + sparsePtr->m_UpdateBuffer.reserve ( sparsePtr->m_Layers[0]->Size() ); + + // Calculates the update values for the active layer indicies in this + // iteration. Iterates through the active layer index list, applying + // the level set function to the output image (level set image) at each + // index. Update values are stored in the update buffer. + LayerConstIterator layerIt = sparsePtr->m_Layers[0]->Begin(); + + unsigned int j; + + while( layerIt != sparsePtr->m_Layers[0]->End() ) + { + outputIt.SetLocation ( layerIt->m_Value ); + + // Calculate the offset to the surface from the center of this + // neighborhood. This is used by some level set functions in sampling a + // speed, advection, or curvature term. + if ( this->GetInterpolateSurfaceLocation() + && ( centerValue = outputIt.GetCenterPixel() ) != 0.0 ) + { + // Surface is at the zero crossing, so distance to surface is: + // phi(x) / norm(grad(phi)), where phi(x) is the center of the + // neighborhood. The location is therefore + // (i,j,k) - ( phi(x) * grad(phi(x)) ) / norm(grad(phi))^2 + norm_grad_phi_squared = 0.0; + + for ( j = 0; j < ImageDimension; ++j ) + { + forwardValue = outputIt.GetNext ( j ); + backwardValue = outputIt.GetPrevious ( j ); + + if ( forwardValue * backwardValue >= 0 ) + { + // Neighbors are same sign OR at least one neighbor is zero. + dx_forward = forwardValue - centerValue; + dx_backward = centerValue - backwardValue; + + // Pick the larger magnitude derivative. + if ( ::vnl_math_abs ( dx_forward ) >::vnl_math_abs( dx_backward ) ) + { + offset[j] = dx_forward; + } + else + { + offset[j] = dx_backward; + } + } + else //Neighbors are opposite sign, pick the direction of 0 surface. + { + if ( forwardValue * centerValue < 0 ) + { + offset[j] = forwardValue - centerValue; + } + else + { + offset[j] = centerValue - backwardValue; + } + } + + norm_grad_phi_squared += offset[j] * offset[j]; + } + + // Adding sqrt imagedimension "extends the reach" of the + // interpolation + // to surfaces that pass close to the center of cells. This is a + // heuristic fudge factor that improves interpolation and reduces + // "wiggling" at convergence. + ValueType coeff = centerValue * vcl_sqrt( ImageDimension + + 0.5 )/ ( norm_grad_phi_squared + MIN_NORM ); + + for ( j = 0; j < ImageDimension; ++j ) + { + offset[j] *= coeff; + } + + sparsePtr->m_UpdateBuffer.push_back ( df->ComputeUpdate ( outputIt, globalData, offset ) ); + } + else // Don't do interpolation + { + sparsePtr->m_UpdateBuffer.push_back ( df->ComputeUpdate ( outputIt, globalData ) ); + } + + ++layerIt; + } + + // Ask the finite difference function to compute the time step for + // this iteration. We give it the global data pointer to use, then + // ask it to free the global data memory. + timeStep = df->ComputeGlobalTimeStep ( globalData ); + df->ReleaseGlobalDataPointer ( globalData ); + + if ( timeStep < minTimeStep ) + { + minTimeStep = timeStep; + } + } + minTimeStep = 0.2; //FIXME finally assined to a constant + return minTimeStep; +} + + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFunction, TIdCell > +::ApplyUpdate ( TimeStepType dt ) +{ + unsigned int j, k; + + for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_CurrentFunctionIndex = i; + + SparseDataStruct *sparsePtr = this->m_SparseData[this->m_CurrentFunctionIndex]; + unsigned int t; + + StatusType up_to, up_search; + StatusType down_to, down_search; + + LayerPointerType UpList[2]; + LayerPointerType DownList[2]; + for ( j = 0; j < 2; ++j ) + { + UpList[j] = LayerType::New(); + DownList[j] = LayerType::New(); + } + + // Process the active layer. This step will update the values in the + //active + // layer as well as the values at indices that *will* become part of the + // active layer when they are promoted/demoted. Also records promotions, + // demotions in the m_StatusLayer for current active layer indices + // (i.e. those indices which will move inside or outside the active + // layers). + this->UpdateActiveLayerValues( dt, UpList[0], DownList[0] ); + + // Process the status up/down lists. This is an iterative process which + // proceeds outwards from the active layer. Each iteration generates the + // list for the next iteration. + + // First process the status lists generated on the active layer. + this->ProcessStatusList ( UpList[0], UpList[1], 2, 1 ); + this->ProcessStatusList ( DownList[0], DownList[1], 1, 2 ); + + down_to = up_to = 0; + up_search = 3; + down_search = 4; + j = 1; + k = 0; + while ( down_search < static_cast<StatusType>(sparsePtr->m_Layers.size())) + { + this->ProcessStatusList(UpList[j], UpList[k], up_to, up_search ); + this->ProcessStatusList(DownList[j], DownList[k], down_to, down_search); + + if( up_to == 0 ) + { + up_to += 1; + } + else + { + up_to += 2; + } + + down_to += 2; + + up_search += 2; + down_search += 2; + + // Swap the lists so we can re-use the empty one. + t = j; + j = k; + k = t; + } + + // Process the outermost inside/outside layers in the sparse field. + this->ProcessStatusList(UpList[j], UpList[k], up_to, m_StatusNull ); + this->ProcessStatusList(DownList[j], DownList[k], down_to, m_StatusNull); + + // Now we are left with the lists of indicies which must be + // brought into the outermost layers. Bring UpList into last inside layer + // and DownList into last outside layer. + this->ProcessOutsideList ( UpList[k], static_cast<signed char> ( + sparsePtr->m_Layers.size() ) -2 ); + this->ProcessOutsideList ( DownList[k], static_cast<signed char> ( + sparsePtr->m_Layers.size() ) -1 ); + + // Finally, we update all of the layer values (excluding the active layer, + // which has already been updated). + this->PropagateAllLayerValues(); + } + this->m_CurrentFunctionIndex = 0; +} + +template < class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFunction, TIdCell > +::ProcessOutsideList ( LayerType *OutsideList, StatusType ChangeToStatus ) +{ + SparseDataStruct *sparsePtr = this->m_SparseData[this->m_CurrentFunctionIndex]; + LayerNodeType *node; + + // Push each index in the input list into its appropriate status layer + // (ChangeToStatus) and update the status image value at that index. + while ( ! OutsideList->Empty() ) + { + sparsePtr->m_StatusImage->SetPixel ( OutsideList->Front()->m_Value, ChangeToStatus ); + node = OutsideList->Front(); + OutsideList->PopFront(); + sparsePtr->m_Layers[ChangeToStatus]->PushFront ( node ); + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFunction, TIdCell > +::ProcessStatusList ( LayerType *InputList, LayerType *OutputList, + StatusType ChangeToStatus, StatusType SearchForStatus ) +{ + SparseDataStruct *sparsePtr = this->m_SparseData[this->m_CurrentFunctionIndex]; + + unsigned int i; + bool bounds_status; + LayerNodeType *node; + StatusType neighbor_status; + NeighborhoodIterator<StatusImageType> + statusIt ( sparsePtr->m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, + this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); + + if ( !m_BoundsCheckingActive ) + { + statusIt.NeedToUseBoundaryConditionOff(); + } + + // Push each index in the input list into its appropriate status layer + // (ChangeToStatus) and update the status image value at that index. + // Also examine the neighbors of the index to determine which need to go + // onto + // the output list (search for SearchForStatus). + while ( ! InputList->Empty() ) + { + statusIt.SetLocation ( InputList->Front()->m_Value ); + statusIt.SetCenterPixel ( ChangeToStatus ); + + node = InputList->Front(); // Must unlink from the input list + InputList->PopFront(); // _before_ transferring to another list. + sparsePtr->m_Layers[ChangeToStatus]->PushFront ( node ); + + for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + { + neighbor_status = statusIt.GetPixel ( + sparsePtr->m_NeighborList.GetArrayIndex ( i ) ); + + // Have we bumped up against the boundary? If so, turn on bounds + // checking. + if ( neighbor_status == m_StatusBoundaryPixel ) + { + m_BoundsCheckingActive = true; + } + + if ( neighbor_status == SearchForStatus ) + { + // mark this pixel so we don't add it twice. + statusIt.SetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ), + m_StatusChanging, bounds_status ); + if ( bounds_status == true ) + { + node = sparsePtr->m_LayerNodeStore->Borrow(); + node->m_Value = statusIt.GetIndex() + + sparsePtr->m_NeighborList.GetNeighborhoodOffset ( i ); + OutputList->PushFront ( node ); + } // else this index was out of bounds. + } + } + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFunction, TIdCell > +::UpdateActiveLayerValues ( TimeStepType dt, LayerType *UpList, LayerType +*DownList ) +{ + SparseDataStruct *sparsePtr = this->m_SparseData[this->m_CurrentFunctionIndex]; + + // This method scales the update buffer values by the time step and adds + // them to the active layer pixels. New values at an index which fall + // outside of the active layer range trigger that index to be placed on the + // "up" or "down" status list. The neighbors of any such index are then + // assigned new values if they are determined to be part of the active list + // for the next iteration (i.e. their values will be raised or lowered into + // the active range). + const ValueType LOWER_ACTIVE_THRESHOLD = -( m_ConstantGradientValue/2.0 ); + const ValueType UPPER_ACTIVE_THRESHOLD = m_ConstantGradientValue / 2.0; + + ValueType new_value, temp_value, rms_change_accumulator; + LayerNodeType *node, *release_node; + StatusType neighbor_status; + unsigned int i, idx, counter; + bool bounds_status, flag; + + LayerIterator layerIt; + UpdateBufferConstIterator updateIt; + + NeighborhoodIterator< OutputImageType > + outputIt ( sparsePtr->m_NeighborList.GetRadius(), + this->m_LevelSet[this->m_CurrentFunctionIndex], + this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); + + NeighborhoodIterator< StatusImageType > + statusIt ( sparsePtr->m_NeighborList.GetRadius(), + sparsePtr->m_StatusImage, + this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); + + if ( !m_BoundsCheckingActive ) + { + outputIt.NeedToUseBoundaryConditionOff(); + statusIt.NeedToUseBoundaryConditionOff(); + } + + counter = 0; + rms_change_accumulator = m_ValueZero; + + layerIt = sparsePtr->m_Layers[0]->Begin(); + updateIt = sparsePtr->m_UpdateBuffer.begin(); + + while( layerIt != sparsePtr->m_Layers[0]->End() ) + { + outputIt.SetLocation ( layerIt->m_Value ); + statusIt.SetLocation ( layerIt->m_Value ); + + new_value = this->CalculateUpdateValue ( layerIt->m_Value, + dt, outputIt.GetCenterPixel(), *updateIt ); + + // If this index needs to be moved to another layer, then search its + // neighborhood for indicies that need to be pulled up/down into the + // active layer. Set those new active layer values appropriately, + // checking first to make sure they have not been set by a more + // influential neighbor. + + // ...But first make sure any neighbors in the active layer are not + // moving to a layer in the opposite direction. This step is necessary + // to avoid the creation of holes in the active layer. The fix is simply + // to not change this value and leave the index in the active set. + + if ( new_value >= UPPER_ACTIVE_THRESHOLD ) + { + // This index will move UP into a positive (outside) layer. + + // First check for active layer neighbors moving in the opposite + // direction. + flag = false; + for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + { + if ( statusIt.GetPixel( sparsePtr->m_NeighborList.GetArrayIndex( i ) ) + == m_StatusActiveChangingDown ) + { + flag = true; + break; + } + } + + if ( flag == true ) + { + ++layerIt; + ++updateIt; + continue; + } + + rms_change_accumulator += vnl_math_sqr ( new_value-outputIt.GetCenterPixel() ); + + // Search the neighborhood for inside indicies. + temp_value = new_value - m_ConstantGradientValue; + for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + { + idx = sparsePtr->m_NeighborList.GetArrayIndex ( i ); + neighbor_status = statusIt.GetPixel ( idx ); + if ( neighbor_status == 1 ) + { + // Keep the smallest possible value for the new active node. This + // places the new active layer node closest to the zero level-set. + if ( outputIt.GetPixel ( idx ) < LOWER_ACTIVE_THRESHOLD || + ::vnl_math_abs ( temp_value ) < ::vnl_math_abs ( + outputIt.GetPixel ( idx ) ) ) + { + UpdatePixel ( this->m_CurrentFunctionIndex, idx, outputIt, temp_value, bounds_status ); + } + } + } + // Push it into the uplist + node = sparsePtr->m_LayerNodeStore->Borrow(); + node->m_Value = layerIt->m_Value; + UpList->PushFront ( node ); + statusIt.SetCenterPixel ( m_StatusActiveChangingUp ); + + // Now remove this index from the active list. + release_node = layerIt.GetPointer(); + ++layerIt; + sparsePtr->m_Layers[0]->Unlink ( release_node ); + sparsePtr->m_LayerNodeStore->Return ( release_node ); + } + + else if ( new_value < LOWER_ACTIVE_THRESHOLD ) + { + // This index will move DOWN into a negative (inside) layer. + + // First check for active layer neighbors moving in the opposite + // direction. + flag = false; + for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + { + + if ( statusIt.GetPixel( sparsePtr->m_NeighborList.GetArrayIndex( i ) ) + == m_StatusActiveChangingUp ) + { + flag = true; + break; + } + } + + if ( flag == true ) + { + ++layerIt; + ++updateIt; + continue; + } + + rms_change_accumulator += vnl_math_sqr ( new_value - outputIt.GetCenterPixel() ); + + // Search the neighborhood for outside indicies. + temp_value = new_value + m_ConstantGradientValue; + for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + { + idx = sparsePtr->m_NeighborList.GetArrayIndex ( i ); + neighbor_status = statusIt.GetPixel ( idx ); + if ( neighbor_status == 2 ) + { + // Keep the smallest magnitude value for this active set node. This + // places the node closest to the active layer. + if ( outputIt.GetPixel ( idx ) >= UPPER_ACTIVE_THRESHOLD || + ::vnl_math_abs ( temp_value ) < ::vnl_math_abs ( + outputIt.GetPixel ( idx ) ) ) + { + UpdatePixel ( this->m_CurrentFunctionIndex, idx, outputIt, temp_value, bounds_status ); + } + } + } + node = sparsePtr->m_LayerNodeStore->Borrow(); + node->m_Value = layerIt->m_Value; + DownList->PushFront ( node ); + statusIt.SetCenterPixel ( m_StatusActiveChangingDown ); + + // Now remove this index from the active list. + release_node = layerIt.GetPointer(); + ++layerIt; + sparsePtr->m_Layers[0]->Unlink ( release_node ); + sparsePtr->m_LayerNodeStore->Return ( release_node ); + } + else + { + rms_change_accumulator += vnl_math_sqr ( new_value - outputIt.GetCenterPixel() ); + + UpdatePixel ( this->m_CurrentFunctionIndex, outputIt.Size() >> 1, outputIt, new_value, bounds_status ); + + ++layerIt; + } + ++updateIt; + ++counter; + } + + // Determine the average change during this iteration. + if ( counter == 0 ) + { + this->SetRMSChange ( static_cast<double> ( m_ValueZero ) ); + } + else + { + this->SetRMSChange ( + vcl_sqrt ( static_cast< double >( rms_change_accumulator / + static_cast<double> ( counter ) ) ) ); + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFunction, TIdCell > +::InitializeActiveLayerValues() +{ + const ValueType CHANGE_FACTOR = m_ConstantGradientValue / 2.0; + // const ValueType CHANGE_FACTOR = 0.7; + const ValueType MIN_NORM = 1.0e-6; + + for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + SparseDataStruct *sparsePtr = this->m_SparseData[i]; + + unsigned int center; + + typename LayerType::ConstIterator activeIt; + ConstNeighborhoodIterator<OutputImageType> + outputIt ( sparsePtr->m_NeighborList.GetRadius(), + this->m_LevelSet[i], + this->m_LevelSet[i]->GetRequestedRegion() ); + + sparsePtr->m_UpdateBuffer.clear(); + sparsePtr->m_UpdateBuffer.reserve ( sparsePtr->m_Layers[0]->Size() ); + + center = outputIt.Size()/2; + typename OutputImageType::Pointer output = this->m_LevelSet[i]; + + ValueType dx_forward, dx_backward, length, distance; + + // For all indicies in the active layer... + activeIt = sparsePtr->m_Layers[0]->Begin(); + while( activeIt != sparsePtr->m_Layers[0]->End() ) + { + // Interpolate on the (shifted) input image values at this index to + // assign an active layer value in the output image. + outputIt.SetLocation ( activeIt->m_Value ); + + length = m_ValueZero; + + for ( unsigned int j = 0; j < ImageDimension; ++j ) + { + dx_forward = outputIt.GetPixel ( center + + sparsePtr->m_NeighborList.GetStride( j ) ) - + outputIt.GetCenterPixel(); + dx_backward = outputIt.GetCenterPixel() - + outputIt.GetPixel ( center - + sparsePtr->m_NeighborList.GetStride ( j ) ); + + if ( vnl_math_abs ( dx_forward ) > vnl_math_abs ( dx_backward ) ) + { + length += dx_forward * dx_forward; + } + else + { + length += dx_backward * dx_backward; + } + } + length = vcl_sqrt ( length ) + MIN_NORM; + distance = outputIt.GetCenterPixel() / length; + + sparsePtr->m_UpdateBuffer.push_back( + vnl_math_min ( vnl_math_max ( -CHANGE_FACTOR, distance ), + CHANGE_FACTOR ) ); + ++activeIt; + } + + activeIt = sparsePtr->m_Layers[0]->Begin(); + while( activeIt != sparsePtr->m_Layers[0]->End() ) + { + output->SetPixel ( activeIt->m_Value, sparsePtr->m_UpdateBuffer.front() ); + ++activeIt; + } + } +} + + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFunction, TIdCell > +::PropagateAllLayerValues() +{ + for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + PropagateFunctionLayerValues ( i ); + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFunction, TIdCell > +::PropagateFunctionLayerValues ( unsigned int functionIndex ) +{ + SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; + + // Update values in the first inside and first outside layers using the + // active layer as a seed. Inside layers are odd numbers, outside layers are + // even numbers. + this->PropagateLayerValues ( sparsePtr, 0, 1, 3, 1 ); // first inside + this->PropagateLayerValues ( sparsePtr, 0, 2, 4, 2 ); // first outside + + // Update the rest of the layers. + for ( unsigned int i = 1; i < sparsePtr->m_Layers.size() - 2; ++i ) + { + this->PropagateLayerValues ( sparsePtr, i, i+2, i+4, ( i+2 ) %2 ); + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, + TOutputImage, + TFunction, TIdCell > +::PropagateLayerValues ( SparseDataStruct *sparsePtr, StatusType from, + StatusType to, StatusType promote, int InOrOut ) +{ + unsigned int i; + ValueType value_temp, delta; + ValueType value = NumericTraits<ValueType>::Zero; // warnings + bool found_neighbor_flag; + LayerIterator toIt; + LayerNodeType *node; + + StatusType past_end = static_cast<StatusType>( sparsePtr->m_Layers.size() )-1; + + // Are we propagating values inward (more negative) or outward (more + // positive)? + if ( InOrOut == 1 ) + { + delta = - m_ConstantGradientValue; + } + else + { + delta = m_ConstantGradientValue; + } + + NeighborhoodIterator<OutputImageType> + outputIt ( sparsePtr->m_NeighborList.GetRadius(), + this->m_LevelSet[sparsePtr->m_Index], + this->m_LevelSet[sparsePtr->m_Index]->GetRequestedRegion() ); + NeighborhoodIterator<StatusImageType> + statusIt ( sparsePtr->m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, + this->m_LevelSet[sparsePtr->m_Index]->GetRequestedRegion() ); + + if ( !m_BoundsCheckingActive ) + { + outputIt.NeedToUseBoundaryConditionOff(); + statusIt.NeedToUseBoundaryConditionOff(); + } + + toIt = sparsePtr->m_Layers[to]->Begin(); + while ( toIt != sparsePtr->m_Layers[to]->End() ) + { + statusIt.SetLocation ( toIt->m_Value ); + + // Is this index marked for deletion? If the status image has + // been marked with another layer's value, we need to delete this node + // from the current list then skip to the next iteration. + if ( statusIt.GetCenterPixel() != to ) + { + node = toIt.GetPointer(); + ++toIt; + sparsePtr->m_Layers[to]->Unlink ( node ); + sparsePtr->m_LayerNodeStore->Return ( node ); + continue; + } + + outputIt.SetLocation ( toIt->m_Value ); + + found_neighbor_flag = false; + for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + { + // If this neighbor is in the "from" list, compare its absolute value + // to to any previous values found in the "from" list. Keep the value + // that will cause the next layer to be closest to the zero level set. + if ( statusIt.GetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ) ) == from ) + { + value_temp = outputIt.GetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ) ); + + if ( !found_neighbor_flag ) + { + value = value_temp; + } + else + { + if ( InOrOut == 1 ) + { + // Find the largest (least negative) neighbor + if ( value_temp > value ) + { + value = value_temp; + } + } + else + { + // Find the smallest (least positive) neighbor + if ( value_temp < value ) + { + value = value_temp; + } + } + } + found_neighbor_flag = true; + } + } + + if ( found_neighbor_flag ) + { + // Set the new value using the smallest distance + // found in our "from" neighbors. + bool bounds_status; + ValueType updateValue = value + delta; + + UpdatePixel ( sparsePtr->m_Index, outputIt.Size() >>1, outputIt, updateValue, bounds_status ); + + ++toIt; + } + else + { + // Did not find any neighbors on the "from" list, then promote this + // node. A "promote" value past the end of my sparse field size + // means delete the node instead. Change the status value in the + // status image accordingly. + node = toIt.GetPointer(); + ++toIt; + sparsePtr->m_Layers[to]->Unlink ( node ); + if ( promote > past_end ) + { + sparsePtr->m_LayerNodeStore->Return ( node ); + statusIt.SetCenterPixel ( m_StatusNull ); + } + else + { + sparsePtr->m_Layers[promote]->PushFront ( node ); + statusIt.SetCenterPixel ( promote ); + } + } + } +} + + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +double MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > +::m_ConstantGradientValue = 1.0; + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, +TOutputImage, TFunction, TIdCell >::ValueType +MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > +::m_ValueOne = NumericTraits<ITK_TYPENAME +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::ValueType >::One; + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +TOutputImage, TFunction, TIdCell >::ValueType +MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > +::m_ValueZero = NumericTraits<ITK_TYPENAME +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell >:: +ValueType>::Zero; + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::m_StatusNull = NumericTraits< ITK_TYPENAME +MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell >:: +StatusType >::NonpositiveMin(); + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::m_StatusChanging = -1; + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::m_StatusActiveChangingUp = -2; + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::m_StatusActiveChangingDown = -3; + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::m_StatusBoundaryPixel = -4; + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::MultiphaseSparseFiniteDifferenceImageFilter() +{ + this->m_CurrentFunctionIndex = 0; + this->m_IsoSurfaceValue = m_ValueZero; + this->m_NumberOfLayers = ImageDimension; + this->SetRMSChange ( NumericTraits< double >::Zero ); + this->m_InterpolateSurfaceLocation = true; + this->m_BoundsCheckingActive = false; +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > +::CopyInputToOutput() +{ + for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + SparseDataStruct * sparsePtr = this->m_SparseData[i]; + OutputImagePointer input = this->m_LevelSet[i]; + + // This is used as a temporary buffer in this specific instance + // However, we need to use it later on. Therefore, its instantiation + // is important. DO NOT DELETE. + sparsePtr->m_ShiftedImage = OutputImageType::New(); + sparsePtr->m_ShiftedImage->SetRegions( input->GetRequestedRegion() ); + sparsePtr->m_ShiftedImage->Allocate(); + sparsePtr->m_ShiftedImage->CopyInformation( input ); + + // Copy input to ShiftedImage + // TODO: Is there a better way to do this?? + // + OutputRegionType region = input->GetRequestedRegion(); + ImageRegionIterator<OutputImageType> lIt( input, region ); + ImageRegionIterator<OutputImageType> sIt( sparsePtr->m_ShiftedImage, region ); + + lIt.GoToBegin(); + sIt.GoToBegin(); + + while( !lIt.IsAtEnd() ) + { + sIt.Set( lIt.Get() ); + ++sIt; + ++lIt; + } + + // TODO: Can the zeroCrossingFilter have the same input and output? + ZeroCrossingFilterPointer zeroCrossingFilter = ZeroCrossingFilterType::New(); + zeroCrossingFilter->SetInput( sparsePtr->m_ShiftedImage ); + zeroCrossingFilter->SetBackgroundValue( m_ValueOne ); + zeroCrossingFilter->SetForegroundValue( m_ValueZero ); + zeroCrossingFilter->Update(); + + this->m_LevelSet[i] = zeroCrossingFilter->GetOutput(); + this->m_LevelSet[i]->DisconnectPipeline(); + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::InitializeIteration() +{ + Superclass::InitializeIteration(); + + // Set the values in the output image for the active layer. + this->InitializeActiveLayerValues(); + + // Initialize layer values using the active layer as seeds. + this->PropagateAllLayerValues(); +} + + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::Initialize() +{ + IdCellType functionIndex; + + for ( functionIndex = 0; functionIndex < this->m_FunctionCount; + functionIndex++ ) + { + SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; + + unsigned int i; + + // Allocate the status image. + sparsePtr->m_StatusImage = StatusImageType::New(); + sparsePtr->m_StatusImage->SetRegions ( + this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + sparsePtr->m_StatusImage->Allocate(); + sparsePtr->m_StatusImage->FillBuffer( m_StatusNull );//NonpositiveMin + + // Initialize the boundary pixels in the status image to + // m_StatusBoundaryPixel values. Uses the face calculator to find all of + // the region faces. + typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< StatusImageType > BFCType; + + BFCType faceCalculator; + typename BFCType::FaceListType faceList; + typename BFCType::SizeType sz; + typename BFCType::FaceListType::iterator fit; + + sz.Fill ( 1 ); // Set the difference function radius here + faceList = faceCalculator ( sparsePtr->m_StatusImage, + sparsePtr->m_StatusImage->GetRequestedRegion(), sz ); + fit = faceList.begin(); + + for( ++fit; fit != faceList.end(); ++fit ) + { + ImageRegionIterator<StatusImageType> statusIt( sparsePtr->m_StatusImage, *fit ); + + statusIt.GoToBegin(); + while( ! statusIt.IsAtEnd() ) + { + statusIt.Set ( m_StatusBoundaryPixel );// -4 : FIXME: What does "-4" means here ? + ++statusIt; + } + } + + // Erase all existing layer lists. + for ( i = 0; i < sparsePtr->m_Layers.size(); ++i ) + { + while ( ! sparsePtr->m_Layers[i]->Empty() ) + { + sparsePtr->m_LayerNodeStore->Return( sparsePtr->m_Layers[i]->Front()); + sparsePtr->m_Layers[i]->PopFront(); + } + } + + // Allocate the layers for the sparse field. + sparsePtr->m_Layers.clear(); + sparsePtr->m_Layers.reserve( 2 * this->m_NumberOfLayers + 1 ); + + while( sparsePtr->m_Layers.size() < ( 2 * this->m_NumberOfLayers+1 ) ) + { + sparsePtr->m_Layers.push_back( LayerType::New() ); + } + + // Throw an exception if we don't have enough layers. + if ( sparsePtr->m_Layers.size() < 3 ) + { + itkExceptionMacro ( << "Not enough layers have been allocated for the" + "sparse field. Requires at least one layer." ); + } + } + + // Construct the active layer and initialize the first layers inside and + // outside of the active layer. + this->ConstructActiveLayer(); + + for ( functionIndex = 0; functionIndex < this->m_FunctionCount; functionIndex++ ) + { + SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; + + // Construct the rest of the non-active set layers using the first two + // layers. Inside layers are odd numbers, outside layers are even numbers. + for ( unsigned int i = 1; i < sparsePtr->m_Layers.size() - 2; ++i ) + { + this->ConstructLayer( sparsePtr, i, i+2 ); + } + } + + // Set the values in the output image for the active layer. + this->InitializeActiveLayerValues(); + + // Initialize layer values using the active layer as seeds. + this->PropagateAllLayerValues(); + + // Initialize pixels inside and outside the sparse field layers to positive + // and negative values, respectively?? This is not necessary for the + // calculations, but is useful for presenting a more intuitive output to the + // filter. See PostProcessOutput method for more information. + this->InitializeBackgroundPixels(); + + + // for ( functionIndex = 0; functionIndex < this->m_FunctionCount; functionIndex++ ) + // { + // // Delete status image + // this->m_SparseData[functionIndex]->m_ShiftedImage->Delete(); + // } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::InitializeBackgroundPixels() +{ + for ( IdCellType functionIndex = 0; functionIndex < this->m_FunctionCount; + functionIndex++ ) + { + SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; + + // Assign background pixels OUTSIDE the sparse field layers to a new level + // set + // with value greater than the outermost layer. Assign background pixels + // INSIDE the sparse field layers to a new level set with value less than + // the innermost layer. + const ValueType max_layer = static_cast<ValueType> ( this->m_NumberOfLayers ); + + const ValueType outside_value = max_layer + m_ConstantGradientValue; + const ValueType inside_value = - ( max_layer + m_ConstantGradientValue ); + + ImageRegionConstIterator<StatusImageType> statusIt ( + sparsePtr->m_StatusImage, + this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + + ImageRegionIterator<OutputImageType> outputIt ( + this->m_LevelSet[functionIndex], + this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + + ImageRegionIterator<OutputImageType> shiftedIt ( + sparsePtr->m_ShiftedImage, + this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + + outputIt.GoToBegin(); + shiftedIt.GoToBegin(); + statusIt.GoToBegin(); + + while( !outputIt.IsAtEnd() ) + { + if( statusIt.Get() == m_StatusNull || statusIt.Get() == + m_StatusBoundaryPixel ) + { + if( shiftedIt.Get() > m_ValueZero ) + { + outputIt.Set ( outside_value ); + } + else + { + outputIt.Set ( inside_value ); + } + } + ++shiftedIt; + ++outputIt; + ++statusIt; + } + } +} + + +template< class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::ConstructActiveLayer() +{ + for ( IdCellType functionIndex = 0; functionIndex < this->m_FunctionCount; + functionIndex++ ) + { + SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; + + // We find the active layer by searching for 0's in the zero crossing + // image (output image). The first inside and outside layers are also + // constructed by searching the neighbors of the active layer in the + // (shifted) input image. Negative neighbors not in the active set are + // assigned to the inside, positive neighbors are assigned to the outside. + // + // During construction we also check whether any of the layers of the + // active set (or the active set itself) is sitting on a boundary pixel + // location. If this is the case, then we need to do active bounds + // checking in the solver. + + unsigned int i; + NeighborhoodIterator< OutputImageType > + outputIt ( sparsePtr->m_NeighborList.GetRadius(), + this->m_LevelSet[functionIndex], + this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + + NeighborhoodIterator< StatusImageType > + statusIt ( sparsePtr->m_NeighborList.GetRadius(), + sparsePtr->m_StatusImage, + this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + + NeighborhoodIterator< OutputImageType > + shiftedIt ( sparsePtr->m_NeighborList.GetRadius(), + sparsePtr->m_ShiftedImage, + this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + + OutputIndexType center_index, offset_index; + LayerNodeType *node; + bool bounds_status; + ValueType value; + StatusType layer_number; + + OutputIndexType lowerBounds; + OutputSizeType upperBounds; + lowerBounds = this->m_LevelSet[functionIndex]->GetRequestedRegion().GetIndex(); + upperBounds = this->m_LevelSet[functionIndex]->GetRequestedRegion().GetSize(); + + outputIt.GoToBegin(); + + while( !outputIt.IsAtEnd() ) + { + if ( outputIt.GetCenterPixel() == m_ValueZero ) + { + // Grab the neighborhood in the status image. + center_index = outputIt.GetIndex(); + statusIt.SetLocation ( center_index ); + + // Check to see if any of the sparse field touches a boundary. If so, + // then activate bounds checking. + for ( i = 0; i < ImageDimension; i++ ) + { + if ( ( center_index[i] + static_cast< long > ( + this->m_NumberOfLayers ) >= static_cast< long>( upperBounds[i] - 1 ) ) + || center_index[i] - static_cast< long >( + this->m_NumberOfLayers ) <= static_cast< long >(lowerBounds[i]) ) + { + m_BoundsCheckingActive = true; + } + } + + // Borrow a node from the store and set its value. + node = sparsePtr->m_LayerNodeStore->Borrow(); + node->m_Value = center_index; + + // Add the node to the active list and set the status in the status + // image. + sparsePtr->m_Layers[0]->PushFront ( node ); + statusIt.SetCenterPixel ( 0 ); + + // Grab the neighborhood in the image of shifted input values. + shiftedIt.SetLocation ( center_index ); + + // Search the neighborhood pixels for first inside & outside layer + // members. Construct these lists and set status list values. + for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + { + offset_index = center_index + sparsePtr->m_NeighborList.GetNeighborhoodOffset ( i ); + + if ( outputIt.GetPixel( sparsePtr->m_NeighborList.GetArrayIndex( i ) ) != m_ValueZero ) + { + value = shiftedIt.GetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ) ); + + if ( value < m_ValueZero ) // Assign to first inside layer. + { + layer_number = 1; + } + else // Assign to first outside layer + { + layer_number = 2; + } + + statusIt.SetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ), + layer_number, bounds_status ); + + if ( bounds_status ) // In bounds. + { + node = sparsePtr->m_LayerNodeStore->Borrow(); + node->m_Value = offset_index; + sparsePtr->m_Layers[layer_number]->PushFront ( node ); + } // else do nothing. + } + } + } + ++outputIt; + } + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::ConstructLayer ( SparseDataStruct *sparsePtr, StatusType from, StatusType to ) +{ + LayerNodeType *node; + bool boundary_status; + typename LayerType::ConstIterator fromIt; + NeighborhoodIterator<StatusImageType> + statusIt ( sparsePtr->m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, + this->m_LevelSet[sparsePtr->m_Index]->GetRequestedRegion() ); + + // For all indices in the "from" layer... + fromIt = sparsePtr->m_Layers[from]->Begin(); + while( fromIt != sparsePtr->m_Layers[from]->End() ) + { + // Search the neighborhood of this index in the status image for + // unassigned indicies. Push those indicies onto the "to" layer and + // assign them values in the status image. Status pixels outside the + // boundary will be ignored. + statusIt.SetLocation ( fromIt->m_Value ); + for ( unsigned int i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + { + if ( statusIt.GetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ) ) == m_StatusNull ) + { + statusIt.SetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ), to, boundary_status ); + if ( boundary_status == true ) // in bounds + { + node = sparsePtr->m_LayerNodeStore->Borrow(); + node->m_Value = statusIt.GetIndex() + sparsePtr->m_NeighborList.GetNeighborhoodOffset ( i ); + sparsePtr->m_Layers[to]->PushFront ( node ); + } + } + } + ++fromIt; + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +::AllocateUpdateBuffer() +{ + for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + SparseDataStruct *sparsePtr = this->m_SparseData[i]; + + // Preallocate the update buffer. NOTE: There is currently no way to + // downsize a std::vector. This means that the update buffer will grow + // dynamically but not shrink. In newer implementations there may be a + // squeeze method which can do this. Alternately, we can implement our + // own strategy for downsizing. + sparsePtr->m_UpdateBuffer.clear(); + sparsePtr->m_UpdateBuffer.reserve ( sparsePtr->m_Layers[0]->Size() ); + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > +::PostProcessOutput() +{ + // Get the output pointer and clear its contents + OutputImagePointer output = this->GetOutput(); + output->FillBuffer( NumericTraits<OutputPixelType>::Zero ); + + // Set the values in the levelset image for the active layer. + this->InitializeActiveLayerValues(); + // Initialize layer values using the active layer as seeds. + this->PropagateAllLayerValues(); + + for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + InputImagePointer input = this->m_LevelSet[i]; + InputPointType origin = input->GetOrigin(); + InputSpacingType spacing = input->GetSpacing(); + + // Local iterator + ImageRegionIterator< InputImageType > inIt ( this->m_LevelSet[i], + this->m_LevelSet[i]->GetLargestPossibleRegion() ); + + // In the context of the global coordinates + OutputIndexType start; + for ( unsigned int j = 0; j < ImageDimension; j++ ) + { + start[j] = static_cast<OutputIndexValueType>( origin[j]/spacing[j] ); + } + + // Defining sub-region in the global coordinates + OutputRegionType region; + region.SetSize( input->GetLargestPossibleRegion().GetSize() ); + region.SetIndex( start ); + + if ( !input || !output ) + { + itkExceptionMacro ( << "Either input and/or output is NULL." ); + } + + ImageRegionIterator< OutputImageType > outIt ( output, region ); + + OutputPixelType p = static_cast<OutputPixelType> ( this->m_Lookup[i] ); + + inIt.GoToBegin(); + outIt.GoToBegin(); + + while( !outIt.IsAtEnd() ) + { + if ( inIt.Get() < 0 ) + { + outIt.Value() = p; + } + ++inIt; + ++outIt; + } + } +} + +template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > +::PrintSelf ( std::ostream& os, Indent indent ) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "m_IsoSurfaceValue: " << this->m_IsoSurfaceValue << std::endl; + os << indent << "m_BoundsCheckingActive: " << m_BoundsCheckingActive; + + for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + SparseDataStruct *sparsePtr = this->m_SparseData[i]; + os << indent << "m_LayerNodeStore: " << std::endl; + sparsePtr->m_LayerNodeStore->Print ( os,indent.GetNextIndent() ); + for ( i = 0; i < sparsePtr->m_Layers.size(); i++ ) + { + os << indent << "m_Layers[" << i << "]: size=" + << sparsePtr->m_Layers[i]->Size() << std::endl; + os << indent << sparsePtr->m_Layers[i]; + } + + os << indent << "m_UpdateBuffer: size=" << + static_cast< unsigned long > ( sparsePtr->m_UpdateBuffer.size() ) + << " capacity = " << + static_cast<unsigned long> ( sparsePtr->m_UpdateBuffer.capacity() ) << + std::endl; + } + + os << indent << "Interpolate Surface Location " << m_InterpolateSurfaceLocation << std::endl; + os << indent << "Number of Layers " << m_NumberOfLayers << std::endl; + os << indent << "Value Zero " << + static_cast< typename NumericTraits<ValueType>::PrintType >( m_ValueZero ) << std::endl; + os << indent << "Value One " << + static_cast< typename NumericTraits<ValueType>::PrintType >( m_ValueOne ) << std::endl; +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkOptAdaptiveHistogramEqualizationImageFilter.h b/Utilities/ITK/Code/Review/itkOptAdaptiveHistogramEqualizationImageFilter.h index 207ead9ed2..2635ac1f8d 100644 --- a/Utilities/ITK/Code/Review/itkOptAdaptiveHistogramEqualizationImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptAdaptiveHistogramEqualizationImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptAdaptiveHistogramEqualizationImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-21 19:15:48 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -87,19 +87,19 @@ public: * histogram equalization (provided beta=0). Alpha=1 produces an * unsharp mask. Default is 0.3. */ itkSetMacro(Alpha, float); - itkGetMacro(Alpha, float); + itkGetConstMacro(Alpha, float); /** Set/Get the value of beta. If beta=1 (and alpha=1), * then the output image matches the input image. As beta * approaches 0, the filter behaves as an unsharp mask. Default is * 0.3. */ itkSetMacro(Beta, float); - itkGetMacro(Beta, float); + itkGetConstMacro(Beta, float); /** Set/Get whether an optimized lookup table for the intensity * mapping function is used. Default is off. */ itkSetMacro(UseLookupTable, bool); - itkGetMacro(UseLookupTable, bool); + itkGetConstMacro(UseLookupTable, bool); itkBooleanMacro(UseLookupTable); protected: diff --git a/Utilities/ITK/Code/Review/itkOptBSplineInterpolateImageFunction.h b/Utilities/ITK/Code/Review/itkOptBSplineInterpolateImageFunction.h index be571fb6be..0ab2d528db 100755 --- a/Utilities/ITK/Code/Review/itkOptBSplineInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Review/itkOptBSplineInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptBSplineInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2009-02-07 16:05:47 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -274,7 +274,7 @@ public: itkGetConstMacro(SplineOrder, int); void SetNumberOfThreads(unsigned int numThreads); - itkGetMacro(NumberOfThreads, int); + itkGetConstMacro(NumberOfThreads, int); /** Set the input image. This must be set by the user. */ virtual void SetInputImage(const TImageType * inputData); @@ -293,7 +293,7 @@ public: * ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE is ON, and OFF by default * when ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE is OFF). */ itkSetMacro( UseImageDirection, bool ); - itkGetMacro( UseImageDirection, bool ); + itkGetConstMacro( UseImageDirection, bool ); itkBooleanMacro( UseImageDirection ); diff --git a/Utilities/ITK/Code/Review/itkOptBlackTopHatImageFilter.h b/Utilities/ITK/Code/Review/itkOptBlackTopHatImageFilter.h index fa3a873ce4..77a0ab48ab 100644 --- a/Utilities/ITK/Code/Review/itkOptBlackTopHatImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptBlackTopHatImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptBlackTopHatImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -91,7 +91,7 @@ public: /** Set/Get the backend filter class. */ itkSetMacro(Algorithm, int); - itkGetMacro(Algorithm, int); + itkGetConstMacro(Algorithm, int); itkSetMacro(ForceAlgorithm, bool); itkGetConstReferenceMacro(ForceAlgorithm, bool); diff --git a/Utilities/ITK/Code/Review/itkOptGrayscaleDilateImageFilter.h b/Utilities/ITK/Code/Review/itkOptGrayscaleDilateImageFilter.h index cd7eb4cbcb..977624f6f2 100644 --- a/Utilities/ITK/Code/Review/itkOptGrayscaleDilateImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptGrayscaleDilateImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptGrayscaleDilateImageFilter.h,v $ Language: C++ - Date: $Date: 2008-09-30 18:07:03 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -105,11 +105,11 @@ public: /** Set/Get the boundary value. */ void SetBoundary( const PixelType value ); - itkGetMacro(Boundary, PixelType); + itkGetConstMacro(Boundary, PixelType); /** Set/Get the backend filter class. */ void SetAlgorithm(int algo ); - itkGetMacro(Algorithm, int); + itkGetConstMacro(Algorithm, int); /** GrayscaleDilateImageFilter need to set its internal filters as modified */ virtual void Modified() const; diff --git a/Utilities/ITK/Code/Review/itkOptGrayscaleErodeImageFilter.h b/Utilities/ITK/Code/Review/itkOptGrayscaleErodeImageFilter.h index 933ddfde93..79fb99af22 100644 --- a/Utilities/ITK/Code/Review/itkOptGrayscaleErodeImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptGrayscaleErodeImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptGrayscaleErodeImageFilter.h,v $ Language: C++ - Date: $Date: 2008-09-30 18:07:03 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -104,11 +104,11 @@ public: /** Set/Get the boundary value. */ void SetBoundary( const PixelType value ); - itkGetMacro(Boundary, PixelType); + itkGetConstMacro(Boundary, PixelType); /** Set/Get the backend filter class. */ void SetAlgorithm(int algo ); - itkGetMacro(Algorithm, int); + itkGetConstMacro(Algorithm, int); /** GrayscaleErodeImageFilter need to set its internal filters as modified */ virtual void Modified() const; diff --git a/Utilities/ITK/Code/Review/itkOptGrayscaleMorphologicalClosingImageFilter.h b/Utilities/ITK/Code/Review/itkOptGrayscaleMorphologicalClosingImageFilter.h index f11556a688..7ba243e71a 100644 --- a/Utilities/ITK/Code/Review/itkOptGrayscaleMorphologicalClosingImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptGrayscaleMorphologicalClosingImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptGrayscaleMorphologicalClosingImageFilter.h,v $ Language: C++ - Date: $Date: 2008-09-29 19:07:46 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -106,7 +106,7 @@ public: /** Set/Get the backend filter class. */ void SetAlgorithm(int algo ); - itkGetMacro(Algorithm, int); + itkGetConstMacro(Algorithm, int); /** GrayscaleMorphologicalClosingImageFilter need to set its internal filters as modified */ virtual void Modified() const; diff --git a/Utilities/ITK/Code/Review/itkOptGrayscaleMorphologicalOpeningImageFilter.h b/Utilities/ITK/Code/Review/itkOptGrayscaleMorphologicalOpeningImageFilter.h index 099d7ea9e0..97abc1d357 100644 --- a/Utilities/ITK/Code/Review/itkOptGrayscaleMorphologicalOpeningImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptGrayscaleMorphologicalOpeningImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptGrayscaleMorphologicalOpeningImageFilter.h,v $ Language: C++ - Date: $Date: 2008-09-29 19:07:46 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -106,7 +106,7 @@ public: /** Set/Get the backend filter class. */ void SetAlgorithm(int algo ); - itkGetMacro(Algorithm, int); + itkGetConstMacro(Algorithm, int); /** GrayscaleMorphologicalOpeningImageFilter need to set its internal filters as modified */ virtual void Modified() const; diff --git a/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.h b/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.h index f042dae0e7..e17ae6da7d 100755 --- a/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptLinearInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2008-01-10 21:01:46 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-03-20 10:25:38 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -62,6 +62,9 @@ public: /** InputImageType typedef support. */ typedef typename Superclass::InputImageType InputImageType; + /** InputPixelType typedef support. */ + typedef typename Superclass::InputPixelType InputPixelType; + /** RealType typedef support. */ typedef typename Superclass::RealType RealType; diff --git a/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.txx b/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.txx index d2b6dc8066..039d3e7c39 100755 --- a/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.txx +++ b/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptLinearInterpolateImageFunction.txx,v $ Language: C++ - Date: $Date: 2008-01-04 01:14:24 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-03-20 10:25:37 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -106,7 +106,9 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > * of the neighbor pixel with respect to a pixel centered on point. */ RealType value = NumericTraits<RealType>::Zero; - RealType totalOverlap = NumericTraits<RealType>::Zero; + + typedef typename NumericTraits<InputPixelType>::ScalarRealType ScalarRealType; + ScalarRealType totalOverlap = NumericTraits<ScalarRealType>::Zero; for( unsigned int counter = 0; counter < m_Neighbors; counter++ ) { @@ -137,7 +139,7 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > // get neighbor value only if overlap is not zero if( overlap ) { - value += overlap * this->GetInputImage()->GetPixel( neighIndex ); + value += static_cast<RealType>( this->GetInputImage()->GetPixel( neighIndex ) ) * overlap; totalOverlap += overlap; } diff --git a/Utilities/ITK/Code/Review/itkOptMatchCardinalityImageToImageMetric.h b/Utilities/ITK/Code/Review/itkOptMatchCardinalityImageToImageMetric.h index bb69b76c31..ba570b64f2 100755 --- a/Utilities/ITK/Code/Review/itkOptMatchCardinalityImageToImageMetric.h +++ b/Utilities/ITK/Code/Review/itkOptMatchCardinalityImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptMatchCardinalityImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2007-12-18 22:25:42 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -123,7 +123,7 @@ public: * (MeasureMatchesOn). */ itkSetMacro(MeasureMatches, bool); itkBooleanMacro(MeasureMatches); - itkGetMacro(MeasureMatches, bool); + itkGetConstMacro(MeasureMatches, bool); /** Return the multithreader used by this class. */ MultiThreader * GetMultiThreader() diff --git a/Utilities/ITK/Code/Review/itkOptMatchCardinalityImageToImageMetric.txx b/Utilities/ITK/Code/Review/itkOptMatchCardinalityImageToImageMetric.txx index a42cf3c1f8..a5d9946b42 100755 --- a/Utilities/ITK/Code/Review/itkOptMatchCardinalityImageToImageMetric.txx +++ b/Utilities/ITK/Code/Review/itkOptMatchCardinalityImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptMatchCardinalityImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2008-02-07 15:07:57 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-06 13:46:38 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -226,8 +226,8 @@ MatchCardinalityImageToImageMetric<TFixedImage, TMovingImage> // determine the actual number of pieces that will be generated typename FixedImageRegionType::SizeType::SizeValueType range = fixedRegionSize[splitAxis]; - int valuesPerThread = (int)::ceil(range/(double)num); - int maxThreadIdUsed = (int)::ceil(range/(double)valuesPerThread) - 1; + int valuesPerThread = (int)vcl_ceil(range/(double)num); + int maxThreadIdUsed = (int)vcl_ceil(range/(double)valuesPerThread) - 1; // Split the region if (i < maxThreadIdUsed) diff --git a/Utilities/ITK/Code/Review/itkOptMorphologicalGradientImageFilter.h b/Utilities/ITK/Code/Review/itkOptMorphologicalGradientImageFilter.h index 547f49e9d0..9655981e3b 100644 --- a/Utilities/ITK/Code/Review/itkOptMorphologicalGradientImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptMorphologicalGradientImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptMorphologicalGradientImageFilter.h,v $ Language: C++ - Date: $Date: 2008-09-29 19:07:46 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -107,7 +107,7 @@ public: /** Set/Get the backend filter class. */ void SetAlgorithm(int algo ); - itkGetMacro(Algorithm, int); + itkGetConstMacro(Algorithm, int); /** MorphologicalGradientImageFilter need to set its internal filters as modified */ virtual void Modified() const; diff --git a/Utilities/ITK/Code/Review/itkOptMorphologyImageFilter.h b/Utilities/ITK/Code/Review/itkOptMorphologyImageFilter.h index 1ee5b096fc..75203720d8 100644 --- a/Utilities/ITK/Code/Review/itkOptMorphologyImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptMorphologyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptMorphologyImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-06 08:50:58 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -130,7 +130,7 @@ public: } /** Get the current boundary condition. */ - itkGetMacro(BoundaryCondition, ImageBoundaryConditionPointerType); + itkGetConstMacro(BoundaryCondition, ImageBoundaryConditionPointerType); protected: MorphologyImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkOptNoiseImageFilter.txx b/Utilities/ITK/Code/Review/itkOptNoiseImageFilter.txx index a2c5447797..b2196a9a49 100644 --- a/Utilities/ITK/Code/Review/itkOptNoiseImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkOptNoiseImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptNoiseImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-08-05 12:13:44 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-06 00:19:18 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -94,7 +94,7 @@ NoiseImageFilter< TInputImage, TOutputImage> // calculate the standard deviation value var = (sumOfSquares - (sum*sum/num)) / (num - 1.0); - it.Set( static_cast<OutputPixelType>(sqrt(var)) ); + it.Set( static_cast<OutputPixelType>(vcl_sqrt(var)) ); ++bit; ++it; diff --git a/Utilities/ITK/Code/Review/itkOptResampleImageFilter.h b/Utilities/ITK/Code/Review/itkOptResampleImageFilter.h index 0e948cc3ba..9b4df52c8c 100755 --- a/Utilities/ITK/Code/Review/itkOptResampleImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptResampleImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptResampleImageFilter.h,v $ Language: C++ - Date: $Date: 2008-11-06 15:25:08 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -104,7 +104,7 @@ public: typedef typename TOutputImage::PixelType PixelType; typedef typename TInputImage::PixelType InputPixelType; - /** + /** * Transform typedef. */ typedef double CoordRepType; @@ -236,7 +236,7 @@ public: itkSetMacro(UseReferenceImage, bool); itkBooleanMacro(UseReferenceImage); - itkGetMacro(UseReferenceImage, bool); + itkGetConstMacro(UseReferenceImage, bool); /** ResampleImageFilter produces an image which is a different size * than its input. As such, it needs to provide an implementation diff --git a/Utilities/ITK/Code/Review/itkOptWhiteTopHatImageFilter.h b/Utilities/ITK/Code/Review/itkOptWhiteTopHatImageFilter.h index 8454d30fec..a0e341b532 100644 --- a/Utilities/ITK/Code/Review/itkOptWhiteTopHatImageFilter.h +++ b/Utilities/ITK/Code/Review/itkOptWhiteTopHatImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptWhiteTopHatImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -87,7 +87,7 @@ public: /** Set/Get the backend filter class. */ itkSetMacro(Algorithm, int); - itkGetMacro(Algorithm, int); + itkGetConstMacro(Algorithm, int); itkSetMacro(ForceAlgorithm, bool); itkGetConstReferenceMacro(ForceAlgorithm, bool); diff --git a/Utilities/ITK/Code/Review/itkOverUnderColormapFunctor.h b/Utilities/ITK/Code/Review/itkOverUnderColormapFunctor.h new file mode 100644 index 0000000000..eacba67651 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkOverUnderColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkOverUnderColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkOverUnderColormapFunctor_h +#define __itkOverUnderColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class OverUnderColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT OverUnderColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef OverUnderColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + OverUnderColormapFunctor() {}; + ~OverUnderColormapFunctor() {}; + +private: + OverUnderColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkOverUnderColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkOverUnderColormapFunctor.txx b/Utilities/ITK/Code/Review/itkOverUnderColormapFunctor.txx new file mode 100644 index 0000000000..cc36b44e09 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkOverUnderColormapFunctor.txx @@ -0,0 +1,69 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkOverUnderColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkOverUnderColormapFunctor_txx +#define __itkOverUnderColormapFunctor_txx + +#include "itkOverUnderColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename OverUnderColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +OverUnderColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color mapping. + RealType red = value; + RealType green = value; + RealType blue = value; + + if( value == 0.0 ) + { + // pixel is saturated in the dark + red = 0.0; + green = 0.0; + blue = 1.0; + } + else if( value == 1.0 ) + { + // pixel is saturated in the white + red = 1.0; + green = 0.0; + blue = 0.0; + } + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkPhilipsPAR.cxx b/Utilities/ITK/Code/Review/itkPhilipsPAR.cxx index b7963ebde1..3c914ccb7a 100644 --- a/Utilities/ITK/Code/Review/itkPhilipsPAR.cxx +++ b/Utilities/ITK/Code/Review/itkPhilipsPAR.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPhilipsPAR.cxx,v $ Language: C++ - Date: $Date: 2008-10-13 11:47:20 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-29 12:17:22 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -16,6 +16,7 @@ =========================================================================*/ #include "itkPhilipsPAR.h" +#include "itkExceptionObject.h" #include <fstream> #include <sstream> #include <iostream> @@ -140,107 +141,20 @@ struct image_info_defV3 # maximum RR-interval (in ms) (integer) # TURBO factor <0=no turbo> (integer) # Inversion delay (in ms) (float) -# -# === IMAGE INFORMATION =======================================================*/ -/** - * \struct image_info_defV4 - */ -struct image_info_defV4 -{ - int problemreading; - int slice; - int echo; - int dynamic; - int cardiac; - int image_type_mr; - int scan_sequence; - int index; - int image_bits; - int scan_percent; - int recon_dimx; - int recon_dimy; - float rescale_int; - float rescale_slope; - float scale_slope; - int window_center; - int window_width; - float angAP; - float angFH; - float angRL; - float offAP; - float offFH; - float offRL; - float slice_thick; - float slice_gap; - int display_orientation; - int slice_orientation; - int fmri_status_indication; - int image_type_ed_es; - float spacingx; - float spacingy; - float echo_time; - float dyn_scan_begin_time; - float trigger_time; - float diffusion_b_factor; - int num_averages; - float image_flip_angle; - int cardiac_freq; - int min_rr_int; - int max_rr_int; - int turbo_factor; - float inversion_delay; -}; - -/*# === IMAGE INFORMATION DEFINITION ============================================ -# The rest of this file contains ONE line per image, this line contains the -# following information: -# -# slice number (integer) -# echo number (integer) -# dynamic scan number (integer) -# cardiac phase number (integer) -# image_type_mr (integer) -# scanning sequence (integer) -# index in REC file (in images) (integer) -# image pixel size (in bits) (integer) -# scan percentage (integer) -# recon resolution (x y) (2*integer) -# rescale intercept (float) -# rescale slope (float) -# scale slope (float) -# window center (integer) -# window width (integer) -# image angulation (ap,fh,rl in degrees ) (3*float) -# image offcentre (ap,fh,rl in mm ) (3*float) -# slice thickness (in mm ) (float) -# slice gap (in mm ) (float) -# image_display_orientation (integer) -# slice orientation ( TRA/SAG/COR ) (integer) -# fmri_status_indication (integer) -# image_type_ed_es (end diast/end syst) (integer) -# pixel spacing (x,y) (in mm) (2*float) -# echo_time (float) -# dyn_scan_begin_time (float) -# trigger_time (float) -# diffusion_b_factor (float) -# number of averages (integer) -# image_flip_angle (in degrees) (float) -# cardiac frequency (bpm) (integer) -# minimum RR-interval (in ms) (integer) -# maximum RR-interval (in ms) (integer) -# TURBO factor <0=no turbo> (integer) -# Inversion delay (in ms) (float) +Version 4.1 # diffusion b value number (imagekey!) (integer) # gradient orientation number (imagekey!) (integer) # contrast type (string) # diffusion anisotropy type (string) # diffusion (ap, fh, rl) (3*float) +Version 4.2 +# label type (ASL) (imagekey!) (integer) # # === IMAGE INFORMATION =======================================================*/ /** - * \struct image_info_defV41 + * \struct image_info_defV4 */ -struct image_info_defV41 +struct image_info_defV4 { int problemreading; int slice; @@ -284,6 +198,7 @@ struct image_info_defV41 int max_rr_int; int turbo_factor; float inversion_delay; + // Version 4.1 added diffusion gradient information int diffusion_b_value_number; int gradient_orientation_number; int contrast_type; @@ -291,72 +206,72 @@ struct image_info_defV41 float diffusion_ap; float diffusion_fh; float diffusion_rl; + // Version 4.2 added ASL labels + int labelTypeASL; }; -static std::string GetLineNumber(std::string file, int lineNum) +struct image_info_defV3 GetImageInformationDefinitionV3(std::string file, + int lineNum, PhilipsPAR *philipsPARClass) { - std::string line = ""; - int lineCount = 0; - char readFileBuffer[512] = ""; - - if( lineNum <= 0 ) - { - return line; - } + struct image_info_defV3 tempInfo; + std::string currentLine = ""; - // Try to read the text file. - std::ifstream local_InputStream; - local_InputStream.open( file.c_str(), - std::ios::in ); - if( local_InputStream.fail() ) - { - return line; - } - while( (!local_InputStream.eof()) && (lineCount != lineNum) ) - { - local_InputStream.getline(readFileBuffer, sizeof(readFileBuffer)); - ++lineCount; - } - local_InputStream.close(); - if( lineCount == lineNum ) + memset((void*)&tempInfo,0,sizeof(struct image_info_defV3)); + if( lineNum < 89 ) { - line = readFileBuffer; + tempInfo.problemreading = 1; + return tempInfo; } - return line; -} - -static std::string GetGeneralInfoString(std::string file, int lineNum) -{ - std::string currentLine = ""; - std::string::size_type index; - std::string outString = ""; - if( (lineNum < 12) && (lineNum > 51) ) + currentLine = philipsPARClass->GetLineNumber(file,lineNum); + if( (currentLine == "") || + (currentLine == "\n") || + (currentLine == "\r\n") || + (currentLine == "\r") || + (currentLine == "# === END OF DATA DESCRIPTION FILE ======================" + "=========================") || + (currentLine == "# === END OF DATA DESCRIPTION FILE ======================" + "=========================\r")) { - return outString; + tempInfo.problemreading = 1; + return tempInfo; } - currentLine = GetLineNumber(file,lineNum); - index = currentLine.find(":"); - if( index != std::string::npos ) + std::istringstream inString(currentLine); + if( !inString ) { - std::string tempString = ":"; - outString = currentLine.substr(index+tempString.length()); + tempInfo.problemreading = 1; + return tempInfo; } - return outString; + inString >> tempInfo.slice >> tempInfo.echo >> tempInfo.dynamic; + inString >> tempInfo.cardiac >> tempInfo.image_type_mr + >> tempInfo.scan_sequence; + inString >> tempInfo.index >> tempInfo.rescale_int >> tempInfo.rescale_slope; + inString >> tempInfo.scale_slope >> tempInfo.window_center + >> tempInfo.window_width; + inString >> tempInfo.angAP >> tempInfo.angFH >> tempInfo.angRL; + inString >> tempInfo.offAP >> tempInfo.offFH >> tempInfo.offRL; + inString >> tempInfo.display_orientation >> tempInfo.slice_orientation + >> tempInfo.fmri_status_indication; + inString >> tempInfo.image_type_ed_es >> tempInfo.spacingx + >> tempInfo.spacingy; + inString >> tempInfo.echo_time >> tempInfo.dyn_scan_begin_time + >> tempInfo.trigger_time; + inString >> tempInfo.diffusion_b_factor >> tempInfo.image_flip_angle; + return tempInfo; } -static struct image_info_defV3 GetImageInformationDefinitionV3(std::string file, - int lineNum) +struct image_info_defV4 GetImageInformationDefinitionV4(std::string file, + int lineNum, PhilipsPAR *philipsPARClass) { - struct image_info_defV3 tempInfo; + struct image_info_defV4 tempInfo; std::string currentLine = ""; - memset((void*)&tempInfo,0,sizeof(struct image_info_defV3)); - if( lineNum < 89 ) + memset((void*)&tempInfo,0,sizeof(struct image_info_defV4)); + if( lineNum < 92 ) { tempInfo.problemreading = 1; return tempInfo; } - currentLine = GetLineNumber(file,lineNum); + currentLine = philipsPARClass->GetLineNumber(file,lineNum); if( (currentLine == "") || (currentLine == "\n") || (currentLine == "\r\n") || @@ -378,34 +293,41 @@ static struct image_info_defV3 GetImageInformationDefinitionV3(std::string file, inString >> tempInfo.slice >> tempInfo.echo >> tempInfo.dynamic; inString >> tempInfo.cardiac >> tempInfo.image_type_mr >> tempInfo.scan_sequence; - inString >> tempInfo.index >> tempInfo.rescale_int >> tempInfo.rescale_slope; + inString >> tempInfo.index >> tempInfo.image_bits >> tempInfo.scan_percent; + inString >> tempInfo.recon_dimx >> tempInfo.recon_dimy; + inString >> tempInfo.rescale_int >> tempInfo.rescale_slope; inString >> tempInfo.scale_slope >> tempInfo.window_center >> tempInfo.window_width; inString >> tempInfo.angAP >> tempInfo.angFH >> tempInfo.angRL; inString >> tempInfo.offAP >> tempInfo.offFH >> tempInfo.offRL; + inString >> tempInfo.slice_thick >> tempInfo.slice_gap; inString >> tempInfo.display_orientation >> tempInfo.slice_orientation >> tempInfo.fmri_status_indication; inString >> tempInfo.image_type_ed_es >> tempInfo.spacingx >> tempInfo.spacingy; inString >> tempInfo.echo_time >> tempInfo.dyn_scan_begin_time >> tempInfo.trigger_time; - inString >> tempInfo.diffusion_b_factor >> tempInfo.image_flip_angle; + inString >> tempInfo.diffusion_b_factor >> tempInfo.num_averages + >> tempInfo.image_flip_angle; + inString >> tempInfo.cardiac_freq >> tempInfo.min_rr_int + >> tempInfo.max_rr_int; + inString >> tempInfo.turbo_factor >> tempInfo.inversion_delay; return tempInfo; } -struct image_info_defV4 GetImageInformationDefinitionV4(std::string file, - int lineNum) +struct image_info_defV4 GetImageInformationDefinitionV41(std::string file, + int lineNum, PhilipsPAR *philipsPARClass) { struct image_info_defV4 tempInfo; std::string currentLine = ""; memset((void*)&tempInfo,0,sizeof(struct image_info_defV4)); - if( lineNum < 92 ) + if( lineNum < 99 ) { tempInfo.problemreading = 1; return tempInfo; } - currentLine = GetLineNumber(file,lineNum); + currentLine = philipsPARClass->GetLineNumber(file,lineNum); if( (currentLine == "") || (currentLine == "\n") || (currentLine == "\r\n") || @@ -446,22 +368,27 @@ struct image_info_defV4 GetImageInformationDefinitionV4(std::string file, inString >> tempInfo.cardiac_freq >> tempInfo.min_rr_int >> tempInfo.max_rr_int; inString >> tempInfo.turbo_factor >> tempInfo.inversion_delay; + inString >> tempInfo.diffusion_b_value_number + >> tempInfo.gradient_orientation_number; + inString >> tempInfo.contrast_type >> tempInfo.contrast_type; + inString >> tempInfo.diffusion_ap >> tempInfo.diffusion_fh + >> tempInfo.diffusion_rl; return tempInfo; } -struct image_info_defV41 GetImageInformationDefinitionV41(std::string file, - int lineNum) +struct image_info_defV4 GetImageInformationDefinitionV42(std::string file, + int lineNum, PhilipsPAR *philipsPARClass) { - struct image_info_defV41 tempInfo; + struct image_info_defV4 tempInfo; std::string currentLine = ""; - memset((void*)&tempInfo,0,sizeof(struct image_info_defV41)); - if( lineNum < 99 ) + memset((void*)&tempInfo,0,sizeof(struct image_info_defV4)); + if( lineNum < 101 ) { tempInfo.problemreading = 1; return tempInfo; } - currentLine = GetLineNumber(file,lineNum); + currentLine = philipsPARClass->GetLineNumber(file,lineNum); if( (currentLine == "") || (currentLine == "\n") || (currentLine == "\r\n") || @@ -507,26 +434,144 @@ struct image_info_defV41 GetImageInformationDefinitionV41(std::string file, inString >> tempInfo.contrast_type >> tempInfo.contrast_type; inString >> tempInfo.diffusion_ap >> tempInfo.diffusion_fh >> tempInfo.diffusion_rl; + inString >> tempInfo.labelTypeASL; return tempInfo; } -#define UNDEFINED "Undefined" +PhilipsPAR::PhilipsPAR() +{ + this->m_FileName = ""; + this->m_PARFileLines.resize(0); +} + +PhilipsPAR::~PhilipsPAR() +{ +} + +std::string PhilipsPAR::GetLineNumber(std::string file, int lineNum) +{ + std::string line = ""; + char readFileBuffer[1024] = ""; -// Adapted from r2agui.m -bool ReadPAR(std::string parFile, struct par_parameter* pPar) + if( lineNum <= 0 ) + { + return line; + } + + // If this is the first time, read the whole file into memory. + if( file != this->m_FileName ) + { + this->m_FileName = file; + this->m_PARFileLines.resize(0); + + // Try to read the text file. + std::ifstream local_InputStream; + local_InputStream.open( file.c_str(), std::ios::in ); + if( local_InputStream.fail() ) + { + return line; + } + while( !local_InputStream.eof() ) + { + local_InputStream.getline(readFileBuffer, sizeof(readFileBuffer)); + line = readFileBuffer; + this->m_PARFileLines.push_back(line); + } + local_InputStream.close(); + } + + // Return line if not EOF. + line = ""; + if( (std::vector<std::string>::size_type)lineNum + <= this->m_PARFileLines.size() ) + { + line = this->m_PARFileLines[lineNum-1]; + } + + return line; +} + +int PhilipsPAR::GetPARVersion(std::string parFile) { //read version number of Philips research tools //Research tools are used to extract data from database; data formats differ - //considerably between versions. Handles V3, V4, and V4.1 + //considerably between versions. Handles V3, V4, V4.1, and V4.2 + std::string currentLine = ""; + int ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_UNKNOWN; + + // Character index 61 on line 8 should be 'V'. + currentLine = this->GetLineNumber(parFile,8); + if( (currentLine.length() >= 63) + && (currentLine[61] == 'V') ) + { + // Next characters contain the version number. + switch(currentLine[62]) + { + case '3': + ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V3; + break; + case '4': + { + if( (currentLine.length() == 63) + || (currentLine[63]) != '.' ) + { + ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4; + } + else if( currentLine.length() >= 65 ) + { + switch( currentLine[64] ) + { + case '1': + ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4_1; + break; + case '2': + ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4_2; + break; + } + } + } + break; + } + } + return ResToolsVersion; +} + +std::string PhilipsPAR::GetGeneralInfoString(std::string file, int lineNum) +{ std::string currentLine = ""; + std::string::size_type index; + std::string outString = ""; + if( (lineNum < 12) && (lineNum > 51) ) + { + return outString; + } + currentLine = this->GetLineNumber(file,lineNum); + index = currentLine.find(":"); + if( index != std::string::npos ) + { + std::string tempString = ":"; + outString = currentLine.substr(index+tempString.length()); + } + return outString; +} + + +#define UNDEFINED "Undefined" + +// Orignally adapted from r2agui.m +void PhilipsPAR::ReadPAR(std::string parFile, struct par_parameter* pPar) +{ std::string temp = ""; - std::string::size_type index = 0; std::istringstream inString; if( pPar == NULL ) { - std::cerr << "ReadPAR: pPar == NULL" << std::endl; - return false; + OStringStream message; + message << "ReadPAR: pPar == NULL"; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } // Zero out struct. @@ -547,630 +592,105 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) // Set num_slice_repetitions to 1 to avoid divide by zero. pPar->num_slice_repetitions = 1; - // Check version of PAR file. - currentLine = GetLineNumber(parFile,8); - //std::cout << currentLine << std::endl; - index = currentLine.find("V3"); - if( index != std::string::npos ) - { - pPar->ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V3; - } - else - { - index = currentLine.find("V4.1"); - if( index != std::string::npos ) - { - pPar->ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4_1; - } - else - { - index = currentLine.find("V4"); - if( index != std::string::npos ) - { - pPar->ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4; - } - else - { - pPar->problemreading = 1; - std::cerr << "ReadPAR: Unknown PAR version?" << std::endl; - return false; - } - } - } - - switch( pPar->ResToolsVersion ) + // Get PAR version. + pPar->ResToolsVersion = this->GetPARVersion(parFile); + + // Parse PAR file according to version. + switch( pPar->ResToolsVersion ) { case RESEARCH_IMAGE_EXPORT_TOOL_V3: { struct image_info_defV3 tempInfo; struct image_info_defV3 tempInfo1; float fovAP, fovFH, fovRL; - strncpy(pPar->patient_name,GetGeneralInfoString(parFile,12).c_str(), + // Start at line 12 and work through PAR file. + // Line numbers are hard-coded on purpose. + strncpy(pPar->patient_name,this->GetGeneralInfoString(parFile,12).c_str(), sizeof(pPar->patient_name)); - strncpy(pPar->exam_name,GetGeneralInfoString(parFile,13).c_str(), + strncpy(pPar->exam_name,this->GetGeneralInfoString(parFile,13).c_str(), sizeof(pPar->exam_name)); - strncpy(pPar->protocol_name,GetGeneralInfoString(parFile,14).c_str(), + strncpy(pPar->protocol_name,this->GetGeneralInfoString(parFile,14).c_str(), sizeof(pPar->protocol_name)); - strncpy(pPar->exam_date,GetGeneralInfoString(parFile,15).c_str(), - GetGeneralInfoString(parFile,15).find("/")); + strncpy(pPar->exam_date,this->GetGeneralInfoString(parFile,15).c_str(), + this->GetGeneralInfoString(parFile,15).find("/")); strncpy(pPar->exam_time, - GetGeneralInfoString(parFile,15).substr( - GetGeneralInfoString(parFile,15).find("/")+1).c_str(), + this->GetGeneralInfoString(parFile,15).substr( + this->GetGeneralInfoString(parFile,15).find("/")+1).c_str(), sizeof(pPar->exam_time)); - inString.str(GetGeneralInfoString(parFile,16)); + inString.str(this->GetGeneralInfoString(parFile,16)); inString >> pPar->scno; inString.clear(); - inString.str(GetGeneralInfoString(parFile,17)); + inString.str(this->GetGeneralInfoString(parFile,17)); inString >> pPar->recno; inString.clear(); - inString.str(GetGeneralInfoString(parFile,18)); + inString.str(this->GetGeneralInfoString(parFile,18)); inString >> pPar->scan_duration; inString.clear(); - inString.str(GetGeneralInfoString(parFile,19)); + inString.str(this->GetGeneralInfoString(parFile,19)); inString >> pPar->cardiac_phases; inString.clear(); - inString.str(GetGeneralInfoString(parFile,20)); + inString.str(this->GetGeneralInfoString(parFile,20)); inString >> pPar->echoes; inString.clear(); - inString.str(GetGeneralInfoString(parFile,21)); + inString.str(this->GetGeneralInfoString(parFile,21)); inString >> pPar->slice; inString.clear(); - inString.str(GetGeneralInfoString(parFile,22)); + inString.str(this->GetGeneralInfoString(parFile,22)); inString >> pPar->dyn; inString.clear(); - inString.str(GetGeneralInfoString(parFile,23)); + inString.str(this->GetGeneralInfoString(parFile,23)); inString >> pPar->mixes; inString.clear(); - inString.str(GetGeneralInfoString(parFile,24)); + inString.str(this->GetGeneralInfoString(parFile,24)); inString >> pPar->bit; inString.clear(); - strncpy(pPar->technique,GetGeneralInfoString(parFile,25).c_str(), + strncpy(pPar->technique,this->GetGeneralInfoString(parFile,25).c_str(), sizeof(pPar->technique)); - strncpy(pPar->scan_mode,GetGeneralInfoString(parFile,26).c_str(), + strncpy(pPar->scan_mode,this->GetGeneralInfoString(parFile,26).c_str(), sizeof(pPar->scan_mode)); - inString.str(GetGeneralInfoString(parFile,27)); + inString.str(this->GetGeneralInfoString(parFile,27)); inString >> pPar->scan_resolution[0]; inString >> pPar->scan_resolution[1]; inString.clear(); - inString.str(GetGeneralInfoString(parFile,28)); - inString >> pPar->scan_percent; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,29)); - inString >> pPar->dim[0] >> pPar->dim[1]; - pPar->dim[2] = pPar->slice; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,30)); - inString >> pPar->num_averages; - inString.clear(); - // It appears that the max number of mixes - // parameter indicates the number of experiment - // repititions. This assumption is based on - // the T1 mapping images that use the look-locker - // sequence. - inString.str(GetGeneralInfoString(parFile,31)); - for(int repTime=0; repTime<pPar->mixes; repTime++) - { - inString >> pPar->repetition_time[repTime]; - } - inString.clear(); - tempInfo = GetImageInformationDefinitionV3(parFile, 89); - if( tempInfo.problemreading ) - { - pPar->problemreading = 1; - std::cerr << "ReadPAR: GetImageInformationDefinitionV3(parFile, 89)" - << std::endl; - return false; - } - pPar->sliceorient = tempInfo.slice_orientation; - int echoNumber = tempInfo.echo; - pPar->echo_times[0] = tempInfo.echo_time; - int cardiacPhase = tempInfo.cardiac; - pPar->trigger_times[0] = tempInfo.trigger_time; - pPar->vox[0] = tempInfo.spacingx; - pPar->vox[1] = tempInfo.spacingy; - inString.str(GetGeneralInfoString(parFile,32)); - inString >> fovAP >> fovFH >> fovRL; - inString.clear(); - // slice orientation: transversal - if( pPar->sliceorient == PAR_SLICE_ORIENTATION_TRANSVERSAL ) - { - pPar->fov[0] = fovAP; - pPar->fov[1] = fovRL; - } - // slice orientation: sagittal - if( pPar->sliceorient == PAR_SLICE_ORIENTATION_SAGITTAL ) - { - pPar->fov[0] = fovFH; - pPar->fov[1] = fovAP; - } - // slice orientation: coronal - if( pPar->sliceorient == PAR_SLICE_ORIENTATION_CORONAL ) - { - pPar->fov[0] = fovRL; - pPar->fov[1] = fovFH; - } - inString.str(GetGeneralInfoString(parFile,33)); - inString >> pPar->slth; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,34)); - inString >> pPar->gap; - inString.clear(); - pPar->fov[2] = (pPar->gap + pPar->slth)*pPar->slice; - pPar->vox[2] = pPar->slth + pPar->gap; - inString.str(GetGeneralInfoString(parFile,35)); - inString >> pPar->water_fat_shift; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,36)); - inString >> pPar->angAP; - inString >> pPar->angFH; - inString >> pPar->angRL; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,37)); - inString >> pPar->offAP; - inString >> pPar->offFH; - inString >> pPar->offRL; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,38)); - inString >> pPar->flow_comp; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,39)); - inString >> pPar->presaturation; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,40)); - inString >> pPar->cardiac_freq; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,41)); - inString >> pPar->min_rr_int; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,42)); - inString >> pPar->max_rr_int; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,43)); - inString >> pPar->phase_encode_vel[0]; - inString >> pPar->phase_encode_vel[1]; - inString >> pPar->phase_encode_vel[2]; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,44)); - inString >> pPar->mtc; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,45)); - inString >> pPar->spir; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,46)); - inString >> pPar->epi; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,47)); - inString >> pPar->turbo; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,48)); - inString >> pPar->dynamic_scan; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,49)); - inString >> pPar->diffusion; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,50)); - inString >> pPar->diff_echo; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,51)); - inString >> pPar->inversion_delay; - inString.clear(); - // OK, need to figure out how many images are stored in the REC file - // and whether or not the images are sorted by slice or by image blocks. - // Also get echo times and trigger_times. - if( pPar->slice > 1 ) - { - int lineIncrement = 89; - int echoIndex = 0; - int cardiacIndex = 0; - tempInfo1 = GetImageInformationDefinitionV3(parFile, 90); - if( tempInfo1.problemreading ) - { - pPar->problemreading = 1; - std::cerr << "ReadPAR: GetImageInformationDefinitionV3(parFile, 90)" - << std::endl; - return false; - } - if ((tempInfo1.slice-tempInfo.slice) > 0 ) - { - pPar->slicessorted = 1; - } - // If slices are sorted I only need to calculate the number of - // image blocks (if more than 1) and store the echo times. - if( pPar->slicessorted ) - { - ++pPar->image_blocks; - ++pPar->num_image_types; - pPar->image_types[0] = tempInfo.image_type_mr; - ++pPar->num_scanning_sequences; - pPar->scanning_sequences[0] = tempInfo.scan_sequence; - lineIncrement += pPar->slice; - tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement); - while( !tempInfo1.problemreading && tempInfo1.slice ) - { - int isUnique = 1; - // Find unique image types in REC. - for(int i=0; i<pPar->num_image_types; i++) - { - if( pPar->image_types[i] == tempInfo1.image_type_mr ) - { - isUnique = 0; - break; - } - } - if( isUnique ) - { - ++pPar->num_image_types; - pPar->image_types[pPar->num_image_types-1] = - tempInfo1.image_type_mr; - } - isUnique = 1; - // Find all of the scanning sequences. - for(int i=0; i<pPar->num_scanning_sequences; i++) - { - if( pPar->scanning_sequences[i] == tempInfo1.scan_sequence ) - { - isUnique = 0; - break; - } - } - if( isUnique ) - { - ++pPar->num_scanning_sequences; - pPar->scanning_sequences[pPar->num_scanning_sequences-1] = - tempInfo1.scan_sequence; - } - ++pPar->image_blocks; - lineIncrement += pPar->slice; - // Get the echo times. - if( echoNumber != tempInfo1.echo ) - { - ++echoIndex; - pPar->echo_times[echoIndex] = tempInfo1.echo_time; - echoNumber = tempInfo1.echo; - } - // Get the trigger times - if( cardiacPhase != tempInfo1.cardiac ) - { - ++cardiacIndex; - pPar->trigger_times[cardiacIndex] = tempInfo1.trigger_time; - cardiacPhase = tempInfo1.cardiac; - } - tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement); - } - } - // Slices are not sorted. - else - { - int slice = tempInfo.slice; - ++pPar->image_blocks; - ++pPar->num_image_types; - pPar->image_types[0] = tempInfo.image_type_mr; - ++pPar->num_scanning_sequences; - pPar->scanning_sequences[0] = tempInfo.scan_sequence; - ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement); - while( !tempInfo1.problemreading && tempInfo1.slice ) - { - if( slice == tempInfo1.slice ) - { - int isUnique = 1; - // Find unique image types in REC. - for(int i=0; i<pPar->num_image_types; i++) - { - if( pPar->image_types[i] == tempInfo1.image_type_mr ) - { - isUnique = 0; - break; - } - } - if( isUnique ) - { - ++pPar->num_image_types; - pPar->image_types[pPar->num_image_types-1] = - tempInfo1.image_type_mr; - } - isUnique = 1; - // Find all of the scanning sequences. - for(int i=0; i<pPar->num_scanning_sequences; i++) - { - if( pPar->scanning_sequences[i] == tempInfo1.scan_sequence ) - { - isUnique = 0; - break; - } - } - if( isUnique ) - { - ++pPar->num_scanning_sequences; - pPar->scanning_sequences[pPar->num_scanning_sequences-1] = - tempInfo1.scan_sequence; - } - ++pPar->image_blocks; - // Get the echo times. - if( echoNumber != tempInfo1.echo ) - { - ++echoIndex; - pPar->echo_times[echoIndex] = tempInfo1.echo_time; - echoNumber = tempInfo1.echo; - } - // Get the trigger times - if( cardiacPhase != tempInfo1.cardiac ) - { - ++cardiacIndex; - pPar->trigger_times[cardiacIndex] = tempInfo1.trigger_time; - cardiacPhase = tempInfo1.cardiac; - } - } - else - { - lineIncrement = 89; - // OK, I need to determine if there are more image blocks, only - // if pPar->num_image_types or pPar->num_scanning_sequences > 1 - if( (pPar->num_image_types > 1) || - (pPar->num_scanning_sequences > 1) ) - { - pPar->num_slice_repetitions = pPar->image_blocks; - lineIncrement += (pPar->slice*pPar->num_slice_repetitions); - tempInfo1 = GetImageInformationDefinitionV3(parFile, - lineIncrement); - while( !tempInfo1.problemreading && tempInfo1.slice ) - { - // Get the echo times. - if( echoNumber != tempInfo1.echo ) - { - ++echoIndex; - pPar->echo_times[echoIndex] = tempInfo1.echo_time; - echoNumber = tempInfo1.echo; - } - // Get the trigger times - if( cardiacPhase != tempInfo1.cardiac ) - { - ++cardiacIndex; - pPar->trigger_times[cardiacIndex] = tempInfo1.trigger_time; - cardiacPhase = tempInfo1.cardiac; - } - pPar->image_blocks += pPar->num_slice_repetitions; - lineIncrement += (pPar->slice*pPar->num_slice_repetitions); - tempInfo1 = GetImageInformationDefinitionV3(parFile, - lineIncrement); - } - } - break; - } - ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement); - } - } - // This is a sanity check. The echoIndex should match - // (pPar->echoes-1). - if( (pPar->echoes-1) != echoIndex ) - { - pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->echoes-1) != echoIndex" << std::endl; - std::cerr << "pPar->echoes-1 = " << pPar->echoes-1 << std::endl; - std::cerr << "echoIndex = " << echoIndex << std::endl; - return false; - } - // Another sanity check. The cardiacIndex should match - // (pPar->cardiac_phases-1). - if( (pPar->cardiac_phases-1) != cardiacIndex ) - { - pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex" - << std::endl; - std::cerr << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 - << std::endl; - std::cerr << "cardiacIndex = " << cardiacIndex << std::endl; - return false; - } - } - // Only 1 slice, but how many repetitions of that slice? - else - { - int lineIncrement = 89; - int echoIndex = 0; - int cardiacIndex = 0; - int slice = tempInfo.slice; - int firstEchoNumber = echoNumber; - int firstCardiacPhase = cardiacPhase; - int firstDynamic = tempInfo.dynamic; - ++pPar->image_blocks; - ++pPar->num_image_types; - pPar->image_types[0] = tempInfo.image_type_mr; - ++pPar->num_scanning_sequences; - pPar->scanning_sequences[0] = tempInfo.scan_sequence; - ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement); - while( !tempInfo1.problemreading && tempInfo1.slice ) - { - if( slice == tempInfo1.slice ) - { - int isUnique = 1; - // Find unique image types in REC. - for(int i=0; i<pPar->num_image_types; i++) - { - if( pPar->image_types[i] == tempInfo1.image_type_mr ) - { - isUnique = 0; - break; - } - } - if( isUnique ) - { - ++pPar->num_image_types; - pPar->image_types[pPar->num_image_types-1] = - tempInfo1.image_type_mr; - } - isUnique = 1; - // Find all of the scanning sequences. - for(int i=0; i<pPar->num_scanning_sequences; i++) - { - if( pPar->scanning_sequences[i] == tempInfo1.scan_sequence ) - { - isUnique = 0; - break; - } - } - if( isUnique ) - { - ++pPar->num_scanning_sequences; - pPar->scanning_sequences[pPar->num_scanning_sequences-1] = - tempInfo1.scan_sequence; - } - ++pPar->image_blocks; - // Get the echo times. - if( echoNumber != tempInfo1.echo ) - { - ++echoIndex; - pPar->echo_times[echoIndex] = tempInfo1.echo_time; - echoNumber = tempInfo1.echo; - } - // Get the trigger times - if( cardiacPhase != tempInfo1.cardiac ) - { - ++cardiacIndex; - pPar->trigger_times[cardiacIndex] = tempInfo1.trigger_time; - cardiacPhase = tempInfo1.cardiac; - } - // Need to keep track of the number of consecutive slice repetitions. - if( (pPar->echoes > 1) && (firstEchoNumber == tempInfo1.echo) ) - { - ++pPar->num_slice_repetitions; - } - if( (pPar->cardiac_phases > 1) && - (firstCardiacPhase == tempInfo1.cardiac) ) - { - ++pPar->num_slice_repetitions; - } - if( (pPar->dyn > 1) && (firstDynamic == tempInfo1.dynamic) ) - { - ++pPar->num_slice_repetitions; - } - } - else - { - break; - } - ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement); - } - // This is a sanity check. The echoIndex should match - // (pPar->echoes-1). - if( (pPar->echoes-1) != echoIndex ) - { - pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->echoes-1) != echoIndex" << std::endl; - std::cerr << "pPar->echoes-1 = " << pPar->echoes-1 << std::endl; - std::cerr << "echoIndex = " << echoIndex << std::endl; - return false; - } - // Another sanity check. The cardiacIndex should match - // (pPar->cardiac_phases-1). - if( (pPar->cardiac_phases-1) != cardiacIndex ) - { - pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex" - << std::endl; - std::cerr << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 - << std::endl; - std::cerr << "cardiacIndex = " << cardiacIndex << std::endl; - return false; - } - } - } - break; - - case RESEARCH_IMAGE_EXPORT_TOOL_V4: - { - struct image_info_defV4 tempInfo; - struct image_info_defV4 tempInfo1; - float fovAP, fovFH, fovRL; - strncpy(pPar->patient_name,GetGeneralInfoString(parFile,12).c_str(), - sizeof(pPar->patient_name)); - strncpy(pPar->exam_name,GetGeneralInfoString(parFile,13).c_str(), - sizeof(pPar->exam_name)); - strncpy(pPar->protocol_name,GetGeneralInfoString(parFile,14).c_str(), - sizeof(pPar->protocol_name)); - strncpy(pPar->exam_date, - GetGeneralInfoString(parFile,15).c_str(), - GetGeneralInfoString(parFile,15).find("/")); - strncpy(pPar->exam_time, - GetGeneralInfoString(parFile,15).substr( - GetGeneralInfoString(parFile,15).find("/")+1).c_str(), - sizeof(pPar->exam_time)); - strncpy(pPar->series_type,GetGeneralInfoString(parFile,16).c_str(), - sizeof(pPar->series_type)); - inString.str(GetGeneralInfoString(parFile,17)); - inString >> pPar->scno; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,18)); - inString >> pPar->recno; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,19)); - inString >> pPar->scan_duration; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,20)); - inString >> pPar->cardiac_phases; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,21)); - inString >> pPar->echoes; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,22)); - inString >> pPar->slice; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,23)); - inString >> pPar->dyn; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,24)); - inString >> pPar->mixes; - inString.clear(); - strncpy(pPar->patient_position,GetGeneralInfoString(parFile,25).c_str(), - sizeof(pPar->patient_position)); - strncpy(pPar->prep_direction,GetGeneralInfoString(parFile,26).c_str(), - sizeof(pPar->prep_direction)); - strncpy(pPar->technique,GetGeneralInfoString(parFile,27).c_str(), - sizeof(pPar->technique)); - inString.str(GetGeneralInfoString(parFile,28)); - inString >> pPar->scan_resolution[0]; - inString >> pPar->scan_resolution[1]; + inString.str(this->GetGeneralInfoString(parFile,28)); + inString >> pPar->scan_percent; inString.clear(); - inString.str(GetGeneralInfoString(parFile,29)); - inString >> pPar->scan_mode; + inString.str(this->GetGeneralInfoString(parFile,29)); + inString >> pPar->dim[0] >> pPar->dim[1]; + pPar->dim[2] = pPar->slice; + inString.clear(); + inString.str(this->GetGeneralInfoString(parFile,30)); + inString >> pPar->num_averages; inString.clear(); // It appears that the max number of mixes // parameter indicates the number of experiment // repititions. This assumption is based on // the T1 mapping images that use the look-locker // sequence. - inString.str(GetGeneralInfoString(parFile,30)); + inString.str(this->GetGeneralInfoString(parFile,31)); for(int repTime=0; repTime<pPar->mixes; repTime++) { inString >> pPar->repetition_time[repTime]; } inString.clear(); - tempInfo = GetImageInformationDefinitionV4(parFile, 92); + tempInfo = GetImageInformationDefinitionV3(parFile, 89, this); if( tempInfo.problemreading ) { - pPar->problemreading = 1; - std::cerr << "ReadPAR: GetImageInformationDefinitionV4(parFile, 92)" - << std::endl; - return false; + OStringStream message; + message << "ReadPAR: Problem with GetImageInformationDefinitionV3()"; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } pPar->sliceorient = tempInfo.slice_orientation; int echoNumber = tempInfo.echo; pPar->echo_times[0] = tempInfo.echo_time; int cardiacPhase = tempInfo.cardiac; pPar->trigger_times[0] = tempInfo.trigger_time; - pPar->dim[0] = tempInfo.recon_dimx; - pPar->dim[1] = tempInfo.recon_dimy; - pPar->dim[2] = pPar->slice; - pPar->bit = tempInfo.image_bits; - pPar->slth = tempInfo.slice_thick; - pPar->gap = tempInfo.slice_gap; pPar->vox[0] = tempInfo.spacingx; pPar->vox[1] = tempInfo.spacingy; - pPar->vox[2] = tempInfo.slice_thick + tempInfo.slice_gap; - inString.str(GetGeneralInfoString(parFile,31)); + inString.str(this->GetGeneralInfoString(parFile,32)); inString >> fovAP >> fovFH >> fovRL; inString.clear(); // slice orientation: transversal @@ -1191,64 +711,89 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) pPar->fov[0] = fovRL; pPar->fov[1] = fovFH; } + inString.str(this->GetGeneralInfoString(parFile,33)); + inString >> pPar->slth; + inString.clear(); + inString.str(this->GetGeneralInfoString(parFile,34)); + inString >> pPar->gap; + inString.clear(); pPar->fov[2] = (pPar->gap + pPar->slth)*pPar->slice; - inString.str(GetGeneralInfoString(parFile,32)); + pPar->vox[2] = pPar->slth + pPar->gap; + inString.str(this->GetGeneralInfoString(parFile,35)); inString >> pPar->water_fat_shift; inString.clear(); - inString.str(GetGeneralInfoString(parFile,33)); + inString.str(this->GetGeneralInfoString(parFile,36)); inString >> pPar->angAP; inString >> pPar->angFH; inString >> pPar->angRL; inString.clear(); - inString.str(GetGeneralInfoString(parFile,34)); + inString.str(this->GetGeneralInfoString(parFile,37)); inString >> pPar->offAP; inString >> pPar->offFH; inString >> pPar->offRL; inString.clear(); - inString.str(GetGeneralInfoString(parFile,35)); + inString.str(this->GetGeneralInfoString(parFile,38)); inString >> pPar->flow_comp; inString.clear(); - inString.str(GetGeneralInfoString(parFile,36)); + inString.str(this->GetGeneralInfoString(parFile,39)); inString >> pPar->presaturation; inString.clear(); - inString.str(GetGeneralInfoString(parFile,37)); + inString.str(this->GetGeneralInfoString(parFile,40)); + inString >> pPar->cardiac_freq; + inString.clear(); + inString.str(this->GetGeneralInfoString(parFile,41)); + inString >> pPar->min_rr_int; + inString.clear(); + inString.str(this->GetGeneralInfoString(parFile,42)); + inString >> pPar->max_rr_int; + inString.clear(); + inString.str(this->GetGeneralInfoString(parFile,43)); inString >> pPar->phase_encode_vel[0]; inString >> pPar->phase_encode_vel[1]; inString >> pPar->phase_encode_vel[2]; inString.clear(); - inString.str(GetGeneralInfoString(parFile,38)); + inString.str(this->GetGeneralInfoString(parFile,44)); inString >> pPar->mtc; inString.clear(); - inString.str(GetGeneralInfoString(parFile,39)); + inString.str(this->GetGeneralInfoString(parFile,45)); inString >> pPar->spir; inString.clear(); - inString.str(GetGeneralInfoString(parFile,40)); + inString.str(this->GetGeneralInfoString(parFile,46)); inString >> pPar->epi; inString.clear(); - inString.str(GetGeneralInfoString(parFile,41)); + inString.str(this->GetGeneralInfoString(parFile,47)); + inString >> pPar->turbo; + inString.clear(); + inString.str(this->GetGeneralInfoString(parFile,48)); inString >> pPar->dynamic_scan; inString.clear(); - inString.str(GetGeneralInfoString(parFile,42)); + inString.str(this->GetGeneralInfoString(parFile,49)); inString >> pPar->diffusion; inString.clear(); - inString.str(GetGeneralInfoString(parFile,43)); + inString.str(this->GetGeneralInfoString(parFile,50)); inString >> pPar->diff_echo; inString.clear(); + inString.str(this->GetGeneralInfoString(parFile,51)); + inString >> pPar->inversion_delay; + inString.clear(); // OK, need to figure out how many images are stored in the REC file // and whether or not the images are sorted by slice or by image blocks. - // Also get echo times. + // Also get echo times and trigger_times. if( pPar->slice > 1 ) { - int lineIncrement = 92; + int lineIncrement = 89; int echoIndex = 0; int cardiacIndex = 0; - tempInfo1 = GetImageInformationDefinitionV4(parFile, 93); + tempInfo1 = GetImageInformationDefinitionV3(parFile, 90,this); if( tempInfo1.problemreading ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: GetImageInformationDefinitionV4(parFile, 93)" - << std::endl; - return false; + OStringStream message; + message << "ReadPAR: Problem with GetImageInformationDefinitionV3()"; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } if ((tempInfo1.slice-tempInfo.slice) > 0 ) { @@ -1264,7 +809,7 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) ++pPar->num_scanning_sequences; pPar->scanning_sequences[0] = tempInfo.scan_sequence; lineIncrement += pPar->slice; - tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement, this); while( !tempInfo1.problemreading && tempInfo1.slice ) { int isUnique = 1; @@ -1300,6 +845,7 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) tempInfo1.scan_sequence; } ++pPar->image_blocks; + lineIncrement += pPar->slice; // Get the echo times. if( echoNumber != tempInfo1.echo ) { @@ -1314,8 +860,7 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) pPar->trigger_times[cardiacIndex] = tempInfo1.trigger_time; cardiacPhase = tempInfo1.cardiac; } - lineIncrement += pPar->slice; - tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement, this); } } // Slices are not sorted. @@ -1328,13 +873,12 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) ++pPar->num_scanning_sequences; pPar->scanning_sequences[0] = tempInfo.scan_sequence; ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement, this); while( !tempInfo1.problemreading && tempInfo1.slice ) { - int isUnique = 1; - // This if statement applies to just the first slice. if( slice == tempInfo1.slice ) { + int isUnique = 1; // Find unique image types in REC. for(int i=0; i<pPar->num_image_types; i++) { @@ -1382,20 +926,18 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) cardiacPhase = tempInfo1.cardiac; } } - // Now we have sufficient information to parse the rest of the PAR - // file. else { - lineIncrement = 92; - // OK, I need to determine if there are more image blocks, only + lineIncrement = 89; + // OK, I need to determine if there are more image blocks, only // if pPar->num_image_types or pPar->num_scanning_sequences > 1 if( (pPar->num_image_types > 1) || (pPar->num_scanning_sequences > 1) ) { pPar->num_slice_repetitions = pPar->image_blocks; lineIncrement += (pPar->slice*pPar->num_slice_repetitions); - tempInfo1 = GetImageInformationDefinitionV4(parFile, - lineIncrement); + tempInfo1 = GetImageInformationDefinitionV3(parFile, + lineIncrement, this); while( !tempInfo1.problemreading && tempInfo1.slice ) { // Get the echo times. @@ -1414,14 +956,14 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) } pPar->image_blocks += pPar->num_slice_repetitions; lineIncrement += (pPar->slice*pPar->num_slice_repetitions); - tempInfo1 = GetImageInformationDefinitionV4(parFile, - lineIncrement); + tempInfo1 = GetImageInformationDefinitionV3(parFile, + lineIncrement, this); } } break; } ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement, this); } } // This is a sanity check. The echoIndex should match @@ -1429,28 +971,34 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) if( (pPar->echoes-1) != echoIndex ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->echoes-1) != echoIndex" << std::endl; - std::cerr << "pPar->echoes-1 = " << pPar->echoes-1 << std::endl; - std::cerr << "echoIndex = " << echoIndex << std::endl; - return false; + OStringStream message; + message << "ReadPAR: (pPar->echoes-1) != echoIndex, " + << "pPar->echoes-1 = " << pPar->echoes-1 + << " and echoIndex = " << echoIndex; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } // Another sanity check. The cardiacIndex should match // (pPar->cardiac_phases-1). if( (pPar->cardiac_phases-1) != cardiacIndex ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex" - << std::endl; - std::cerr << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 - << std::endl; - std::cerr << "cardiacIndex = " << cardiacIndex << std::endl; - return false; + OStringStream message; + message << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex, " + << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 + << " and cardiacIndex = " << cardiacIndex; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } } // Only 1 slice, but how many repetitions of that slice? else { - int lineIncrement = 92; + int lineIncrement = 89; int echoIndex = 0; int cardiacIndex = 0; int slice = tempInfo.slice; @@ -1463,7 +1011,7 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) ++pPar->num_scanning_sequences; pPar->scanning_sequences[0] = tempInfo.scan_sequence; ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement, this); while( !tempInfo1.problemreading && tempInfo1.slice ) { if( slice == tempInfo1.slice ) @@ -1501,9 +1049,7 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) tempInfo1.scan_sequence; } ++pPar->image_blocks; - // Should be equal after the first iteration, but will only - // add additional echoes in latter iterations if they differ - // from the first. + // Get the echo times. if( echoNumber != tempInfo1.echo ) { ++echoIndex; @@ -1537,89 +1083,99 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) break; } ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo1 = GetImageInformationDefinitionV3(parFile, lineIncrement, this); } // This is a sanity check. The echoIndex should match // (pPar->echoes-1). if( (pPar->echoes-1) != echoIndex ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->echoes-1) != echoIndex" << std::endl; - std::cerr << "pPar->echoes-1 = " << pPar->echoes-1 << std::endl; - std::cerr << "echoIndex = " << echoIndex << std::endl; - return false; + OStringStream message; + message << "ReadPAR: (pPar->echoes-1) != echoIndex, " + << "pPar->echoes-1 = " << pPar->echoes-1 + << " and echoIndex = " << echoIndex; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } // Another sanity check. The cardiacIndex should match // (pPar->cardiac_phases-1). if( (pPar->cardiac_phases-1) != cardiacIndex ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex" - << std::endl; - std::cerr << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 - << std::endl; - std::cerr << "cardiacIndex = " << cardiacIndex << std::endl; - return false; + OStringStream message; + message << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex, " + << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 + << " and cardiacIndex = " << cardiacIndex; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } } } break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4: case RESEARCH_IMAGE_EXPORT_TOOL_V4_1: + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: { - struct image_info_defV41 tempInfo; - struct image_info_defV41 tempInfo1; + struct image_info_defV4 tempInfo; + struct image_info_defV4 tempInfo1; float fovAP, fovFH, fovRL; - strncpy(pPar->patient_name,GetGeneralInfoString(parFile,12).c_str(), + // Start at line 12 and work through PAR file. + // Line numbers are hard-coded on purpose. + strncpy(pPar->patient_name,this->GetGeneralInfoString(parFile,12).c_str(), sizeof(pPar->patient_name)); - strncpy(pPar->exam_name,GetGeneralInfoString(parFile,13).c_str(), + strncpy(pPar->exam_name,this->GetGeneralInfoString(parFile,13).c_str(), sizeof(pPar->exam_name)); - strncpy(pPar->protocol_name,GetGeneralInfoString(parFile,14).c_str(), + strncpy(pPar->protocol_name,this->GetGeneralInfoString(parFile,14).c_str(), sizeof(pPar->protocol_name)); strncpy(pPar->exam_date, - GetGeneralInfoString(parFile,15).c_str(), - GetGeneralInfoString(parFile,15).find("/")); + this->GetGeneralInfoString(parFile,15).c_str(), + this->GetGeneralInfoString(parFile,15).find("/")); strncpy(pPar->exam_time, - GetGeneralInfoString(parFile,15).substr( - GetGeneralInfoString(parFile,15).find("/")+1).c_str(), + this->GetGeneralInfoString(parFile,15).substr( + this->GetGeneralInfoString(parFile,15).find("/")+1).c_str(), sizeof(pPar->exam_time)); - strncpy(pPar->series_type,GetGeneralInfoString(parFile,16).c_str(), + strncpy(pPar->series_type,this->GetGeneralInfoString(parFile,16).c_str(), sizeof(pPar->series_type)); - inString.str(GetGeneralInfoString(parFile,17)); + inString.str(this->GetGeneralInfoString(parFile,17)); inString >> pPar->scno; inString.clear(); - inString.str(GetGeneralInfoString(parFile,18)); + inString.str(this->GetGeneralInfoString(parFile,18)); inString >> pPar->recno; inString.clear(); - inString.str(GetGeneralInfoString(parFile,19)); + inString.str(this->GetGeneralInfoString(parFile,19)); inString >> pPar->scan_duration; inString.clear(); - inString.str(GetGeneralInfoString(parFile,20)); + inString.str(this->GetGeneralInfoString(parFile,20)); inString >> pPar->cardiac_phases; inString.clear(); - inString.str(GetGeneralInfoString(parFile,21)); + inString.str(this->GetGeneralInfoString(parFile,21)); inString >> pPar->echoes; inString.clear(); - inString.str(GetGeneralInfoString(parFile,22)); + inString.str(this->GetGeneralInfoString(parFile,22)); inString >> pPar->slice; inString.clear(); - inString.str(GetGeneralInfoString(parFile,23)); + inString.str(this->GetGeneralInfoString(parFile,23)); inString >> pPar->dyn; inString.clear(); - inString.str(GetGeneralInfoString(parFile,24)); + inString.str(this->GetGeneralInfoString(parFile,24)); inString >> pPar->mixes; inString.clear(); - strncpy(pPar->patient_position,GetGeneralInfoString(parFile,25).c_str(), + strncpy(pPar->patient_position,this->GetGeneralInfoString(parFile,25).c_str(), sizeof(pPar->patient_position)); - strncpy(pPar->prep_direction,GetGeneralInfoString(parFile,26).c_str(), + strncpy(pPar->prep_direction,this->GetGeneralInfoString(parFile,26).c_str(), sizeof(pPar->prep_direction)); - strncpy(pPar->technique,GetGeneralInfoString(parFile,27).c_str(), + strncpy(pPar->technique,this->GetGeneralInfoString(parFile,27).c_str(), sizeof(pPar->technique)); - inString.str(GetGeneralInfoString(parFile,28)); + inString.str(this->GetGeneralInfoString(parFile,28)); inString >> pPar->scan_resolution[0]; inString >> pPar->scan_resolution[1]; inString.clear(); - inString.str(GetGeneralInfoString(parFile,29)); + inString.str(this->GetGeneralInfoString(parFile,29)); inString >> pPar->scan_mode; inString.clear(); // It appears that the max number of mixes @@ -1627,19 +1183,33 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) // repititions. This assumption is based on // the T1 mapping images that use the look-locker // sequence. - inString.str(GetGeneralInfoString(parFile,30)); + inString.str(this->GetGeneralInfoString(parFile,30)); for(int repTime=0; repTime<pPar->mixes; repTime++) { inString >> pPar->repetition_time[repTime]; } inString.clear(); - tempInfo = GetImageInformationDefinitionV41(parFile, 99); + switch( pPar->ResToolsVersion ) + { + case RESEARCH_IMAGE_EXPORT_TOOL_V4: + tempInfo = GetImageInformationDefinitionV4(parFile, 92, this); + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_1: + tempInfo = GetImageInformationDefinitionV41(parFile, 99, this); + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: + tempInfo = GetImageInformationDefinitionV42(parFile, 101, this); + break; + } if( tempInfo.problemreading ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: GetImageInformationDefinitionV41(parFile, 99)" - << std::endl; - return false; + OStringStream message; + message << "ReadPAR: Problem with GetImageInformationDefinitionV4()"; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } pPar->sliceorient = tempInfo.slice_orientation; int echoNumber = tempInfo.echo; @@ -1655,7 +1225,7 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) pPar->vox[0] = tempInfo.spacingx; pPar->vox[1] = tempInfo.spacingy; pPar->vox[2] = tempInfo.slice_thick + tempInfo.slice_gap; - inString.str(GetGeneralInfoString(parFile,31)); + inString.str(this->GetGeneralInfoString(parFile,31)); inString >> fovAP >> fovFH >> fovRL; inString.clear(); // slice orientation: transversal @@ -1677,69 +1247,96 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) pPar->fov[1] = fovFH; } pPar->fov[2] = (pPar->gap + pPar->slth)*pPar->slice; - inString.str(GetGeneralInfoString(parFile,32)); + inString.str(this->GetGeneralInfoString(parFile,32)); inString >> pPar->water_fat_shift; inString.clear(); - inString.str(GetGeneralInfoString(parFile,33)); + inString.str(this->GetGeneralInfoString(parFile,33)); inString >> pPar->angAP; inString >> pPar->angFH; inString >> pPar->angRL; inString.clear(); - inString.str(GetGeneralInfoString(parFile,34)); + inString.str(this->GetGeneralInfoString(parFile,34)); inString >> pPar->offAP; inString >> pPar->offFH; inString >> pPar->offRL; inString.clear(); - inString.str(GetGeneralInfoString(parFile,35)); + inString.str(this->GetGeneralInfoString(parFile,35)); inString >> pPar->flow_comp; inString.clear(); - inString.str(GetGeneralInfoString(parFile,36)); + inString.str(this->GetGeneralInfoString(parFile,36)); inString >> pPar->presaturation; inString.clear(); - inString.str(GetGeneralInfoString(parFile,37)); + inString.str(this->GetGeneralInfoString(parFile,37)); inString >> pPar->phase_encode_vel[0]; inString >> pPar->phase_encode_vel[1]; inString >> pPar->phase_encode_vel[2]; inString.clear(); - inString.str(GetGeneralInfoString(parFile,38)); + inString.str(this->GetGeneralInfoString(parFile,38)); inString >> pPar->mtc; inString.clear(); - inString.str(GetGeneralInfoString(parFile,39)); + inString.str(this->GetGeneralInfoString(parFile,39)); inString >> pPar->spir; inString.clear(); - inString.str(GetGeneralInfoString(parFile,40)); + inString.str(this->GetGeneralInfoString(parFile,40)); inString >> pPar->epi; inString.clear(); - inString.str(GetGeneralInfoString(parFile,41)); + inString.str(this->GetGeneralInfoString(parFile,41)); inString >> pPar->dynamic_scan; inString.clear(); - inString.str(GetGeneralInfoString(parFile,42)); + inString.str(this->GetGeneralInfoString(parFile,42)); inString >> pPar->diffusion; inString.clear(); - inString.str(GetGeneralInfoString(parFile,43)); + inString.str(this->GetGeneralInfoString(parFile,43)); inString >> pPar->diff_echo; inString.clear(); - inString.str(GetGeneralInfoString(parFile,44)); - inString >> pPar->max_num_diff_vals; - inString.clear(); - inString.str(GetGeneralInfoString(parFile,45)); - inString >> pPar->max_num_grad_orient; - inString.clear(); + // Versions >= 4.1 + if( pPar->ResToolsVersion >= RESEARCH_IMAGE_EXPORT_TOOL_V4_1 ) + { + inString.str(this->GetGeneralInfoString(parFile,44)); + inString >> pPar->max_num_diff_vals; + inString.clear(); + inString.str(this->GetGeneralInfoString(parFile,45)); + inString >> pPar->max_num_grad_orient; + inString.clear(); + } + // Version 4.2 only + if( pPar->ResToolsVersion == RESEARCH_IMAGE_EXPORT_TOOL_V4_2 ) + { + inString.str(this->GetGeneralInfoString(parFile,46)); + inString >> pPar->num_label_types; + inString.clear(); + } // OK, need to figure out how many images are stored in the REC file // and whether or not the images are sorted by slice or by image blocks. // Also get echo times. if( pPar->slice > 1 ) { - int lineIncrement = 99; + int lineIncrement = 92; int echoIndex = 0; int cardiacIndex = 0; - tempInfo1 = GetImageInformationDefinitionV41(parFile, 100); + switch( pPar->ResToolsVersion ) + { + case RESEARCH_IMAGE_EXPORT_TOOL_V4: + tempInfo1 = GetImageInformationDefinitionV4(parFile, 93, this); + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_1: + lineIncrement = 99; + tempInfo1 = GetImageInformationDefinitionV41(parFile, 100, this); + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: + lineIncrement = 101; + tempInfo1 = GetImageInformationDefinitionV42(parFile, 102, this); + break; + } if( tempInfo1.problemreading ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: GetImageInformationDefinitionV41(parFile, 100)" - << std::endl; - return false; + OStringStream message; + message << "ReadPAR: Problem with GetImageInformationV4()"; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } if ((tempInfo1.slice-tempInfo.slice) > 0 ) { @@ -1755,7 +1352,8 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) ++pPar->num_scanning_sequences; pPar->scanning_sequences[0] = tempInfo.scan_sequence; lineIncrement += pPar->slice; - tempInfo1 = GetImageInformationDefinitionV41(parFile, lineIncrement); + // lineIncrement is set according to version 4.x PAR file. + tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement, this); while( !tempInfo1.problemreading && tempInfo1.slice ) { int isUnique = 1; @@ -1790,9 +1388,7 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) pPar->scanning_sequences[pPar->num_scanning_sequences-1] = tempInfo1.scan_sequence; } - ++pPar->image_blocks; - // Get the echo times. if( echoNumber != tempInfo1.echo ) { @@ -1800,7 +1396,6 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) pPar->echo_times[echoIndex] = tempInfo1.echo_time; echoNumber = tempInfo1.echo; } - // Get the trigger times if( cardiacPhase != tempInfo1.cardiac ) { @@ -1809,7 +1404,8 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) cardiacPhase = tempInfo1.cardiac; } lineIncrement += pPar->slice; - tempInfo1 = GetImageInformationDefinitionV41(parFile, lineIncrement); + // lineIncrement is set according to version 4.x PAR file. + tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement, this); } } // Slices are not sorted. @@ -1822,7 +1418,8 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) ++pPar->num_scanning_sequences; pPar->scanning_sequences[0] = tempInfo.scan_sequence; ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV41(parFile, lineIncrement); + // lineIncrement is set according to version 4.x PAR file. + tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement, this); while( !tempInfo1.problemreading && tempInfo1.slice ) { int isUnique = 1; @@ -1877,10 +1474,21 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) } } // Now we have sufficient information to parse the rest of the PAR - // file (a very poorly designed file format!). + // file. else { - lineIncrement = 99; + switch( pPar->ResToolsVersion ) + { + case RESEARCH_IMAGE_EXPORT_TOOL_V4: + lineIncrement = 92; + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_1: + lineIncrement = 99; + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: + lineIncrement = 101; + break; + } // OK, I need to determine if there are more image blocks, only // if pPar->num_image_types or pPar->num_scanning_sequences > 1 if( (pPar->num_image_types > 1) || @@ -1888,8 +1496,9 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) { pPar->num_slice_repetitions = pPar->image_blocks; lineIncrement += (pPar->slice*pPar->num_slice_repetitions); - tempInfo1 = GetImageInformationDefinitionV41(parFile, - lineIncrement); + // lineIncrement is set according to version 4.x PAR file. + tempInfo1 = GetImageInformationDefinitionV4(parFile, + lineIncrement, this); while( !tempInfo1.problemreading && tempInfo1.slice ) { // Get the echo times. @@ -1908,14 +1517,14 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) } pPar->image_blocks += pPar->num_slice_repetitions; lineIncrement += (pPar->slice*pPar->num_slice_repetitions); - tempInfo1 = GetImageInformationDefinitionV41(parFile, - lineIncrement); + tempInfo1 = GetImageInformationDefinitionV4(parFile, + lineIncrement, this); } } break; } ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement, this); } } // This is a sanity check. The echoIndex should match @@ -1923,29 +1532,34 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) if( (pPar->echoes-1) != echoIndex ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->echoes-1) != echoIndex" << std::endl; - std::cerr << "pPar->echoes-1 = " << pPar->echoes-1 << std::endl; - std::cerr << "echoIndex = " << echoIndex << std::endl; - return false; + OStringStream message; + message << "ReadPAR: (pPar->echoes-1) != echoIndex, " + << "pPar->echoes-1 = " << pPar->echoes-1 + << " and echoIndex = " << echoIndex; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } - // Another sanity check. The cardiacIndex should match // (pPar->cardiac_phases-1). if( (pPar->cardiac_phases-1) != cardiacIndex ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex" - << std::endl; - std::cerr << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 - << std::endl; - std::cerr << "cardiacIndex = " << cardiacIndex << std::endl; - return false; + OStringStream message; + message << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex, " + << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 + << " and cardiacIndex = " << cardiacIndex; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } } // Only 1 slice, but how many repetitions of that slice? else { - int lineIncrement = 99; + int lineIncrement = 92; int echoIndex = 0; int cardiacIndex = 0; int slice = tempInfo.slice; @@ -1957,8 +1571,17 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) pPar->image_types[0] = tempInfo.image_type_mr; ++pPar->num_scanning_sequences; pPar->scanning_sequences[0] = tempInfo.scan_sequence; + switch( pPar->ResToolsVersion ) + { + case RESEARCH_IMAGE_EXPORT_TOOL_V4_1: + lineIncrement = 99; + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: + lineIncrement = 101; + break; + } ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement, this); while( !tempInfo1.problemreading && tempInfo1.slice ) { if( slice == tempInfo1.slice ) @@ -2032,37 +1655,50 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) break; } ++lineIncrement; - tempInfo1 = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo1 = GetImageInformationDefinitionV4(parFile, lineIncrement, this); } // This is a sanity check. The echoIndex should match // (pPar->echoes-1). if( (pPar->echoes-1) != echoIndex ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->echoes-1) != echoIndex" << std::endl; - std::cerr << "pPar->echoes-1 = " << pPar->echoes-1 << std::endl; - std::cerr << "echoIndex = " << echoIndex << std::endl; - return false; + OStringStream message; + message << "ReadPAR: (pPar->echoes-1) != echoIndex, " + << "pPar->echoes-1 = " << pPar->echoes-1 + << " and echoIndex = " << echoIndex; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } // Another sanity check. The cardiacIndex should match // (pPar->cardiac_phases-1). if( (pPar->cardiac_phases-1) != cardiacIndex ) { pPar->problemreading = 1; - std::cerr << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex" - << std::endl; - std::cerr << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 - << std::endl; - std::cerr << "cardiacIndex = " << cardiacIndex << std::endl; - return false; + OStringStream message; + message << "ReadPAR: (pPar->cardiac_phases-1) != cardiacIndex, " + << "pPar->cardiac_phases-1 = " << pPar->cardiac_phases-1 + << " and cardiacIndex = " << cardiacIndex; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; } } } break; default: - std::cerr << "ReadPAR: Unkown PAR version" << std::endl; - return false; + { + pPar->problemreading = 1; + OStringStream message; + message << "ReadPAR: Unkown PAR version"; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); + throw exception; + } } @@ -2099,93 +1735,84 @@ bool ReadPAR(std::string parFile, struct par_parameter* pPar) // This is a final fixup that will report the total z dimension // as the product of the # of slices and the number of image blocks. pPar->dim[2] *= pPar->image_blocks; - return true; } -PARSliceIndexImageTypeVector GetRECSliceIndexImageTypes( - std::string parFile) +PhilipsPAR::PARSliceIndexImageTypeVector +PhilipsPAR::GetRECSliceIndexImageTypes(std::string parFile) { - PARSliceIndexImageTypeVector recSliceIndexImageTypes; - std::string currentLine = ""; - std::string::size_type index; + PhilipsPAR::PARSliceIndexImageTypeVector recSliceIndexImageTypes; int ResToolsVersion; // Check version of PAR file. - currentLine = GetLineNumber(parFile,8); - //std::cout << currentLine << std::endl; - index = currentLine.find("V3"); - if( index != std::string::npos ) + ResToolsVersion = this->GetPARVersion(parFile); + if( ResToolsVersion == RESEARCH_IMAGE_EXPORT_TOOL_UNKNOWN ) { - ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V3; + return recSliceIndexImageTypes; } - else - { - index = currentLine.find("V4.1"); - if( index != std::string::npos ) - { - ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4_1; - } - else - { - index = currentLine.find("V4"); - if( index != std::string::npos ) - { - ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4; - } - else - { - return recSliceIndexImageTypes; - } - } - } - + switch ( ResToolsVersion ) { case RESEARCH_IMAGE_EXPORT_TOOL_V3: { struct image_info_defV3 tempInfo; - PARSliceIndexImageType sliceAndType; + PhilipsPAR::PARSliceIndexImageType sliceAndType; int lineIncrement = 89; - tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { sliceAndType.first = tempInfo.slice; sliceAndType.second = tempInfo.image_type_mr; recSliceIndexImageTypes.push_back(sliceAndType); ++lineIncrement; - tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement, this); } } break; case RESEARCH_IMAGE_EXPORT_TOOL_V4: { struct image_info_defV4 tempInfo; - PARSliceIndexImageType sliceAndType; + PhilipsPAR::PARSliceIndexImageType sliceAndType; int lineIncrement = 92; - tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { sliceAndType.first = tempInfo.slice; sliceAndType.second = tempInfo.image_type_mr; recSliceIndexImageTypes.push_back(sliceAndType); ++lineIncrement; - tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement, this); } } break; case RESEARCH_IMAGE_EXPORT_TOOL_V4_1: { - struct image_info_defV41 tempInfo; - PARSliceIndexImageType sliceAndType; + struct image_info_defV4 tempInfo; + PhilipsPAR::PARSliceIndexImageType sliceAndType; int lineIncrement = 99; - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); + while( !tempInfo.problemreading && tempInfo.slice ) + { + sliceAndType.first = tempInfo.slice; + sliceAndType.second = tempInfo.image_type_mr; + recSliceIndexImageTypes.push_back(sliceAndType); + ++lineIncrement; + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); + } + } + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: + { + struct image_info_defV4 tempInfo; + PhilipsPAR::PARSliceIndexImageType sliceAndType; + int lineIncrement = 101; + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { sliceAndType.first = tempInfo.slice; sliceAndType.second = tempInfo.image_type_mr; recSliceIndexImageTypes.push_back(sliceAndType); ++lineIncrement; - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); } } break; @@ -2193,90 +1820,82 @@ PARSliceIndexImageTypeVector GetRECSliceIndexImageTypes( return recSliceIndexImageTypes; } -PARSliceIndexScanSequenceVector GetRECSliceIndexScanningSequence( - std::string parFile) +PhilipsPAR::PARSliceIndexScanSequenceVector +PhilipsPAR::GetRECSliceIndexScanningSequence(std::string parFile) { - PARSliceIndexScanSequenceVector recSliceIndexScanSequence; - std::string currentLine = ""; - std::string::size_type index; + PhilipsPAR::PARSliceIndexScanSequenceVector recSliceIndexScanSequence; int ResToolsVersion; // Check version of PAR file. - currentLine = GetLineNumber(parFile,8); - //std::cout << currentLine << std::endl; - index = currentLine.find("V3"); - if( index != std::string::npos ) + ResToolsVersion = this->GetPARVersion(parFile); + if( ResToolsVersion == RESEARCH_IMAGE_EXPORT_TOOL_UNKNOWN ) { - ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V3; - } - else - { - index = currentLine.find("V4.1"); - if( index != std::string::npos ) - { - ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4_1; - } - else - { - index = currentLine.find("V4"); - if( index != std::string::npos ) - { - ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4; - } - else - { - return recSliceIndexScanSequence; - } - } + return recSliceIndexScanSequence; } - + switch ( ResToolsVersion ) { case RESEARCH_IMAGE_EXPORT_TOOL_V3: { struct image_info_defV3 tempInfo; - PARSliceIndexScanSequence sliceAndSequence; + PhilipsPAR::PARSliceIndexScanSequence sliceAndSequence; int lineIncrement = 89; - tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { sliceAndSequence.first = tempInfo.slice; sliceAndSequence.second = tempInfo.scan_sequence; recSliceIndexScanSequence.push_back(sliceAndSequence); ++lineIncrement; - tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement, this); } } break; case RESEARCH_IMAGE_EXPORT_TOOL_V4: { struct image_info_defV4 tempInfo; - PARSliceIndexScanSequence sliceAndSequence; + PhilipsPAR::PARSliceIndexScanSequence sliceAndSequence; int lineIncrement = 92; - tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { sliceAndSequence.first = tempInfo.slice; sliceAndSequence.second = tempInfo.scan_sequence; recSliceIndexScanSequence.push_back(sliceAndSequence); ++lineIncrement; - tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement, this); } } break; case RESEARCH_IMAGE_EXPORT_TOOL_V4_1: { - struct image_info_defV41 tempInfo; - PARSliceIndexScanSequence sliceAndSequence; + struct image_info_defV4 tempInfo; + PhilipsPAR::PARSliceIndexScanSequence sliceAndSequence; int lineIncrement = 99; - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); + while( !tempInfo.problemreading && tempInfo.slice ) + { + sliceAndSequence.first = tempInfo.slice; + sliceAndSequence.second = tempInfo.scan_sequence; + recSliceIndexScanSequence.push_back(sliceAndSequence); + ++lineIncrement; + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); + } + } + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: + { + struct image_info_defV4 tempInfo; + PhilipsPAR::PARSliceIndexScanSequence sliceAndSequence; + int lineIncrement = 101; + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { sliceAndSequence.first = tempInfo.slice; sliceAndSequence.second = tempInfo.scan_sequence; recSliceIndexScanSequence.push_back(sliceAndSequence); ++lineIncrement; - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); } } break; @@ -2284,15 +1903,18 @@ PARSliceIndexScanSequenceVector GetRECSliceIndexScanningSequence( return recSliceIndexScanSequence; } -PARImageTypeScanSequenceVector GetImageTypesScanningSequence( - std::string parFile) +PhilipsPAR::PARImageTypeScanSequenceVector +PhilipsPAR::GetImageTypesScanningSequence(std::string parFile) { - PARImageTypeScanSequenceVector recImageTypesScanSequence; - std::string currentLine = ""; + PhilipsPAR::PARImageTypeScanSequenceVector recImageTypesScanSequence; struct par_parameter parParam; // Read the PAR file. - if( !ReadPAR(parFile, &parParam) ) + try + { + this->ReadPAR(parFile, &parParam); + } + catch(ExceptionObject &) { return recImageTypesScanSequence; } @@ -2305,10 +1927,10 @@ PARImageTypeScanSequenceVector GetImageTypesScanningSequence( for(int scanIndex=0; scanIndex<parParam.num_scanning_sequences; scanIndex++) { - PARImageTypeScanSequence imageTypeAndSequence; + PhilipsPAR::PARImageTypeScanSequence imageTypeAndSequence; int lineIncrement = 89; int imageType[PAR_DEFAULT_IMAGE_TYPES_SIZE] = {-1,-1,-1,-1,-1,-1,-1,-1}; - tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { if((*(imageType+tempInfo.image_type_mr) < 0) && @@ -2317,7 +1939,7 @@ PARImageTypeScanSequenceVector GetImageTypesScanningSequence( *(imageType+tempInfo.image_type_mr) = tempInfo.image_type_mr; } ++lineIncrement; - tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement, this); } for(int imageTypeIndex=0; imageTypeIndex<PAR_DEFAULT_IMAGE_TYPES_SIZE; imageTypeIndex++) @@ -2339,10 +1961,10 @@ PARImageTypeScanSequenceVector GetImageTypesScanningSequence( for(int scanIndex=0; scanIndex<parParam.num_scanning_sequences; scanIndex++) { - PARImageTypeScanSequence imageTypeAndSequence; + PhilipsPAR::PARImageTypeScanSequence imageTypeAndSequence; int lineIncrement = 92; int imageType[PAR_DEFAULT_IMAGE_TYPES_SIZE] = {-1,-1,-1,-1,-1,-1,-1,-1}; - tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { if((*(imageType+tempInfo.image_type_mr) < 0) && @@ -2351,7 +1973,7 @@ PARImageTypeScanSequenceVector GetImageTypesScanningSequence( *(imageType+tempInfo.image_type_mr) = tempInfo.image_type_mr; } ++lineIncrement; - tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement, this); } for(int imageTypeIndex=0; imageTypeIndex<PAR_DEFAULT_IMAGE_TYPES_SIZE; imageTypeIndex++) @@ -2369,14 +1991,48 @@ PARImageTypeScanSequenceVector GetImageTypesScanningSequence( break; case RESEARCH_IMAGE_EXPORT_TOOL_V4_1: { - struct image_info_defV41 tempInfo; + struct image_info_defV4 tempInfo; for(int scanIndex=0; scanIndex<parParam.num_scanning_sequences; scanIndex++) { - PARImageTypeScanSequence imageTypeAndSequence; + PhilipsPAR::PARImageTypeScanSequence imageTypeAndSequence; int lineIncrement = 99; int imageType[PAR_DEFAULT_IMAGE_TYPES_SIZE] = {-1,-1,-1,-1,-1,-1,-1,-1}; - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); + while( !tempInfo.problemreading && tempInfo.slice ) + { + if((*(imageType+tempInfo.image_type_mr) < 0) && + (tempInfo.scan_sequence == *(parParam.scanning_sequences+scanIndex))) + { + *(imageType+tempInfo.image_type_mr) = tempInfo.image_type_mr; + } + ++lineIncrement; + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); + } + for(int imageTypeIndex=0; imageTypeIndex<PAR_DEFAULT_IMAGE_TYPES_SIZE; + imageTypeIndex++) + { + if( *(imageType+imageTypeIndex) >= 0 ) + { + imageTypeAndSequence.first = imageTypeIndex; + imageTypeAndSequence.second = + *(parParam.scanning_sequences+scanIndex); + recImageTypesScanSequence.push_back(imageTypeAndSequence); + } + } + } + } + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: + { + struct image_info_defV4 tempInfo; + for(int scanIndex=0; scanIndex<parParam.num_scanning_sequences; + scanIndex++) + { + PhilipsPAR::PARImageTypeScanSequence imageTypeAndSequence; + int lineIncrement = 101; + int imageType[PAR_DEFAULT_IMAGE_TYPES_SIZE] = {-1,-1,-1,-1,-1,-1,-1,-1}; + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { if((*(imageType+tempInfo.image_type_mr) < 0) && @@ -2385,7 +2041,7 @@ PARImageTypeScanSequenceVector GetImageTypesScanningSequence( *(imageType+tempInfo.image_type_mr) = tempInfo.image_type_mr; } ++lineIncrement; - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); } for(int imageTypeIndex=0; imageTypeIndex<PAR_DEFAULT_IMAGE_TYPES_SIZE; imageTypeIndex++) @@ -2405,58 +2061,35 @@ PARImageTypeScanSequenceVector GetImageTypesScanningSequence( return recImageTypesScanSequence; } -bool GetRECRescaleValues(std::string parFile, - PARRescaleValuesContainer *rescaleValues, int scan_sequence) +bool PhilipsPAR::GetRECRescaleValues(std::string parFile, + PhilipsPAR::PARRescaleValuesContainer *rescaleValues, int scan_sequence) { - std::string currentLine = ""; - std::string::size_type index; int ResToolsVersion; rescaleValues->clear(); // Must match size of image_types rescaleValues->resize(PAR_DEFAULT_IMAGE_TYPES_SIZE); - PARRescaleValues zero(0.0); + PhilipsPAR::PARRescaleValues zero(0.0); for(unsigned int zeroIndex=0; zeroIndex<rescaleValues->size(); zeroIndex++) { (*rescaleValues)[zeroIndex] = zero; // Zero out everything } // Check version of PAR file. - currentLine = GetLineNumber(parFile,8); - index = currentLine.find("V3"); - if( index != std::string::npos ) - { - ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V3; - } - else + ResToolsVersion = this->GetPARVersion(parFile); + if( ResToolsVersion == RESEARCH_IMAGE_EXPORT_TOOL_UNKNOWN ) { - index = currentLine.find("V4.1"); - if( index != std::string::npos ) - { - ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4_1; - } - else - { - index = currentLine.find("V4"); - if( index != std::string::npos ) - { - ResToolsVersion = RESEARCH_IMAGE_EXPORT_TOOL_V4; - } - else - { - return false; - } - } + return false; } - + switch ( ResToolsVersion ) { case RESEARCH_IMAGE_EXPORT_TOOL_V3: { struct image_info_defV3 tempInfo; - PARRescaleValues rescale; + PhilipsPAR::PARRescaleValues rescale; int imageType[PAR_DEFAULT_IMAGE_TYPES_SIZE] = {-1,-1,-1,-1,-1,-1,-1,-1}; int lineIncrement = 89; - tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { if( (*(imageType+tempInfo.image_type_mr) < 0) && @@ -2469,17 +2102,17 @@ bool GetRECRescaleValues(std::string parFile, (*rescaleValues)[tempInfo.image_type_mr] = rescale; } ++lineIncrement; - tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV3(parFile, lineIncrement, this); } } break; case RESEARCH_IMAGE_EXPORT_TOOL_V4: { struct image_info_defV4 tempInfo; - PARRescaleValues rescale; + PhilipsPAR::PARRescaleValues rescale; int imageType[PAR_DEFAULT_IMAGE_TYPES_SIZE] = {-1,-1,-1,-1,-1,-1,-1,-1}; int lineIncrement = 92; - tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { if( (*(imageType+tempInfo.image_type_mr) < 0) && @@ -2492,17 +2125,40 @@ bool GetRECRescaleValues(std::string parFile, (*rescaleValues)[tempInfo.image_type_mr] = rescale; } ++lineIncrement; - tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV4(parFile, lineIncrement, this); } } break; case RESEARCH_IMAGE_EXPORT_TOOL_V4_1: { - struct image_info_defV41 tempInfo; - PARRescaleValues rescale; + struct image_info_defV4 tempInfo; + PhilipsPAR::PARRescaleValues rescale; int imageType[PAR_DEFAULT_IMAGE_TYPES_SIZE] = {-1,-1,-1,-1,-1,-1,-1,-1}; int lineIncrement = 99; - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); + while( !tempInfo.problemreading && tempInfo.slice ) + { + if( (*(imageType+tempInfo.image_type_mr) < 0) && + (tempInfo.scan_sequence == scan_sequence) ) + { + *(imageType+tempInfo.image_type_mr) = tempInfo.image_type_mr; + rescale[0] = tempInfo.rescale_int; + rescale[1] = tempInfo.rescale_slope; + rescale[2] = tempInfo.scale_slope; + (*rescaleValues)[tempInfo.image_type_mr] = rescale; + } + ++lineIncrement; + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); + } + } + break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: + { + struct image_info_defV4 tempInfo; + PhilipsPAR::PARRescaleValues rescale; + int imageType[PAR_DEFAULT_IMAGE_TYPES_SIZE] = {-1,-1,-1,-1,-1,-1,-1,-1}; + int lineIncrement = 101; + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice ) { if( (*(imageType+tempInfo.image_type_mr) < 0) && @@ -2515,7 +2171,7 @@ bool GetRECRescaleValues(std::string parFile, (*rescaleValues)[tempInfo.image_type_mr] = rescale; } ++lineIncrement; - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); } } break; @@ -2523,27 +2179,35 @@ bool GetRECRescaleValues(std::string parFile, return true; } -bool GetDiffusionGradientOrientationAndBValues(std::string parFile, - PARDiffusionValuesContainer *gradientValues, PARBValuesContainer *bValues) +bool PhilipsPAR::GetDiffusionGradientOrientationAndBValues(std::string parFile, + PhilipsPAR::PARDiffusionValuesContainer *gradientValues, + PhilipsPAR::PARBValuesContainer *bValues) { - std::string currentLine = ""; - std::string::size_type index; int gradientDirectionCount = 0; gradientValues->resize(0); // Reset to zero size. bValues->resize(0); struct par_parameter tempPar; + int ResToolsVersion; // Check version of PAR file. - // Diffusion gradients are only stored in version 4.1 PAR files. - currentLine = GetLineNumber(parFile,8); - index = currentLine.find("V4.1"); - if( index != std::string::npos ) + // Diffusion gradients are only stored in PAR version >= 4.1 + ResToolsVersion = this->GetPARVersion(parFile); + if( ResToolsVersion >= RESEARCH_IMAGE_EXPORT_TOOL_V4_1 ) { - struct image_info_defV41 tempInfo; + struct image_info_defV4 tempInfo; int gradientOrientationNumber = -1; int lineIncrement = 99; + + if( ResToolsVersion == RESEARCH_IMAGE_EXPORT_TOOL_V4_2 ) + { + lineIncrement = 101; + } - if( !ReadPAR(parFile, &tempPar) ) + try + { + this->ReadPAR(parFile, &tempPar); + } + catch(ExceptionObject &) { return false; } @@ -2556,14 +2220,16 @@ bool GetDiffusionGradientOrientationAndBValues(std::string parFile, return true; } - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + // Can use either version 4.1 or 4.2 GetImageInformationDefinition + // function. + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); while( !tempInfo.problemreading && tempInfo.slice && (gradientDirectionCount < tempPar.max_num_grad_orient) ) { int tempGradientOrientationNumber = tempInfo.gradient_orientation_number; if( gradientOrientationNumber != tempGradientOrientationNumber ) { - PARDiffusionValues direction; + PhilipsPAR::PARDiffusionValues direction; direction[0] = tempInfo.diffusion_ap; direction[1] = tempInfo.diffusion_fh; direction[2] = tempInfo.diffusion_rl; @@ -2573,10 +2239,66 @@ bool GetDiffusionGradientOrientationAndBValues(std::string parFile, gradientOrientationNumber = tempGradientOrientationNumber; } ++lineIncrement; - tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement); + tempInfo = GetImageInformationDefinitionV41(parFile, lineIncrement, this); + } + } + return true; +} + +bool PhilipsPAR::GetLabelTypesASL(std::string parFile, + PhilipsPAR::PARLabelTypesASLContainer *labelTypes) +{ + int aslLabelCount = 0; + labelTypes->resize(0); // Reset to zero size. + struct par_parameter tempPar; + int ResToolsVersion; + + // Check version of PAR file. + // ASL labels are only stored in PAR version >= 4.2 + ResToolsVersion = this->GetPARVersion(parFile); + if( ResToolsVersion >= RESEARCH_IMAGE_EXPORT_TOOL_V4_2 ) + { + struct image_info_defV4 tempInfo; + int aslLabelNumber = -1; + int lineIncrement = 101; + + try + { + this->ReadPAR(parFile, &tempPar); + } + catch(ExceptionObject &) + { + return false; + } + + labelTypes->resize(tempPar.num_label_types); + + if( tempPar.num_label_types <= 0 ) + { + return true; + } + + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); + while( !tempInfo.problemreading && tempInfo.slice + && (aslLabelCount < tempPar.num_label_types) ) + { + int tempASLLabelNumber = tempInfo.labelTypeASL; + if( aslLabelNumber != tempASLLabelNumber ) + { + (*labelTypes)[aslLabelCount] = tempASLLabelNumber; + ++aslLabelCount; + aslLabelNumber = tempASLLabelNumber; + } + ++lineIncrement; + tempInfo = GetImageInformationDefinitionV42(parFile, lineIncrement, this); } } return true; } +void PhilipsPAR::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); +} + } // end namespace itk diff --git a/Utilities/ITK/Code/Review/itkPhilipsPAR.h b/Utilities/ITK/Code/Review/itkPhilipsPAR.h index 89953e61c2..967a63b109 100644 --- a/Utilities/ITK/Code/Review/itkPhilipsPAR.h +++ b/Utilities/ITK/Code/Review/itkPhilipsPAR.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPhilipsPAR.h,v $ Language: C++ - Date: $Date: 2008-06-23 22:04:35 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-29 12:17:28 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,25 +36,28 @@ #include <stdio.h> #include <stdlib.h> #include <string> +#include "itkLightProcessObject.h" #include "itkVectorContainer.h" #include "vnl/vnl_vector_fixed.h" -#define RESEARCH_IMAGE_EXPORT_TOOL_V3 3 -#define RESEARCH_IMAGE_EXPORT_TOOL_V4 4 -#define RESEARCH_IMAGE_EXPORT_TOOL_V4_1 41 - -#define PAR_DEFAULT_STRING_LENGTH 32 -#define PAR_DEFAULT_TRIGGER_TIMES_SIZE 128 -#define PAR_DEFAULT_ECHO_TIMES_SIZE 128 -#define PAR_DEFAULT_REP_TIMES_SIZE 128 -#define PAR_DEFAULT_IMAGE_TYPES_SIZE 8 -#define PAR_DEFAULT_SCAN_SEQUENCE_SIZE 8 -#define PAR_RESCALE_VALUES_SIZE 3 -#define PAR_DIFFUSION_VALUES_SIZE 3 - -#define PAR_SLICE_ORIENTATION_TRANSVERSAL 1 -#define PAR_SLICE_ORIENTATION_SAGITTAL 2 -#define PAR_SLICE_ORIENTATION_CORONAL 3 +#define RESEARCH_IMAGE_EXPORT_TOOL_V3 30 +#define RESEARCH_IMAGE_EXPORT_TOOL_V4 40 +#define RESEARCH_IMAGE_EXPORT_TOOL_V4_1 41 +#define RESEARCH_IMAGE_EXPORT_TOOL_V4_2 42 +#define RESEARCH_IMAGE_EXPORT_TOOL_UNKNOWN -1 + +#define PAR_DEFAULT_STRING_LENGTH 32 +#define PAR_DEFAULT_TRIGGER_TIMES_SIZE 128 +#define PAR_DEFAULT_ECHO_TIMES_SIZE 128 +#define PAR_DEFAULT_REP_TIMES_SIZE 128 +#define PAR_DEFAULT_IMAGE_TYPES_SIZE 8 +#define PAR_DEFAULT_SCAN_SEQUENCE_SIZE 8 +#define PAR_RESCALE_VALUES_SIZE 3 +#define PAR_DIFFUSION_VALUES_SIZE 3 + +#define PAR_SLICE_ORIENTATION_TRANSVERSAL 1 +#define PAR_SLICE_ORIENTATION_SAGITTAL 2 +#define PAR_SLICE_ORIENTATION_CORONAL 3 namespace itk { @@ -65,7 +68,7 @@ namespace itk struct par_parameter //par_parameter { int problemreading; // Marked 1 if problem occurred reading in PAR file - int ResToolsVersion; // V3, V4, or V4.1 PAR/REC version + int ResToolsVersion; // V3, V4, V4.1, or V4.2 PAR/REC version char patient_name[PAR_DEFAULT_STRING_LENGTH]; // Patient name char exam_name[PAR_DEFAULT_STRING_LENGTH]; // Examination name char protocol_name[PAR_DEFAULT_STRING_LENGTH]; // Protocol name @@ -116,9 +119,10 @@ struct par_parameter //par_parameter int dynamic_scan; // Dynamic scan <0=no 1=yes> ? int diffusion; // Diffusion <0=no 1=yes> ? float diff_echo; // Diffusion echo time [msec] + float inversion_delay; // Inversion delay [msec] int max_num_diff_vals; // Max. number of diffusion values int max_num_grad_orient; // Max. number of gradient orients - float inversion_delay; // Inversion delay [msec] + int num_label_types; // Number of label types <0=no ASL> float vox[3]; // pixel spacing (x,y) (in mm) int slicessorted; // 1-slices sorted, 0-slices not sorted int image_blocks; // The total number of image blocks stored in the REC file @@ -137,58 +141,112 @@ struct par_parameter //par_parameter }; -// Reads the PAR file parameters in "parFile" and stores the PAR parameters in -// pPar. -// Returns false if an error is encountered during reading, otherwise true is -// returned. -ITK_EXPORT bool ReadPAR(std::string parFile, struct par_parameter* pPar); - -// Returns a vector of paired values, the first contains the slice index and the -// second is the image type for the PAR file "parFile". -typedef std::pair< int, int > PARSliceIndexImageType; -typedef std::vector< PARSliceIndexImageType > PARSliceIndexImageTypeVector; -ITK_EXPORT PARSliceIndexImageTypeVector GetRECSliceIndexImageTypes( - std::string parFile); - -// Returns a vector of paired values, the first contains the slice index and the -// second is the scan sequence for the PAR file "parFile". -typedef std::pair< int, int > PARSliceIndexScanSequence; -typedef std::vector< PARSliceIndexScanSequence > PARSliceIndexScanSequenceVector; -ITK_EXPORT PARSliceIndexScanSequenceVector GetRECSliceIndexScanningSequence( - std::string parFile); - -// Returns a vector of paired values, the first contains the image type and the -// second is the scan sequence for that image type for the PAR file "parFile". -typedef std::pair< int, int > PARImageTypeScanSequence; -typedef std::vector< PARImageTypeScanSequence > PARImageTypeScanSequenceVector; -ITK_EXPORT PARImageTypeScanSequenceVector GetImageTypesScanningSequence( - std::string parFile); - -// Stores rescale values in the VectorContainer "rescaleValues" for each image -// type of the specified scan sequence number "scan_sequence" (from -// scanning_sequences) for the PAR file "parFile". -// Returns false if an error is encountered during reading, otherwise true is -// returned. -typedef vnl_vector_fixed< double, PAR_RESCALE_VALUES_SIZE > -PARRescaleValues; -typedef VectorContainer< unsigned int, PARRescaleValues > -PARRescaleValuesContainer; -ITK_EXPORT bool GetRECRescaleValues(std::string parFile, - PARRescaleValuesContainer *rescaleValues, int scan_sequence); - -// Stores the diffusion gradient values in the VectorContainer "gradientValues" -// and the diffusion b values in the VectorContainer "bValues" for each gradient -// direction in the PAR file "parFile". -// Returns false if an error is encountered during reading, otherwise true is -// returned. -typedef vnl_vector_fixed< double, PAR_DIFFUSION_VALUES_SIZE > -PARDiffusionValues; -typedef VectorContainer< unsigned int, PARDiffusionValues > -PARDiffusionValuesContainer; -typedef VectorContainer< unsigned int, double > -PARBValuesContainer; -ITK_EXPORT bool GetDiffusionGradientOrientationAndBValues(std::string parFile, - PARDiffusionValuesContainer *gradientValues, PARBValuesContainer *bValues); +/** \class PhilipsPAR + * \brief Class for reading parameters from a Philips PAR file. + * + * \sa PhilipsRECImageIO + * + * \ingroup IOFilters + * + */ +class ITK_EXPORT PhilipsPAR : public LightProcessObject +{ +public: + /** Standard class typedefs. */ + typedef PhilipsPAR Self; + typedef LightProcessObject Superclass; + typedef SmartPointer<Self> Pointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(PhilipsPAR, Superclass); + + // Reads the PAR file parameters in "parFile" and stores the PAR parameters in + // pPar. + // Returns false if an error is encountered during reading, otherwise true is + // returned. + void ReadPAR(std::string parFile, struct par_parameter* pPar); + + // Returns a vector of paired values, the first contains the slice index and the + // second is the image type for the PAR file "parFile". + typedef std::pair< int, int > PARSliceIndexImageType; + typedef std::vector< PARSliceIndexImageType > PARSliceIndexImageTypeVector; + PARSliceIndexImageTypeVector GetRECSliceIndexImageTypes( + std::string parFile); + + // Returns a vector of paired values, the first contains the slice index and the + // second is the scan sequence for the PAR file "parFile". + typedef std::pair< int, int > PARSliceIndexScanSequence; + typedef std::vector< PARSliceIndexScanSequence > PARSliceIndexScanSequenceVector; + PARSliceIndexScanSequenceVector GetRECSliceIndexScanningSequence( + std::string parFile); + + // Returns a vector of paired values, the first contains the image type and the + // second is the scan sequence for that image type for the PAR file "parFile". + typedef std::pair< int, int > PARImageTypeScanSequence; + typedef std::vector< PARImageTypeScanSequence > PARImageTypeScanSequenceVector; + PARImageTypeScanSequenceVector GetImageTypesScanningSequence( + std::string parFile); + + // Stores rescale values in the VectorContainer "rescaleValues" for each image + // type of the specified scan sequence number "scan_sequence" (from + // scanning_sequences) for the PAR file "parFile". + // Returns false if an error is encountered during reading, otherwise true is + // returned. + typedef vnl_vector_fixed< double, PAR_RESCALE_VALUES_SIZE > + PARRescaleValues; + typedef VectorContainer< unsigned int, PARRescaleValues > + PARRescaleValuesContainer; + bool GetRECRescaleValues(std::string parFile, + PARRescaleValuesContainer *rescaleValues, int scan_sequence); + + // Stores the diffusion gradient values in the VectorContainer "gradientValues" + // and the diffusion b values in the VectorContainer "bValues" for each gradient + // direction in the PAR file "parFile". This function is applicable only for PAR + // versions > 4.1 + // Returns false if an error is encountered during reading, otherwise true is + // returned. + typedef vnl_vector_fixed< double, PAR_DIFFUSION_VALUES_SIZE > + PARDiffusionValues; + typedef VectorContainer< unsigned int, PARDiffusionValues > + PARDiffusionValuesContainer; + typedef VectorContainer< unsigned int, double > + PARBValuesContainer; + bool GetDiffusionGradientOrientationAndBValues(std::string parFile, + PARDiffusionValuesContainer *gradientValues, PARBValuesContainer *bValues); + + // Returns a vector of ASL label types for the PAR file "parFile". + typedef VectorContainer< unsigned int, int > PARLabelTypesASLContainer; + bool GetLabelTypesASL(std::string parFile, + PARLabelTypesASLContainer *labelTypes); + + // Read a line number within the PAR file. + std::string GetLineNumber(std::string file, int lineNum); + +protected: + PhilipsPAR(); + ~PhilipsPAR(); + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + PhilipsPAR(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Function used internally to get PAR version. */ + int GetPARVersion(std::string parFile); + + /** Function used internally to get info string at top of PAR. */ + std::string GetGeneralInfoString(std::string file, int lineNum); + + /** Filename to read. */ + std::string m_FileName; + + /** Vector of strings for storing each line of PAR file. */ + std::vector<std::string> m_PARFileLines; + +}; } // end namespace itk diff --git a/Utilities/ITK/Code/Review/itkPhilipsRECImageIO.cxx b/Utilities/ITK/Code/Review/itkPhilipsRECImageIO.cxx index d51adc69d4..04194a4acc 100644 --- a/Utilities/ITK/Code/Review/itkPhilipsRECImageIO.cxx +++ b/Utilities/ITK/Code/Review/itkPhilipsRECImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPhilipsRECImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-02-25 03:20:41 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-29 12:20:40 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -93,6 +93,8 @@ const char *const PAR_NumberOfScanningSequences = const char *const PAR_ScanningSequences = "PAR_ScanningSequences"; const char *const PAR_ScanningSequenceImageTypeRescaleValues = "PAR_ScanningSequenceImageTypeRescaleValues"; +const char *const PAR_NumberOfASLLabelTypes = "PAR_NumberOfASLLabelTypes"; +const char *const PAR_ASLLabelTypes = "PAR_ASLLabelTypes"; static std::string GetExtension( const std::string& filename ) @@ -104,11 +106,24 @@ GetExtension( const std::string& filename ) if(fileExt == std::string(".gz")) { fileExt = itksys::SystemTools::GetFilenameLastExtension( - itksys::SystemTools::GetFilenameLastExtension(filename)); + itksys::SystemTools::GetFilenameWithoutLastExtension(filename)); fileExt += ".gz"; } // Check that a valid extension was found - if(fileExt != ".REC.gz" && fileExt != ".REC" && fileExt != ".PAR") + // Will check for either all caps or all lower-case. + // By default the Philips Pride Workstation outputs + // the filenames as all caps, but a user may change the + // filenames to lowercase. This will allow one or the + // other. Mixed caps/lower-case will always (with the + // exception of the lower-case gz on the end which is + // always assumed to be lower-case) fail on an OS with + // a case sensitive file system. + if(fileExt != ".REC.gz" + && fileExt != ".REC" + && fileExt != ".PAR" + && fileExt != ".rec.gz" + && fileExt != ".rec" + && fileExt != ".par") { return ( "" ); } @@ -138,8 +153,19 @@ GetRootName( const std::string& filename ) static std::string GetHeaderFileName( const std::string & filename ) { - std::string ImageFileName = GetRootName(filename); - ImageFileName += ".PAR"; + std::string ImageFileName(filename); + const std::string fileExt = GetExtension(filename); + // Accomodate either all caps or all lower-case filenames. + if( (fileExt == ".REC") || (fileExt == ".REC.gz") ) + { + ImageFileName = GetRootName(filename); + ImageFileName += ".PAR"; + } + else if( (fileExt == ".rec") || (fileExt == ".rec.gz") ) + { + ImageFileName = GetRootName(filename); + ImageFileName += ".par"; + } return( ImageFileName ); } @@ -154,6 +180,11 @@ static std::string GetImageFileName( const std::string& filename ) ImageFileName = GetRootName(filename); ImageFileName += ".REC"; } + else if(fileExt == ".par") + { + ImageFileName = GetRootName(filename); + ImageFileName += ".rec"; + } return( ImageFileName ); } @@ -162,8 +193,8 @@ static std::string GetImageFileName( const std::string& filename ) // scanning sequence (randomly ordered in the REC). int PhilipsRECImageIOGetImageTypeOffset(int imageType, int scanSequence, int volumeIndex, int slice, int numSlices, struct par_parameter parParam, - PARSliceIndexImageTypeVector sliceImageTypesIndex, - PARSliceIndexScanSequenceVector sliceScanSequenceIndex) + PhilipsPAR::PARSliceIndexImageTypeVector sliceImageTypesIndex, + PhilipsPAR::PARSliceIndexScanSequenceVector sliceScanSequenceIndex) { int index = volumeIndex*parParam.num_slice_repetitions*numSlices + slice*parParam.num_slice_repetitions; @@ -184,9 +215,9 @@ int PhilipsRECImageIOGetImageTypeOffset(int imageType, int scanSequence, void PhilipsRECImageIOSetupSliceIndex( PhilipsRECImageIO::SliceIndexType *indexMatrix, int sortBlock, struct par_parameter parParam, - PARImageTypeScanSequenceVector imageTypesScanSequenceIndex, - PARSliceIndexImageTypeVector sliceImageTypesIndex, - PARSliceIndexScanSequenceVector sliceScanSequenceIndex) + PhilipsPAR::PARImageTypeScanSequenceVector imageTypesScanSequenceIndex, + PhilipsPAR::PARSliceIndexImageTypeVector sliceImageTypesIndex, + PhilipsPAR::PARSliceIndexScanSequenceVector sliceScanSequenceIndex) { int index = 0; int actualSlices = parParam.slice; @@ -195,27 +226,39 @@ void PhilipsRECImageIOSetupSliceIndex( if(indexMatrix->size() != (PhilipsRECImageIO::SliceIndexType::size_type)parParam.dim[2]) { - ExceptionObject exception(__FILE__, __LINE__); - std::string message="PhilipsRECImageIOSetupSliceIndex: indexMatrix->size() !" - "= parParam.dim[2]\n"; - exception.SetDescription(message.c_str()); + OStringStream message; + message << "indexMatrix->size(): " + << indexMatrix->size() + << " != parParam.dim[2]: " + << parParam.dim[2]; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if(parParam.dim[2] != (parParam.slice*parParam.image_blocks)) { - ExceptionObject exception(__FILE__, __LINE__); - std::string message="PhilipsRECImageIOSetupSliceIndex: parParam.dim[2] != " - "(parParam.slice*parParam.image_blocks)\n"; - exception.SetDescription(message.c_str()); + OStringStream message; + message << "parParam.dim[2]: " + << parParam.dim[2] + << " != (parParam.slice*parParam.image_blocks): " + << parParam.slice * parParam.image_blocks; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } if(imageTypesScanSequenceIndex.size() != (PhilipsRECImageIO::SliceIndexType::size_type)parParam.num_slice_repetitions) { - ExceptionObject exception(__FILE__, __LINE__); - std::string message="PhilipsRECImageIOSetupSliceIndex: " - "imageTypesScanSequenceIndex.size() != parParam.num_slice_repetitions\n"; - exception.SetDescription(message.c_str()); + OStringStream message; + message << "imageTypesScanSequenceIndex.size(): " + << imageTypesScanSequenceIndex.size() + << " != parParam.num_slice_repetitions " + << parParam.num_slice_repetitions; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } @@ -316,8 +359,9 @@ PhilipsRECImageIO::SwapBytesIfNecessary( void* buffer, ((double*)buffer, numberOfPixels ); break; default: - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Pixel Type Unknown"); + ExceptionObject exception(__FILE__, __LINE__, + "Component Type Unknown", + ITK_LOCATION); throw exception; } } @@ -366,8 +410,9 @@ PhilipsRECImageIO::SwapBytesIfNecessary( void* buffer, ((double *)buffer, numberOfPixels ); break; default: - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Pixel Type Unknown"); + ExceptionObject exception(__FILE__, __LINE__, + "Component Type Unknown", + ITK_LOCATION); throw exception; } } @@ -425,12 +470,15 @@ void PhilipsRECImageIO::Read(void* buffer) } char * const p = static_cast<char *>(buffer); - //3 cases to handle + //6 cases to handle //1: given .PAR and image is .REC //2: given .REC //3: given .REC.gz + //4: given .par and image is .rec + //5: given .rec + //6: given .rec.gz - /* Returns proper name for cases 1,2,3 */ + /* Returns proper name for cases 1,2,3,4,5,6 */ std::string ImageFileName = GetImageFileName( this->m_FileName ); //NOTE: gzFile operations act just like FILE * operations when the files // are not in gzip fromat. @@ -441,14 +489,14 @@ void PhilipsRECImageIO::Read(void* buffer) gzFile file_p = ::gzopen( ImageFileName.c_str(), "rb" ); if( file_p == NULL ) { - ExceptionObject exception(__FILE__, __LINE__); - std::string message="Philips REC Data File can not be read: " - "The following files were attempted:\n "; - message += GetImageFileName( this->m_FileName ); - message += '\n'; - message += ImageFileName; - message += '\n'; - exception.SetDescription(message.c_str()); + OStringStream message; + message << "Philips REC Data File can not be opened. " + << "The following files were attempted:" << std::endl + << GetImageFileName( this->m_FileName ) << std::endl + << ImageFileName; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } @@ -461,14 +509,14 @@ void PhilipsRECImageIO::Read(void* buffer) int realIndex = this->GetSliceIndex((int)slice); if( realIndex < 0 ) { - ExceptionObject exception(__FILE__, __LINE__); - std::string message="Philips REC Data File can not be read: " - "The following files were attempted:\n "; - message += GetImageFileName( this->m_FileName ); - message += '\n'; - message += ImageFileName; - message += '\n'; - exception.SetDescription(message.c_str()); + OStringStream message; + message << "Philips REC Data File can not be read. " + << "The following files were attempted:" << std::endl + << GetImageFileName( this->m_FileName ) << std::endl + << ImageFileName; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; } ::gzseek( file_p, (unsigned int)realIndex*imageSliceSizeInBytes, SEEK_SET ); @@ -485,8 +533,11 @@ bool PhilipsRECImageIO::CanReadFile( const char* FileNameToRead ) // we check that the correct extension is given by the user std::string filenameext = GetExtension(filename); if( filenameext != std::string(".PAR") - && filenameext != std::string(".REC") - && filenameext != std::string(".REC.gz") ) + && filenameext != std::string(".REC") + && filenameext != std::string(".REC.gz") + && filenameext != std::string(".par") + && filenameext != std::string(".rec") + && filenameext != std::string(".rec.gz")) { return false; } @@ -498,12 +549,10 @@ bool PhilipsRECImageIO::CanReadFile( const char* FileNameToRead ) // Zero out par_parameter. memset(&par,0, sizeof(struct par_parameter)); - if( !ReadPAR(HeaderFileName, &par) ) - { - return false; - } - else + PhilipsPAR::Pointer philipsPAR = PhilipsPAR::New(); + try { + philipsPAR->ReadPAR(HeaderFileName, &par); // Check to see if there were any problems reading // the par file. if( par.problemreading ) @@ -511,7 +560,11 @@ bool PhilipsRECImageIO::CanReadFile( const char* FileNameToRead ) return false; } } - + catch(ExceptionObject &) + { + return false; + } + return true; } @@ -519,18 +572,25 @@ void PhilipsRECImageIO::ReadImageInformation() { const std::string HeaderFileName = GetHeaderFileName( this->m_FileName ); struct par_parameter par; + // Zero out par_parameter. memset(&par,0, sizeof(struct par_parameter)); - if( !ReadPAR( HeaderFileName, &par) ) + + // Read PAR file. + PhilipsPAR::Pointer philipsPAR = PhilipsPAR::New(); + try { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Problem reading PAR file"); - throw exception; + philipsPAR->ReadPAR( HeaderFileName, &par); } - else if( par.problemreading ) + catch(itk::ExceptionObject &err) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Problem reading PAR file"); + throw err; + } + if( par.problemreading ) + { + ExceptionObject exception(__FILE__, __LINE__, + "Problem reading PAR file", + ITK_LOCATION); throw exception; } @@ -539,13 +599,27 @@ void PhilipsRECImageIO::ReadImageInformation() = GradientBvalueContainerType::New(); GradientDirectionContainerType::Pointer diffusionGradientOrientationVector = GradientDirectionContainerType::New(); - if( !GetDiffusionGradientOrientationAndBValues(HeaderFileName, + if( !philipsPAR->GetDiffusionGradientOrientationAndBValues(HeaderFileName, diffusionGradientOrientationVector, diffusionBvalueVector) ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Problem reading PAR file"); + ExceptionObject exception(__FILE__, __LINE__, + "Problem reading diffusion gradients and b values from PAR file", + ITK_LOCATION); + throw exception; + } + + // Get ASL label types. + LabelTypesASLContainerType::Pointer labelTypesASLVector = + LabelTypesASLContainerType::New(); + if( !philipsPAR->GetLabelTypesASL(HeaderFileName, labelTypesASLVector) ) + { + ExceptionObject exception(__FILE__, __LINE__, + "Problem reading ASL label types from PAR file", + ITK_LOCATION); throw exception; } + + // Get rescale values associated with each scanning sequence. ScanningSequenceImageTypeRescaleValuesContainerType::Pointer scanningSequenceImageTypeRescaleVector = ScanningSequenceImageTypeRescaleValuesContainerType::New(); @@ -556,11 +630,12 @@ void PhilipsRECImageIO::ReadImageInformation() { ImageTypeRescaleValuesContainerType::Pointer imageTypeRescaleValuesVector = ImageTypeRescaleValuesContainerType::New(); - if( !GetRECRescaleValues(HeaderFileName,imageTypeRescaleValuesVector, + if( !philipsPAR->GetRECRescaleValues(HeaderFileName,imageTypeRescaleValuesVector, par.scanning_sequences[scanIndex]) ) { - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Problem reading PAR file"); + ExceptionObject exception(__FILE__, __LINE__, + "Problem reading recale values for each scanning sequence from PAR file", + ITK_LOCATION); throw exception; } (*scanningSequenceImageTypeRescaleVector)[scanIndex] = @@ -570,12 +645,12 @@ void PhilipsRECImageIO::ReadImageInformation() // Setup the slice index matrix. this->m_SliceIndex->clear(); this->m_SliceIndex->resize(par.dim[2]); - PARSliceIndexImageTypeVector sliceImageTypesIndexes = - GetRECSliceIndexImageTypes(HeaderFileName); - PARSliceIndexScanSequenceVector sliceScanSequencesIndexes = - GetRECSliceIndexScanningSequence(HeaderFileName); - PARImageTypeScanSequenceVector imageTypesScanSequencesIndexes = - GetImageTypesScanningSequence(HeaderFileName); + PhilipsPAR::PARSliceIndexImageTypeVector sliceImageTypesIndexes = + philipsPAR->GetRECSliceIndexImageTypes(HeaderFileName); + PhilipsPAR::PARSliceIndexScanSequenceVector sliceScanSequencesIndexes = + philipsPAR->GetRECSliceIndexScanningSequence(HeaderFileName); + PhilipsPAR::PARImageTypeScanSequenceVector imageTypesScanSequencesIndexes = + philipsPAR->GetImageTypesScanningSequence(HeaderFileName); PhilipsRECImageIOSetupSliceIndex(this->m_SliceIndex,1,par, imageTypesScanSequencesIndexes,sliceImageTypesIndexes, sliceScanSequencesIndexes); @@ -606,10 +681,14 @@ void PhilipsRECImageIO::ReadImageInformation() m_PixelType = SCALAR; break; default: - ExceptionObject exception(__FILE__, __LINE__); - exception.SetDescription("Unknown data type"); + OStringStream message; + message << "Unknown data type. par.bit must be 8 or 16. " + << "par.bit is " + << par.bit; + ExceptionObject exception(__FILE__, __LINE__, + message.str(), + ITK_LOCATION); throw exception; - break; } // // set up the dimension stuff @@ -734,6 +813,10 @@ void PhilipsRECImageIO::ReadImageInformation() EncapsulateMetaData<std::string>(thisDic,PAR_Version, std::string("V4.1",6)); break; + case RESEARCH_IMAGE_EXPORT_TOOL_V4_2: + EncapsulateMetaData<std::string>(thisDic,PAR_Version, + std::string("V4.2",6)); + break; } EncapsulateMetaData<std::string>(thisDic,PAR_ExaminationName, @@ -847,6 +930,10 @@ void PhilipsRECImageIO::ReadImageInformation() EncapsulateMetaData<ScanningSequenceImageTypeRescaleValuesContainerTypePtr>( thisDic,PAR_ScanningSequenceImageTypeRescaleValues, scanningSequenceImageTypeRescaleVector); + EncapsulateMetaData<int>(thisDic,PAR_NumberOfASLLabelTypes, + par.num_label_types); + EncapsulateMetaData<LabelTypesASLContainerType::Pointer>(thisDic, + PAR_ASLLabelTypes, labelTypesASLVector); return; } diff --git a/Utilities/ITK/Code/Review/itkPhilipsRECImageIO.h b/Utilities/ITK/Code/Review/itkPhilipsRECImageIO.h index eef92a8950..15541b7767 100644 --- a/Utilities/ITK/Code/Review/itkPhilipsRECImageIO.h +++ b/Utilities/ITK/Code/Review/itkPhilipsRECImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPhilipsRECImageIO.h,v $ Language: C++ - Date: $Date: 2008-06-23 22:04:35 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-03-19 14:20:58 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,18 +85,20 @@ public: typedef vnl_vector_fixed< double, 3 > ImageTypeRescaleValuesType; typedef VectorContainer< unsigned int, ImageTypeRescaleValuesType > - ImageTypeRescaleValuesContainerType; + ImageTypeRescaleValuesContainerType; typedef ImageTypeRescaleValuesContainerType::Pointer - ImageTypeRescaleValuesContainerTypePtr; + ImageTypeRescaleValuesContainerTypePtr; typedef VectorContainer< unsigned int, ImageTypeRescaleValuesContainerTypePtr > - ScanningSequenceImageTypeRescaleValuesContainerType; - typedef double GradientBvalueType; + ScanningSequenceImageTypeRescaleValuesContainerType; + typedef double GradientBvalueType; typedef VectorContainer< unsigned int, GradientBvalueType > - GradientBvalueContainerType; + GradientBvalueContainerType; typedef vnl_vector_fixed< double, 3 > - GradientDirectionType; + GradientDirectionType; typedef VectorContainer< unsigned int, GradientDirectionType > - GradientDirectionContainerType; + GradientDirectionContainerType; + typedef VectorContainer< unsigned int, int > + LabelTypesASLContainerType; /*-------- This part of the interfaces deals with reading data. ----- */ @@ -155,56 +157,6 @@ private: ImageIOBase::ByteOrder m_MachineByteOrder; }; -extern const char *const PAR_Version; -extern const char *const PAR_SliceOrientation; -extern const char *const PAR_ExaminationName; -extern const char *const PAR_ProtocolName; -extern const char *const PAR_SeriesType; -extern const char *const PAR_AcquisitionNr; -extern const char *const PAR_ReconstructionNr; -extern const char *const PAR_ScanDuration; -extern const char *const PAR_MaxNumberOfCardiacPhases; -extern const char *const PAR_TriggerTimes; -extern const char *const PAR_MaxNumberOfEchoes; -extern const char *const PAR_EchoTimes; -extern const char *const PAR_MaxNumberOfDynamics; -extern const char *const PAR_MaxNumberOfMixes; -extern const char *const PAR_PatientPosition; -extern const char *const PAR_PreparationDirection; -extern const char *const PAR_Technique; -extern const char *const PAR_ScanMode; -extern const char *const PAR_NumberOfAverages; -extern const char *const PAR_ScanResolution; -extern const char *const PAR_RepetitionTimes; -extern const char *const PAR_ScanPercentage; -extern const char *const PAR_FOV; -extern const char *const PAR_WaterFatShiftPixels; -extern const char *const PAR_AngulationMidSlice; -extern const char *const PAR_OffCentreMidSlice; -extern const char *const PAR_FlowCompensation; -extern const char *const PAR_Presaturation; -extern const char *const PAR_CardiacFrequency; -extern const char *const PAR_MinRRInterval; -extern const char *const PAR_MaxRRInterval; -extern const char *const PAR_PhaseEncodingVelocity; -extern const char *const PAR_MTC; -extern const char *const PAR_SPIR; -extern const char *const PAR_EPIFactor; -extern const char *const PAR_TurboFactor; -extern const char *const PAR_DynamicScan; -extern const char *const PAR_Diffusion; -extern const char *const PAR_DiffusionEchoTime; -extern const char *const PAR_MaxNumberOfDiffusionValues; -extern const char *const PAR_GradientBValues; -extern const char *const PAR_MaxNumberOfGradientOrients; -extern const char *const PAR_GradientDirectionValues; -extern const char *const PAR_InversionDelay; -extern const char *const PAR_NumberOfImageTypes; -extern const char *const PAR_ImageTypes; -extern const char *const PAR_NumberOfScanningSequences; -extern const char *const PAR_ScanningSequences; -extern const char *const PAR_ScanningSequenceImageTypeRescaleValues; - } // end namespace itk #endif // __itkPhilipsRECImageIO_h diff --git a/Utilities/ITK/Code/Review/itkPhilipsRECImageIOFactory.h b/Utilities/ITK/Code/Review/itkPhilipsRECImageIOFactory.h index 637b8e1c6d..6fed5846c4 100644 --- a/Utilities/ITK/Code/Review/itkPhilipsRECImageIOFactory.h +++ b/Utilities/ITK/Code/Review/itkPhilipsRECImageIOFactory.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPhilipsRECImageIOFactory.h,v $ Language: C++ - Date: $Date: 2008-06-23 22:04:35 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-03-18 15:10:38 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,9 +58,9 @@ public: /** Register one factory of this type */ static void RegisterOneFactory(void) { - PhilipsRECImageIOFactory::Pointer MINC2Factory = + PhilipsRECImageIOFactory::Pointer factory = PhilipsRECImageIOFactory::New(); - ObjectFactoryBase::RegisterFactory(MINC2Factory); + ObjectFactoryBase::RegisterFactory(factory); } protected: diff --git a/Utilities/ITK/Code/Review/itkPriorityQueueContainer.h b/Utilities/ITK/Code/Review/itkPriorityQueueContainer.h index 06033f7d4c..adad7b9d1c 100755 --- a/Utilities/ITK/Code/Review/itkPriorityQueueContainer.h +++ b/Utilities/ITK/Code/Review/itkPriorityQueueContainer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPriorityQueueContainer.h,v $ Language: C++ - Date: $Date: 2008-10-12 12:46:48 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-05-13 22:05:47 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,7 +23,6 @@ #include <functional> #include <queue> -#include <assert.h> #include <vector> namespace itk @@ -280,7 +279,7 @@ public: Element Peek( ) { - assert( !Empty( ) ); + itkAssertOrThrowMacro( (!Empty( )), "Element is Empty" ); return( GetElementAtLocation( 0 ) ); } @@ -305,8 +304,9 @@ public: void Update( Element element ) { ElementIdentifier location = m_Interface.GetLocation( element ); - assert( location != -1 ); - assert( location < static_cast< ElementIdentifier >( this->Size( ) ) ); + itkAssertOrThrowMacro( (location != -1), "element is unknown"); + itkAssertOrThrowMacro( (location < static_cast< ElementIdentifier >( this->Size( ) ) ), + "Element location is out of range" ); UpdateDownTree( location ); UpdateUpTree( location ); } @@ -316,8 +316,9 @@ public: ElementIdentifier location = m_Interface.GetLocation( element ); m_Interface.SetLocation( element, -1); - assert( location != -1 ); - assert( location < static_cast< ElementIdentifier >( this->Size( ) ) ); + itkAssertOrThrowMacro( (location != -1), "element is unknown"); + itkAssertOrThrowMacro( (location < static_cast< ElementIdentifier >( this->Size( ) ) ), + "Element location is out of range" ); if( location == static_cast< ElementIdentifier >( this->Size( ) ) - 1 ) { @@ -325,8 +326,7 @@ public: } else { - SetElementAtLocation( location, - GetElementAtLocation( this->Size( ) - 1 ) ); + SetElementAtLocation( location, GetElementAtLocation( this->Size( ) - 1 ) ); this->pop_back(); UpdateDownTree( location ); UpdateUpTree( location ); diff --git a/Utilities/ITK/Code/Review/itkQuadEdge.h b/Utilities/ITK/Code/Review/itkQuadEdge.h index 3f1074bda3..c56604c723 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdge.h +++ b/Utilities/ITK/Code/Review/itkQuadEdge.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdge.h,v $ Language: C++ - Date: $Date: 2009-02-07 17:19:59 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-05-13 21:52:25 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,8 +22,6 @@ #include "itkMacro.h" -#include <assert.h> - // Debugging macros for classes that do not derive from the itkObject. // FIXME: Maybe variations of these macros should be moved into // itkMacro.h diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMesh.h b/Utilities/ITK/Code/Review/itkQuadEdgeMesh.h index 2e5a5e4a92..a3e8e065e0 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMesh.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMesh.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMesh.h,v $ Language: C++ - Date: $Date: 2009-02-07 23:16:28 $ - Version: $Revision: 1.33 $ + Date: $Date: 2009-04-08 23:10:20 $ + Version: $Revision: 1.34 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -483,6 +483,9 @@ protected: QuadEdgeMesh(); virtual ~QuadEdgeMesh(); + /** Release the memory of each one of the cells independently. */ + virtual void ClearCellsContainer(); + CellsContainerPointer m_EdgeCellsContainer; private: diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMesh.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMesh.txx index 2fb4e78bba..609e37af9c 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMesh.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMesh.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMesh.txx,v $ Language: C++ - Date: $Date: 2009-02-07 23:16:29 $ - Version: $Revision: 1.53 $ + Date: $Date: 2009-04-08 23:10:22 $ + Version: $Revision: 1.54 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -108,6 +108,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > this->m_FreePointIndexes = mesh->m_FreePointIndexes; this->m_FreeCellIndexes = mesh->m_FreeCellIndexes; + this->ClearCellsContainer(); this->m_EdgeCellsContainer = mesh->m_EdgeCellsContainer; this->m_NumberOfFaces = mesh->m_NumberOfFaces; this->m_NumberOfEdges = mesh->m_NumberOfEdges; @@ -1331,6 +1332,14 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > template< typename TPixel, unsigned int VDimension, typename TTraits > QuadEdgeMesh< TPixel, VDimension, TTraits > ::~QuadEdgeMesh() +{ + this->ClearCellsContainer(); +} + +template< typename TPixel, unsigned int VDimension, typename TTraits > +void +QuadEdgeMesh< TPixel, VDimension, TTraits > +::ClearCellsContainer() { if( m_EdgeCellsContainer->GetReferenceCount() == 1 ) { @@ -1346,7 +1355,6 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > } } - /** */ template< typename TPixel, unsigned int VDimension, typename TTraits > diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshBorderTransform.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshBorderTransform.h index 3ffa8d9af5..161eab2e66 100755 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshBorderTransform.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshBorderTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshBorderTransform.h,v $ Language: C++ - Date: $Date: 2009-01-19 00:09:47 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -103,10 +103,10 @@ public: }; itkSetMacro( TransformType, BorderTransformType ); - itkGetMacro( TransformType, BorderTransformType ); + itkGetConstMacro( TransformType, BorderTransformType ); itkSetMacro( Radius, InputCoordRepType ); - itkGetMacro( Radius, InputCoordRepType ); + itkGetConstMacro( Radius, InputCoordRepType ); void ComputeTransform( ); MapPointIdentifier GetBoundaryPtMap( ); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshBorderTransform.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshBorderTransform.txx index 29e9bbdced..50805f61f9 100755 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshBorderTransform.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshBorderTransform.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshBorderTransform.txx,v $ Language: C++ - Date: $Date: 2009-01-19 00:09:47 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-22 01:41:44 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,9 +26,10 @@ namespace itk // ---------------------------------------------------------------------------- template< class TInputMesh, class TOutputMesh > QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > -::QuadEdgeMeshBorderTransform( ) : m_TransformType( SQUARE_BORDER_TRANSFORM ), -m_Radius( 0. ) +::QuadEdgeMeshBorderTransform() { + this->m_TransformType = SQUARE_BORDER_TRANSFORM; + this->m_Radius = 0.0; } // ---------------------------------------------------------------------------- @@ -37,7 +38,7 @@ typename QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh >::MapPointIdentif QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > ::GetBoundaryPtMap( ) { - return m_BoundaryPtMap; + return this->m_BoundaryPtMap; } // ---------------------------------------------------------------------------- @@ -46,7 +47,7 @@ typename QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh >::InputVectorPoin QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > ::GetBorder( ) { - return m_Border; + return this->m_Border; } @@ -70,10 +71,10 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > it != bdryEdge->EndGeomLnext( ); ++it, i++ ) { - m_BoundaryPtMap[it.Value( )->GetOrigin( )] = i; + this->m_BoundaryPtMap[it.Value( )->GetOrigin( )] = i; } - m_Border.resize( i ); + this->m_Border.resize( i ); } @@ -82,7 +83,7 @@ template< class TInputMesh, class TOutputMesh > void QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh >:: GenerateData( ) { - ComputeTransform(); + this->ComputeTransform(); } @@ -100,7 +101,7 @@ ComputeLongestBorder( ) InputEdgeListPointerType list = boundaryRepresentativeEdges->Evaluate( *input ); - InputCoordRepType max_length( 0. ), length( 0. ); + InputCoordRepType max_length( 0.0 ), length( 0.0 ); InputEdgeListIterator oborder_it = list->begin( ); for( InputEdgeListIterator b_it = list->begin( ); @@ -176,14 +177,14 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > { InputMeshPointer input = this->GetInput( ); - size_t NbBoundaryPt = m_BoundaryPtMap.size( ); + size_t NbBoundaryPt = this->m_BoundaryPtMap.size( ); InputCoordRepType r = RadiusMaxSquare( ); - InputCoordRepType two_r = 2. * r; - InputCoordRepType inv_two_r = 1. / two_r; + InputCoordRepType two_r = 2.0 * r; + InputCoordRepType inv_two_r = 1.0 / two_r; - InputPointIdentifier id = m_BoundaryPtMap.begin( )->first; + InputPointIdentifier id = this->m_BoundaryPtMap.begin( )->first; InputPointType pt1 = input->GetPoint( id ); id = ( --m_BoundaryPtMap.end( ) )->first; @@ -191,17 +192,17 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > InputCoordRepType dist = pt1.SquaredEuclideanDistanceTo( pt2 ); - std::vector< InputCoordRepType > tetas( NbBoundaryPt, 0. ); + std::vector< InputCoordRepType > tetas( NbBoundaryPt, 0.0 ); tetas[0] = static_cast< InputCoordRepType >( vcl_acos( ( two_r - dist ) * inv_two_r ) ); - MapPointIdentifierIterator BoundaryPtIterator = m_BoundaryPtMap.begin( ); + MapPointIdentifierIterator BoundaryPtIterator = this->m_BoundaryPtMap.begin( ); ++BoundaryPtIterator; OutputPointIdentifier j = 1; - while( BoundaryPtIterator != m_BoundaryPtMap.end() ) + while( BoundaryPtIterator != this->m_BoundaryPtMap.end() ) { pt1 = pt2; @@ -216,26 +217,26 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > ++BoundaryPtIterator; } - InputCoordRepType a = ( 2. * vnl_math::pi ) / tetas[NbBoundaryPt-1]; + InputCoordRepType a = ( 2.0 * vnl_math::pi ) / tetas[NbBoundaryPt-1]; - if( m_Radius == 0. ) - m_Radius = vcl_pow( vcl_sqrt( r ), a ); + if( this->m_Radius == 0.0 ) + { + this->m_Radius = vcl_pow( vcl_sqrt( r ), a ); + } for( MapPointIdentifierIterator - BoundaryPtMapIterator = m_BoundaryPtMap.begin( ); - BoundaryPtMapIterator != m_BoundaryPtMap.end( ); + BoundaryPtMapIterator = this->m_BoundaryPtMap.begin( ); + BoundaryPtMapIterator != this->m_BoundaryPtMap.end( ); ++BoundaryPtMapIterator ) { id = BoundaryPtMapIterator->first; j = BoundaryPtMapIterator->second; - pt1[0] = m_Radius * - static_cast< InputCoordRepType >( vcl_cos( a * tetas[j] ) ); - pt1[1] = m_Radius * - static_cast< InputCoordRepType >( vcl_sin( a * tetas[j] ) ); - pt1[2] = 0.; + pt1[0] = this->m_Radius * static_cast< InputCoordRepType >( vcl_cos( a * tetas[j] ) ); + pt1[1] = this->m_Radius * static_cast< InputCoordRepType >( vcl_sin( a * tetas[j] ) ); + pt1[2] = 0.0; - m_Border[j] = pt1; + this->m_Border[j] = pt1; } } @@ -254,12 +255,10 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > InputCoordRepType oRmax( 0.), r; for( MapPointIdentifierIterator - BoundaryPtIterator = m_BoundaryPtMap.begin( ); - BoundaryPtIterator != m_BoundaryPtMap.end( ); + BoundaryPtIterator = this->m_BoundaryPtMap.begin( ); + BoundaryPtIterator != this->m_BoundaryPtMap.end( ); ++BoundaryPtIterator ) { -// InputPointIdentifier pid = BoundaryPtIterator->first; - r = static_cast< InputCoordRepType >( center.SquaredEuclideanDistanceTo( input->GetPoint( BoundaryPtIterator->first ) ) ); @@ -286,7 +285,7 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > InputMeshPointer input = this->GetInput( ); InputPointType oCenter; - oCenter.Fill( 0. ); + oCenter.Fill( 0.0 ); InputPointsContainer* points = input->GetPoints( ); @@ -305,7 +304,7 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > } } - InputCoordRepType invNbOfPoints = 1. / + InputCoordRepType invNbOfPoints = 1.0 / static_cast< InputCoordRepType >( input->GetNumberOfPoints( ) ); for( i = 0; i < PointDimension; ++i ) @@ -324,7 +323,7 @@ void QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > { this->ComputeBoundary( ); - switch( m_TransformType ) + switch( this->m_TransformType ) { default: case SQUARE_BORDER_TRANSFORM: @@ -352,10 +351,10 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > InputQEType* bdryEdge = ( *list->begin( ) ); - size_t NbBoundaryPt = m_BoundaryPtMap.size( ); - std::vector< InputCoordRepType > Length( NbBoundaryPt + 1, 0. ); + size_t NbBoundaryPt = this->m_BoundaryPtMap.size( ); + std::vector< InputCoordRepType > Length( NbBoundaryPt + 1, 0.0 ); - InputCoordRepType TotalLength( 0. ), distance; + InputCoordRepType TotalLength( 0.0 ), distance; InputPointIdentifier i(0), org(0), dest(0); InputPointType PtOrg, PtDest; @@ -375,11 +374,13 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > Length[i] = TotalLength; } - if( m_Radius == 0. ) - m_Radius = 1000.; + if( this->m_Radius == 0.0 ) + { + this->m_Radius = 1000.; + } - InputCoordRepType EdgeLength = 2. * m_Radius; - InputCoordRepType ratio = 4. * EdgeLength / TotalLength; + InputCoordRepType EdgeLength = 2.0 * this->m_Radius; + InputCoordRepType ratio = 4.0 * EdgeLength / TotalLength; for( i = 0; i < NbBoundaryPt + 1; ++i ) { @@ -387,47 +388,47 @@ QuadEdgeMeshBorderTransform< TInputMesh, TOutputMesh > } InputPointType pt; - pt[0] = -m_Radius; - pt[1] = m_Radius; - pt[2] = 0.; + pt[0] = - this->m_Radius; + pt[1] = this->m_Radius; + pt[2] = 0.0; - m_Border[0] = pt; + this->m_Border[0] = pt; i = 1; while( Length[i] < EdgeLength ) { - pt[0] = -m_Radius + Length[i]; - m_Border[ i++ ] = pt; + pt[0] = - this->m_Radius + Length[i]; + this->m_Border[ i++ ] = pt; } - pt[0] = m_Radius; - pt[1] = m_Radius; - m_Border[ i++ ] = pt; + pt[0] = this->m_Radius; + pt[1] = this->m_Radius; + this->m_Border[ i++ ] = pt; - while( Length[i] < ( 2. * EdgeLength ) ) + while( Length[i] < ( 2.0 * EdgeLength ) ) { - pt[1] = m_Radius - ( Length[i] - EdgeLength ); - m_Border[ i++ ] = pt; + pt[1] = this->m_Radius - ( Length[i] - EdgeLength ); + this->m_Border[ i++ ] = pt; } - pt[0] = m_Radius; - pt[1] = - m_Radius; - m_Border[ i++ ] = pt; + pt[0] = this->m_Radius; + pt[1] = - this->m_Radius; + this->m_Border[ i++ ] = pt; - while( Length[i] < ( 3. * EdgeLength ) ) + while( Length[i] < ( 3.0 * EdgeLength ) ) { - pt[0] = m_Radius - ( Length[i] - 2. * EdgeLength ); - m_Border[ i++ ] = pt; + pt[0] = this->m_Radius - ( Length[i] - 2.0 * EdgeLength ); + this->m_Border[ i++ ] = pt; } - pt[0] = - m_Radius; - pt[1] = - m_Radius; - m_Border[ i++ ] = pt; + pt[0] = - this->m_Radius; + pt[1] = - this->m_Radius; + this->m_Border[ i++ ] = pt; while( i < NbBoundaryPt ) { - pt[1] = -m_Radius + ( Length[i] - 3. * EdgeLength ); - m_Border[ i++ ] = pt; + pt[1] = - this->m_Radius + ( Length[i] - 3.0 * EdgeLength ); + this->m_Border[ i++ ] = pt; } } diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshCleanFilter.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshCleanFilter.h index 2b7af43d77..3663a211da 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshCleanFilter.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshCleanFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshCleanFilter.h,v $ Language: C++ - Date: $Date: 2009-02-20 16:55:42 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-05-13 21:52:25 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -119,7 +119,8 @@ protected: if( ( m_AbsoluteTolerance == zeroValue ) && ( m_RelativeTolerance != zeroValue ) ) { - assert( ( m_RelativeTolerance > zeroValue ) && ( m_RelativeTolerance < 1. ) ); + itkAssertOrThrowMacro( ( m_RelativeTolerance > zeroValue ) && ( m_RelativeTolerance < 1. ), + "Relative tolerance out of range" ); BoundingBoxPointer bounding_box = BoundingBoxType::New(); bounding_box->SetPoints( this->GetInput()->GetPoints() ); bounding_box->ComputeBoundingBox(); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDecimationCriteria.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDecimationCriteria.h index dc8899d5bd..729fa7da24 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDecimationCriteria.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDecimationCriteria.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshDecimationCriteria.h,v $ Language: C++ - Date: $Date: 2008-09-30 22:27:57 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -61,7 +61,7 @@ public: this->m_MeasureBound = bound; } - itkGetMacro( TopologicalChange, bool ); + itkGetConstMacro( TopologicalChange, bool ); itkSetMacro( TopologicalChange, bool ); virtual bool is_satisfied( MeshType* iMesh, diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDecimationFilter.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDecimationFilter.h index d3d0990dbc..ca52c62f3e 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDecimationFilter.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDecimationFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshDecimationFilter.h,v $ Language: C++ - Date: $Date: 2009-02-16 20:22:11 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-22 01:41:45 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -66,30 +66,21 @@ protected: void GenerateData() { - Superclass::GenerateData(); + this->CopyInputMeshToOutputMesh(); Initialize(); FillPriorityQueue(); m_Iteration = 0; -// bool topological_change = this->m_Criterion->GetTopologicalChange(); do { -// std::cout <<m_Iteration <<std::endl; - Extract(); -// if ( topological_change ) -// { -// std::cout <<"ProcessWithoutAnyTopologicalGuarantee" <<std::endl; -// ProcessWithoutAnyTopologicalGuarantee(); -// } -// else -// { - if ( ProcessWithTopologicalGuarantee() ) - { -// std::cout <<"ProcessWithTopologicalGuarantee" <<std::endl; - return; - } -// } + this->Extract(); + + if ( ProcessWithTopologicalGuarantee() ) + { + return; + } + ++m_Iteration; } while ( !IsCriterionSatisfied() ); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDelaunayConformingFilter.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDelaunayConformingFilter.h index a29bf7db4c..c66317150f 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDelaunayConformingFilter.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDelaunayConformingFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshDelaunayConformingFilter.h,v $ Language: C++ - Date: $Date: 2008-10-07 20:13:57 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -89,7 +89,7 @@ public: itkNewMacro( Self ); itkTypeMacro( QuadEdgeMeshDelaunayConformingFilter, QuadEdgeMeshToQuadEdgeMeshFilter ); - itkGetMacro( NumberOfEdgeFlips, unsigned long ); + itkGetConstMacro( NumberOfEdgeFlips, unsigned long ); public: typedef std::list< OutputEdgeCellType* > OutputEdgeCellListType; diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDelaunayConformingFilter.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDelaunayConformingFilter.txx index 64b2eac6d2..80784eedca 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDelaunayConformingFilter.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDelaunayConformingFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshDelaunayConformingFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-09 14:33:44 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-22 01:41:45 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,11 +25,12 @@ namespace itk // --------------------------------------------------------------------- template< typename TInputMesh, typename TOutputMesh > -QuadEdgeMeshDelaunayConformingFilter< TInputMesh, TOutputMesh >:: - QuadEdgeMeshDelaunayConformingFilter( ) : Superclass( ), m_NumberOfEdgeFlips( 0 ) +QuadEdgeMeshDelaunayConformingFilter< TInputMesh, TOutputMesh > +::QuadEdgeMeshDelaunayConformingFilter() { - m_FlipEdge = FlipEdgeFunctionType::New( ); - m_PriorityQueue = PriorityQueueType::New( ); + this->m_NumberOfEdgeFlips = 0; + this->m_FlipEdge = FlipEdgeFunctionType::New( ); + this->m_PriorityQueue = PriorityQueueType::New( ); } // --------------------------------------------------------------------- @@ -143,7 +144,7 @@ Process( ) qe = m_FlipEdge->Evaluate( qe ); if( qe != 0 ) { - ++m_NumberOfEdgeFlips; + ++this->m_NumberOfEdgeFlips; list_qe[4] = qe; for( it = list_qe.begin( ); it != list_qe.end( ); ++it ) @@ -186,13 +187,13 @@ template< typename TInputMesh, typename TOutputMesh > void QuadEdgeMeshDelaunayConformingFilter< TInputMesh, TOutputMesh >:: GenerateData( ) { - Superclass::GenerateData( ); + this->CopyInputMeshToOutputMesh( ); // initialize all required instances - m_NumberOfEdgeFlips = 0; + this->m_NumberOfEdgeFlips = 0; - InitializePriorityQueue(); - Process(); + this->InitializePriorityQueue(); + this->Process(); } } // end namespace itk diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDiscreteCurvatureEstimator.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDiscreteCurvatureEstimator.h index f968963028..08e8600ed0 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshDiscreteCurvatureEstimator.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshDiscreteCurvatureEstimator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshDiscreteCurvatureEstimator.h,v $ Language: C++ - Date: $Date: 2008-10-01 18:52:09 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-22 01:41:45 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -77,7 +77,9 @@ protected: OutputPointType p[3]; for( int i = 0; i < 3; i++ ) + { p[i] = output->GetPoint( id[i] ); + } if( !TriangleType::IsObtuse( p[0], p[1], p[2] ) ) { @@ -101,15 +103,20 @@ protected: static_cast< OutputCurvatureType >( TriangleType::ComputeArea( p[0], p[1], p[2] ) ); if( ( p[1] - p[0] ) * ( p[2] - p[0] ) < 0. ) + { return 0.5 * area; + } else + { return 0.25 * area; + } } } virtual void GenerateData() { - Superclass::GenerateData(); + this->CopyInputMeshToOutputMesh(); + OutputMeshPointer output = this->GetOutput(); OutputPointsContainerPointer points = output->GetPoints(); @@ -125,6 +132,7 @@ protected: private: QuadEdgeMeshDiscreteCurvatureEstimator( const Self& ); // purposely not implemented void operator = ( const Self& ); // purposely not implemented + }; } // end namespace itk diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshEdgeMergeDecimationFilter.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshEdgeMergeDecimationFilter.txx index 4fdf72faa5..fe3ab8ae76 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshEdgeMergeDecimationFilter.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshEdgeMergeDecimationFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshEdgeMergeDecimationFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-26 21:47:35 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-03-25 14:58:44 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -159,6 +159,7 @@ Extract() m_Priority = m_PriorityQueue->Peek( )->m_Priority; m_PriorityQueue->Pop(); + delete m_QueueMapper[m_Element]; m_QueueMapper.erase( m_Element ); } while ( !IsEdgeOKToBeProcessed( m_Element ) ); } diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.h index 0cac31d17c..98f8b61f8d 100755 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.h,v $ Language: C++ - Date: $Date: 2009-02-10 05:07:49 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -70,7 +70,7 @@ public: /** Evaluate at the specified input position */ virtual OutputType Evaluate( QEType* h ); - // itkGetMacro( EdgeStatus, EdgeStatusType ); + // itkGetConstMacro( EdgeStatus, EdgeStatusType ); protected: QuadEdgeMeshEulerOperatorFlipEdgeFunction(); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshEulerOperatorJoinVertexFunction.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshEulerOperatorJoinVertexFunction.h index 3bb8051543..cd026f0f32 100755 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshEulerOperatorJoinVertexFunction.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshEulerOperatorJoinVertexFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshEulerOperatorJoinVertexFunction.h,v $ Language: C++ - Date: $Date: 2009-02-16 20:22:11 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -94,8 +94,8 @@ public: EDGE_JOINING_DIFFERENT_BORDERS //10 }; - itkGetMacro( OldPointID, PointIdentifier ); - itkGetMacro( EdgeStatus, EdgeStatusType ); + itkGetConstMacro( OldPointID, PointIdentifier ); + itkGetConstMacro( EdgeStatus, EdgeStatusType ); protected: QuadEdgeMeshEulerOperatorJoinVertexFunction(); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshNormalFilter.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshNormalFilter.h index 43e2963a4a..f976b9e6a6 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshNormalFilter.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshNormalFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshNormalFilter.h,v $ Language: C++ - Date: $Date: 2008-10-03 21:30:29 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -99,7 +99,7 @@ public: }; itkSetMacro ( Weight, WeightType ); - itkGetMacro ( Weight, WeightType ); + itkGetConstMacro ( Weight, WeightType ); protected: QuadEdgeMeshNormalFilter( ); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshNormalFilter.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshNormalFilter.txx index f209013c82..976dbf1a28 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshNormalFilter.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshNormalFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshNormalFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-03 21:33:40 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-22 01:41:45 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,19 +23,22 @@ namespace itk { template< class TInputMesh, class TOutputMesh > -QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >:: -QuadEdgeMeshNormalFilter( ) : Superclass( ), m_Weight( THURMER ) -{} +QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh > +::QuadEdgeMeshNormalFilter( ) +{ + this->m_Weight = THURMER; +} template< class TInputMesh, class TOutputMesh > -QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >:: -~QuadEdgeMeshNormalFilter( ) -{} +QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh > +::~QuadEdgeMeshNormalFilter( ) +{ +} template< class TInputMesh, class TOutputMesh > typename QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >::OutputFaceNormalType -QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >:: -ComputeFaceNormal( OutputPolygonType* iPoly ) +QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh > +::ComputeFaceNormal( OutputPolygonType* iPoly ) { OutputMeshPointer output = this->GetOutput( ); @@ -56,8 +59,8 @@ ComputeFaceNormal( OutputPolygonType* iPoly ) template< class TInputMesh, class TOutputMesh > void -QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >:: -ComputeAllFaceNormals( ) +QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh > +::ComputeAllFaceNormals( ) { OutputMeshPointer output = this->GetOutput( ); OutputPolygonType* poly; @@ -81,8 +84,8 @@ ComputeAllFaceNormals( ) template< class TInputMesh, class TOutputMesh > void -QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >:: -ComputeAllVertexNormals( ) +QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh > +::ComputeAllVertexNormals( ) { OutputMeshPointer output = this->GetOutput( ); OutputPointsContainerPointer points = output->GetPoints( ); @@ -99,8 +102,8 @@ ComputeAllVertexNormals( ) template< class TInputMesh, class TOutputMesh > typename QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >::OutputVertexNormalType -QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >:: -ComputeVertexNormal( const OutputPointIdentifier& iId ) +QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh > +::ComputeVertexNormal( const OutputPointIdentifier& iId ) { OutputMeshPointer output = this->GetOutput( ); @@ -127,11 +130,9 @@ ComputeVertexNormal( const OutputPointIdentifier& iId ) } template< class TInputMesh, class TOutputMesh > -typename QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >:: - OutputVertexNormalComponentType -QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >:: -Weight( const OutputPointIdentifier& iPId, - const OutputCellIdentifier& iCId ) +typename QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >::OutputVertexNormalComponentType +QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh > +::Weight( const OutputPointIdentifier& iPId, const OutputCellIdentifier& iCId ) { if( m_Weight == GOURAUD ) { @@ -207,13 +208,15 @@ Weight( const OutputPointIdentifier& iPId, } template< class TInputMesh, class TOutputMesh > -void QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh >::GenerateData( ) +void QuadEdgeMeshNormalFilter< TInputMesh, TOutputMesh > +::GenerateData( ) { - Superclass::GenerateData( ); - - ComputeAllFaceNormals( ); - ComputeAllVertexNormals( ); + this->CopyInputMeshToOutputMesh( ); + this->ComputeAllFaceNormals( ); + this->ComputeAllVertexNormals( ); } + + } #endif diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshParam.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshParam.txx index abf84af260..9185544ecc 100755 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshParam.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshParam.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshParam.txx,v $ Language: C++ - Date: $Date: 2008-10-03 22:03:41 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-05-13 21:52:25 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -165,7 +165,7 @@ void QuadEdgeMeshParam< TInputMesh, TOutputMesh, TSolverTraits > ::GenerateData( ) { - Superclass::GenerateData( ); + this->CopyInputMeshToOutputMesh( ); InputMeshPointer input = this->GetInput( ); OutputMeshType* output = this->GetOutput( ); @@ -177,10 +177,12 @@ QuadEdgeMeshParam< TInputMesh, TOutputMesh, TSolverTraits > m_BoundaryPtMap = m_BorderTransform->GetBoundaryPtMap( ); } - assert( ( m_BoundaryPtMap.size( ) > 2 ) && ( m_Border.size( ) > 2 ) ); - CopyToOutputBorder( ); + itkAssertOrThrowMacro( ( ( m_BoundaryPtMap.size( ) > 2 ) && ( m_Border.size( ) > 2 ) ), + "BoundaryPtMap or Border have less than 2 elements" ); - ComputeListOfInteriorVertices( ); + this->CopyToOutputBorder( ); + + this->ComputeListOfInteriorVertices( ); size_t NbOfInteriorPts = m_InternalPtMap.size( ); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshSmoothing.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshSmoothing.h index 8e3672ca80..8d941132cb 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshSmoothing.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshSmoothing.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshSmoothing.h,v $ Language: C++ - Date: $Date: 2009-02-25 21:17:07 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,8 +85,13 @@ public: { m_CoefficientsMethod = iMethod; } itkSetMacro( NumberOfIterations, unsigned int ); + itkGetConstMacro( NumberOfIterations, unsigned int ); + itkSetMacro( DelaunayConforming, bool ); + itkGetConstMacro( DelaunayConforming, bool ); + itkSetMacro( RelaxationFactor, OutputCoordType ); + itkGetConstMacro( RelaxationFactor, OutputCoordType ); protected: QuadEdgeMeshSmoothing(); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshSmoothing.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshSmoothing.txx index 32ca31f498..42bb04213b 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshSmoothing.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshSmoothing.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshSmoothing.txx,v $ Language: C++ - Date: $Date: 2009-02-20 15:29:08 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-22 01:41:45 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,18 +21,22 @@ namespace itk { template< class TInputMesh, class TOutputMesh > -QuadEdgeMeshSmoothing< TInputMesh, TOutputMesh >::QuadEdgeMeshSmoothing() : - Superclass(), m_CoefficientsMethod( 0 ), - m_DelaunayConforming( false ), m_NumberOfIterations( 1 ), - m_RelaxationFactor( static_cast< OutputCoordType >( 1. ) ) +QuadEdgeMeshSmoothing< TInputMesh, TOutputMesh > +::QuadEdgeMeshSmoothing() { - m_InputDelaunayFilter = InputOutputDelaunayConformingType::New(); - m_OutputDelaunayFilter = OutputDelaunayConformingType::New(); + this->m_CoefficientsMethod = 0; + this->m_DelaunayConforming = false; + this->m_NumberOfIterations = 1; + this->m_RelaxationFactor = static_cast< OutputCoordType >( 1.0 ); + + this->m_InputDelaunayFilter = InputOutputDelaunayConformingType::New(); + this->m_OutputDelaunayFilter = OutputDelaunayConformingType::New(); } template< class TInputMesh, class TOutputMesh > QuadEdgeMeshSmoothing< TInputMesh, TOutputMesh >::~QuadEdgeMeshSmoothing() -{} +{ +} template< class TInputMesh, class TOutputMesh > void QuadEdgeMeshSmoothing< TInputMesh, TOutputMesh >:: @@ -45,13 +49,20 @@ GenerateData() OutputPointsContainerPointer points; OutputPointsContainerIterator it; - OutputPointType p, q, r; + + OutputPointType p; + OutputPointType q; + OutputPointType r; OutputVectorType v; - OutputCoordType coeff, sum_coeff, den; - OutputQEType* qe; - OutputQEType* qe_it; - if( m_DelaunayConforming ) + OutputCoordType coeff; + OutputCoordType sum_coeff; + OutputCoordType den; + + OutputQEType * qe; + OutputQEType * qe_it; + + if( this->m_DelaunayConforming ) { m_InputDelaunayFilter->SetInput( this->GetInput() ); if( m_NumberOfIterations == 0 ) @@ -69,9 +80,13 @@ GenerateData() else { if( m_NumberOfIterations == 0 ) - Superclass::GenerateData(); + { + this->CopyInputMeshToOutputMesh(); + } else + { mesh = this->GetInput(); + } } for( unsigned int iter = 0; iter < m_NumberOfIterations; ++iter ) @@ -85,7 +100,7 @@ GenerateData() if( qe != 0 ) { r = p; - v.Fill( 0. ); + v.Fill( 0.0 ); qe_it = qe; sum_coeff = 0.; do @@ -99,7 +114,7 @@ GenerateData() qe_it = qe_it->GetOnext(); } while( qe_it != qe ); - den = 1. / static_cast< OutputCoordType >( sum_coeff ); + den = 1.0 / static_cast< OutputCoordType >( sum_coeff ); v *= den; r += m_RelaxationFactor * v; @@ -114,7 +129,7 @@ GenerateData() mesh->SetPoints( temp ); - if( m_DelaunayConforming ) + if( this->m_DelaunayConforming ) { mesh->DisconnectPipeline(); m_OutputDelaunayFilter->SetInput( mesh ); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.h index c7c271ccc0..6dd3f02c3d 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshToQuadEdgeMeshFilter.h,v $ Language: C++ - Date: $Date: 2008-07-08 22:13:48 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-22 01:41:45 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -87,7 +87,7 @@ protected: QuadEdgeMeshToQuadEdgeMeshFilter( ); virtual ~QuadEdgeMeshToQuadEdgeMeshFilter( ) { } - virtual void GenerateData( ); + virtual void CopyInputMeshToOutputMesh( ); private: QuadEdgeMeshToQuadEdgeMeshFilter( const Self& ); // Not impl. diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.txx index eb4c6079d3..641016d066 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshToQuadEdgeMeshFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-07 23:16:29 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-22 01:41:45 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,7 +37,7 @@ QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > template< class TInputMesh, class TOutputMesh > void QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > -::GenerateData() +::CopyInputMeshToOutputMesh() { InputMeshConstPointer in = this->GetInput(); OutputMeshPointer out = this->GetOutput(); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshTopologyChecker.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshTopologyChecker.h index 047d890ae9..17069d68ac 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshTopologyChecker.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshTopologyChecker.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshTopologyChecker.h,v $ Language: C++ - Date: $Date: 2008-02-07 15:58:06 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-05-13 21:52:25 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,7 @@ namespace itk { /** \class QuadEdgeMeshTopologyChecker - * \brief Make some basic checks in order to assert that the considered + * \brief Make some basic checks in order to verify that the considered * mesh is not degenerated and correctly represents a surface * with a potential boundary. * diff --git a/Utilities/ITK/Code/Review/itkRankHistogram.h b/Utilities/ITK/Code/Review/itkRankHistogram.h index a9bd9ae069..a830113ac6 100644 --- a/Utilities/ITK/Code/Review/itkRankHistogram.h +++ b/Utilities/ITK/Code/Review/itkRankHistogram.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRankHistogram.h,v $ Language: C++ - Date: $Date: 2008-10-04 12:43:20 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-13 21:52:25 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -134,8 +134,8 @@ public: unsigned long ThisBin; bool eraseFlag = false; - // an assert is better than a log message in that case - assert(m_Initialized); + // an itkAssertOrThrowMacro is better than a log message in that case + itkAssertOrThrowMacro( m_Initialized, "Not Initialized" ); if (total < target) { @@ -325,9 +325,11 @@ public: void RemovePixel(const TInputPixel &p) { - assert(p - NumericTraits< TInputPixel >::NonpositiveMin() >= 0); - assert(p - NumericTraits< TInputPixel >::NonpositiveMin() < (int)m_Vec.size()); - assert(m_Entries >= 1); + itkAssertOrThrowMacro( ( p - NumericTraits< TInputPixel >::NonpositiveMin() >= 0 ), + "pixel value too close to zero"); + itkAssertOrThrowMacro( ( p - NumericTraits< TInputPixel >::NonpositiveMin() < (int)m_Vec.size()), + "pixel value outside the range of m_Vec.size()"); + itkAssertOrThrowMacro( ( m_Entries >= 1), "Not enough entries"); m_Vec[ (long unsigned int)(p - NumericTraits< TInputPixel >::NonpositiveMin()) ]--; --m_Entries; diff --git a/Utilities/ITK/Code/Review/itkRankImageFilter.h b/Utilities/ITK/Code/Review/itkRankImageFilter.h index f2e8956107..a1f1c073ca 100644 --- a/Utilities/ITK/Code/Review/itkRankImageFilter.h +++ b/Utilities/ITK/Code/Review/itkRankImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRankImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-08 22:26:45 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -98,7 +98,7 @@ public: typedef typename KernelType::SizeType RadiusType; itkSetMacro(Rank, float) - itkGetMacro(Rank, float) + itkGetConstMacro(Rank, float) protected: RankImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkRedColormapFunctor.h b/Utilities/ITK/Code/Review/itkRedColormapFunctor.h new file mode 100644 index 0000000000..57800a8a61 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRedColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRedColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRedColormapFunctor_h +#define __itkRedColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class RedColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT RedColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef RedColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + RedColormapFunctor() {}; + ~RedColormapFunctor() {}; + +private: + RedColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkRedColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkRedColormapFunctor.txx b/Utilities/ITK/Code/Review/itkRedColormapFunctor.txx new file mode 100644 index 0000000000..38b74c99fd --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRedColormapFunctor.txx @@ -0,0 +1,49 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRedColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRedColormapFunctor_txx +#define __itkRedColormapFunctor_txx + +#include "itkRedColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename RedColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +RedColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( value ); + pixel[1] = 0; + pixel[2] = 0; + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.h b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.h new file mode 100644 index 0000000000..281f6dc355 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.h @@ -0,0 +1,395 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRegionBasedLevelSetFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-13 15:27:45 $ + Version: $Revision: 1.11 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkRegionBasedLevelSetFunction_h +#define __itkRegionBasedLevelSetFunction_h + +#include "itkFiniteDifferenceFunction.h" +#include "itkRegularizedHeavisideStepFunction.h" +#include "vnl/vnl_matrix_fixed.h" + +namespace itk { + +/** \class RegionBasedLevelSetFunction + * + * \brief LevelSet function that computes a speed image based on regional integrals + * + * This class implements a level set function that computes the speed image by + * integrating values on the image domain. + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template < class TInput, // LevelSetImageType + class TFeature, // FeatureImageType + class TSharedData > +class ITK_EXPORT RegionBasedLevelSetFunction: public +FiniteDifferenceFunction< TInput > +{ +public: + /** Standard class typedefs. */ + typedef RegionBasedLevelSetFunction Self; + typedef FiniteDifferenceFunction< TInput > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + itkStaticConstMacro(ImageDimension, unsigned int, Superclass::ImageDimension); + + // itkNewMacro() is purposely not provided since this is an abstract class. + + /** Run-time type information (and related methods) */ + itkTypeMacro( RegionBasedLevelSetFunction, FiniteDifferenceFunction ); + + /** Extract some parameters from the superclass. */ + typedef double TimeStepType; + typedef typename Superclass::ImageType ImageType; + typedef typename Superclass::PixelType PixelType; + typedef PixelType ScalarValueType; + typedef typename Superclass::RadiusType RadiusType; + typedef typename Superclass::NeighborhoodType NeighborhoodType; + typedef typename Superclass::NeighborhoodScalesType NeighborhoodScalesType; + typedef typename Superclass::FloatOffsetType FloatOffsetType; + typedef FixedArray< ScalarValueType, itkGetStaticConstMacro(ImageDimension) > + VectorType; + + /* This structure is derived from LevelSetFunction and stores intermediate + values for computing time step sizes */ + struct GlobalDataStruct + { + GlobalDataStruct() + { + ScalarValueType null_value = NumericTraits<ScalarValueType>::Zero; + + m_MaxCurvatureChange = null_value; + m_MaxGlobalChange = null_value; + } + + ~GlobalDataStruct() {} + +// ScalarValueType m_MaxAdvectionChange; // not used +// ScalarValueType m_MaxPropagationChange; // not used + ScalarValueType m_MaxCurvatureChange; + + vnl_matrix_fixed<ScalarValueType, + itkGetStaticConstMacro(ImageDimension), + itkGetStaticConstMacro(ImageDimension)> m_dxy; + + ScalarValueType m_dx[itkGetStaticConstMacro(ImageDimension)]; + + ScalarValueType m_dx_forward[itkGetStaticConstMacro(ImageDimension)]; + ScalarValueType m_dx_backward[itkGetStaticConstMacro(ImageDimension)]; + + ScalarValueType m_GradMagSqr; + ScalarValueType m_MaxGlobalChange; + }; + + + typedef TInput InputImageType; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::PixelType InputPixelType; + typedef typename InputImageType::IndexType InputIndexType; + typedef typename InputImageType::IndexValueType InputIndexValueType; + typedef typename InputImageType::SizeType InputSizeType; + typedef typename InputImageType::SizeValueType InputSizeValueType; + typedef typename InputImageType::RegionType InputRegionType; + typedef typename InputImageType::PointType InputPointType; + + typedef TFeature FeatureImageType; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeaturePixelType; + typedef typename FeatureImageType::IndexType FeatureIndexType; + typedef typename FeatureImageType::OffsetType FeatureOffsetType; + + typedef TSharedData SharedDataType; + typedef typename SharedDataType::Pointer SharedDataPointer; + + typedef HeavisideStepFunctionBase< InputPixelType, InputPixelType > HeavisideFunctionType; + typedef typename HeavisideFunctionType::ConstPointer HeavisideFunctionConstPointer; + + void SetDomainFunction( const HeavisideFunctionType * f ) + { + this->m_DomainFunction = f; + } + + virtual void Initialize(const RadiusType &r) + { + this->SetRadius(r); + + // Dummy neighborhood. + NeighborhoodType it; + it.SetRadius( r ); + + // Find the center index of the neighborhood. + m_Center = it.Size() / 2; + + // Get the stride length for each axis. + for(unsigned int i = 0; i < ImageDimension; i++) + { + m_xStride[i] = it.GetStride(i); + } + } + + + void SetSharedData( SharedDataPointer sharedDataIn ) + { + this->m_SharedData = sharedDataIn; + } + + void UpdateSharedData( bool forceUpdate ); + + void *GetGlobalDataPointer() const + { + return new GlobalDataStruct; + } + + TimeStepType ComputeGlobalTimeStep(void *GlobalData) const; + + /** Compute the equation value. */ + PixelType ComputeUpdate(const NeighborhoodType &neighborhood, + void *globalData, const FloatOffsetType& = FloatOffsetType(0.0)); + + void SetInitialImage(InputImageType *f) + { + m_InitialImage = f; + } + + virtual const FeatureImageType *GetFeatureImage() const + { return m_FeatureImage.GetPointer(); } + virtual void SetFeatureImage(const FeatureImageType *f) + { m_FeatureImage = f; } + + /** Nu. Area regularization values */ + void SetAreaWeight( const ScalarValueType& nu) + { this->m_AreaWeight = nu; } + ScalarValueType GetAreaWeight() const + { return this->m_AreaWeight; } + + /** Lambda1. Internal intensity difference weight */ + void SetLambda1( const ScalarValueType& lambda1 ) + { this->m_Lambda1 = lambda1; } + ScalarValueType GetLambda1() const + { return this->m_Lambda1; } + + /** Lambda2. External intensity difference weight */ + void SetLambda2( const ScalarValueType& lambda2 ) + { this->m_Lambda2 = lambda2; } + ScalarValueType GetLambda2() const + { return this->m_Lambda2; } + + /** Gamma. Overlap penalty */ + void SetOverlapPenaltyWeight( const ScalarValueType& gamma ) + { this->m_OverlapPenaltyWeight = gamma; } + ScalarValueType GetOverlapPenaltyWeight() const + { return this->m_OverlapPenaltyWeight; } + + /** Gamma. Scales all curvature weight values */ + virtual void SetCurvatureWeight(const ScalarValueType c) + { m_CurvatureWeight = c; } + ScalarValueType GetCurvatureWeight() const + { return m_CurvatureWeight; } + + /** Weight of the laplacian smoothing term */ + void SetLaplacianSmoothingWeight(const ScalarValueType c) + { m_LaplacianSmoothingWeight = c; } + ScalarValueType GetLaplacianSmoothingWeight() const + { return m_LaplacianSmoothingWeight; } + + /** Volume matching weight. */ + void SetVolumeMatchingWeight( const ScalarValueType& tau ) + { this->m_VolumeMatchingWeight = tau; } + ScalarValueType GetVolumeMatchingWeight() const + { return this->m_VolumeMatchingWeight; } + + /** Pixel Volume = Number of pixels inside the level-set */ + void SetVolume( const ScalarValueType& volume ) + { this->m_Volume = volume; } + ScalarValueType GetVolume() const + { return this->m_Volume; } + + /** Set function id. */ + void SetFunctionId( const unsigned int& iFid ) + { this->m_FunctionId = iFid; } + + virtual void ReleaseGlobalDataPointer(void *GlobalData) const + { delete (GlobalDataStruct *) GlobalData; } + + virtual ScalarValueType ComputeCurvatureTerm(const NeighborhoodType &, + const FloatOffsetType &, GlobalDataStruct *gd ); + + /** \brief Laplacian smoothing speed can be used to spatially modify the + effects of laplacian smoothing of the level set function */ + virtual ScalarValueType LaplacianSmoothingSpeed( + const NeighborhoodType &, + const FloatOffsetType &, GlobalDataStruct * = 0) const + { return NumericTraits<ScalarValueType>::One; } + + /** \brief Curvature speed can be used to spatially modify the effects of + curvature . The default implementation returns one. */ + virtual ScalarValueType CurvatureSpeed(const NeighborhoodType &, + const FloatOffsetType &, GlobalDataStruct * = 0 + ) const + { return NumericTraits<ScalarValueType>::One; } + +protected: + + RegionBasedLevelSetFunction(); + virtual ~RegionBasedLevelSetFunction() {} + + /** The initial level set image */ + InputImageConstPointer m_InitialImage; + + /** The feature image */ + FeatureImageConstPointer m_FeatureImage; + + SharedDataPointer m_SharedData; + HeavisideFunctionConstPointer m_DomainFunction; + + /** Area regularization weight */ + ScalarValueType m_AreaWeight; + + /** Internal functional of the level set weight */ + ScalarValueType m_Lambda1; + + /** External functional of the level set weight */ + ScalarValueType m_Lambda2; + + /** Overlap Penalty Weight */ + ScalarValueType m_OverlapPenaltyWeight; + + /** Volume Regularization Weight */ + ScalarValueType m_VolumeMatchingWeight; + + /** Volume Constraint in pixels */ + ScalarValueType m_Volume; + + /** Curvature Regularization Weight */ + ScalarValueType m_CurvatureWeight; + + /** Laplacian Regularization Weight */ + ScalarValueType m_LaplacianSmoothingWeight; + + unsigned int m_FunctionId; + + std::slice x_slice[itkGetStaticConstMacro(ImageDimension)]; + ::size_t m_Center; + ::size_t m_xStride[itkGetStaticConstMacro(ImageDimension)]; + + static double m_WaveDT; + static double m_DT; + + void ComputeHImage(); + + /** \brief Compute the global term as a combination of the internal, external, + overlapping and volume regularization terms. */ + ScalarValueType ComputeGlobalTerm( + const ScalarValueType& imagePixel, + const InputIndexType& inputIndex ); + + /** \brief Compute the internal term + \param[in] iValue Feature Image Value + \param[in] iIdx Feature Image Index + \param[in] fId Index of the LevelSet Function */ + virtual ScalarValueType ComputeInternalTerm(const FeaturePixelType& iValue, + const FeatureIndexType& iIdx ) = 0; + + /** \brief Compute the external term + \param[in] iValue Feature Image Value + \param[in] iIdx Feature Image Index + \param[in] pr Product of Heaviside Functions + \note after discussion with kishore, pr is not and unsigned int */ + virtual ScalarValueType ComputeExternalTerm(const FeaturePixelType& iValue, + const FeatureIndexType& iIdx ) = 0; + + /** \brief Compute the overlap term + \param[in] featIndex + \param[out] pr = \f$ \prod_{i \neq j} H(\phi_i)\f$ + \return OverlapTerm = \f$ \sum_{i \neq j} H(\phi_i)\f$ */ + virtual ScalarValueType ComputeOverlapParameters( const FeatureIndexType& featIndex, + ScalarValueType& pr ) = 0; + + /** \brief Compute the overlap term + \return \f$ \int_{p \in \Omega} H(\phi_i) dp - this->Volume \f$ + \note the volume regularization does not depend on the spacing. + So the volume must be set in number of pixels (not in real world unit). */ + ScalarValueType ComputeVolumeRegularizationTerm( ); + + /** \brief Compute the laplacian term + \return \f$ \Delta \phi - \div(\frac{\nabla \phi}{|\nabla \phi|}) \f$ + \verbatim For details see + @inproceedings{bb30335, + AUTHOR = "Li, C.M. and Xu, C.Y. and Gui, C. and Fox, M.D.", + TITLE = "Level Set Evolution without Re-Initialization: A New Variational Formulation", + BOOKTITLE = CVPR05, + YEAR = "2005", + PAGES = "I: 430-436"} + \endverbatim */ + ScalarValueType ComputeLaplacianTerm( const NeighborhoodType &, + const FloatOffsetType &, GlobalDataStruct *gd ); + + /** \brief Compute the laplacian + \return \f$ \Delta \phi \f$ */ + ScalarValueType ComputeLaplacian( GlobalDataStruct *gd ); + + /** \brief Compute Hessian Matrix */ + void ComputeHessian( const NeighborhoodType &it, + GlobalDataStruct *globalData ); + + /** \brief Compute Parameters for the inner and outer parts. */ + virtual void ComputeParameters() = 0; + + /** \brief Update and save the inner and outer parameters in the shared data + data structure. */ + virtual void UpdateSharedDataParameters() = 0; + +private: + RegionBasedLevelSetFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkRegionBasedLevelSetFunction.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.txx b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.txx new file mode 100644 index 0000000000..d58e7c67a2 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.txx @@ -0,0 +1,412 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRegionBasedLevelSetFunction.txx,v $ + Language: C++ + Date: $Date: 2009-05-21 22:03:29 $ + Version: $Revision: 1.21 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkRegionBasedLevelSetFunction_txx +#define __itkRegionBasedLevelSetFunction_txx + +#include "itkRegionBasedLevelSetFunction.h" +#include "itkImageRegionIteratorWithIndex.h" + +namespace itk +{ +template < class TInput, + class TFeature, + class TSharedData > +double +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::m_WaveDT = 1.0/(2.0 * ImageDimension); + +template < class TInput, + class TFeature, + class TSharedData > +double +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::m_DT = 1.0/(2.0 * ImageDimension); + +template < class TInput, + class TFeature, + class TSharedData > +RegionBasedLevelSetFunction< TInput, + TFeature, + TSharedData > +::RegionBasedLevelSetFunction() +{ + m_Lambda1 = NumericTraits<ScalarValueType>::One; + m_Lambda2 = NumericTraits<ScalarValueType>::One; + + m_OverlapPenaltyWeight = NumericTraits<ScalarValueType>::Zero; + m_AreaWeight = NumericTraits<ScalarValueType>::Zero; + m_VolumeMatchingWeight = NumericTraits<ScalarValueType>::Zero; + m_LaplacianSmoothingWeight = NumericTraits<ScalarValueType>::Zero; + m_CurvatureWeight = NumericTraits<ScalarValueType>::Zero; + m_Volume = NumericTraits<ScalarValueType>::Zero; + + m_FunctionId = 0; + + m_SharedData = 0; + m_InitialImage = 0; + m_FeatureImage = 0; +} + +/* Computes the Heaviside function and stores it in m_HeavisideFunctionOfLevelSetImage */ +template < class TInput, + class TFeature, + class TSharedData > +void RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ComputeHImage() +{ + // The phi function + InputImageConstPointer contourImage = this->m_InitialImage; + InputImagePointer hBuffer = this->m_SharedData->m_LevelSetDataPointerVector[this->m_FunctionId]->m_HeavisideFunctionOfLevelSetImage; + + // Iterator for the phi function + typedef ImageRegionConstIteratorWithIndex< InputImageType > ConstImageIteratorType; + ConstImageIteratorType constIt( contourImage, contourImage->GetRequestedRegion() ); + + typedef ImageRegionIteratorWithIndex< InputImageType > ImageIteratorType; + ImageIteratorType It( hBuffer, hBuffer->GetRequestedRegion() ); + + It.GoToBegin(), + constIt.GoToBegin(); + + while( !constIt.IsAtEnd() ) + { + ScalarValueType hVal = m_DomainFunction->Evaluate( - constIt.Get() ); + It.Set( hVal ); + ++It; + ++constIt; + } +} + +template < class TInput, + class TFeature, + class TSharedData > +void +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::UpdateSharedData( bool forceUpdate ) +{ + if ( forceUpdate ) + { + // Must update all H before updating C + this->ComputeHImage(); + } + else + { + this->ComputeParameters(); + this->UpdateSharedDataParameters(); + } +} + +template < class TInput, + class TFeature, + class TSharedData > +typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData >::TimeStepType +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ComputeGlobalTimeStep(void *GlobalData) const +{ +/* Computing the time-step for stable curve evolution */ + + TimeStepType dt = 0.0; + + GlobalDataStruct *d = (GlobalDataStruct *)GlobalData; + + if (vnl_math_abs(d->m_MaxCurvatureChange) > vnl_math::eps) + { + if (d->m_MaxGlobalChange > vnl_math::eps) + { + dt = vnl_math_min( ( this->m_WaveDT / d->m_MaxGlobalChange ), + ( this->m_DT / d->m_MaxCurvatureChange ) ); + } + else + { + dt = this->m_DT / d->m_MaxCurvatureChange; + } + } + else + { + if (d->m_MaxGlobalChange > vnl_math::eps) + { + //NOTE: What's the difference between this->m_WaveDT and this->m_DT? + dt = this->m_WaveDT / d->m_MaxGlobalChange; + } + } + + // Reset the values + d->m_MaxCurvatureChange = NumericTraits<ScalarValueType>::Zero; + d->m_MaxGlobalChange = NumericTraits<ScalarValueType>::Zero; + + return dt; +} + +template < class TInput, + class TFeature, class TSharedData > +typename RegionBasedLevelSetFunction< TInput, + TFeature, TSharedData >:: +ScalarValueType +RegionBasedLevelSetFunction< TInput, + TFeature, TSharedData >:: +ComputeCurvatureTerm( + const NeighborhoodType &itkNotUsed(neighborhood), + const FloatOffsetType &itkNotUsed(offset), GlobalDataStruct *gd) +{ + // Calculate the mean curvature + ScalarValueType curvature_term = NumericTraits<ScalarValueType>::Zero; + + unsigned int i, j; + + for (i = 0; i < ImageDimension; i++) + { + for(j = 0; j < ImageDimension; j++) + { + if(j != i) + { + curvature_term -= gd->m_dx[i] * gd->m_dx[j] * gd->m_dxy[i][j]; + curvature_term += gd->m_dxy[j][j] * gd->m_dx[i] * gd->m_dx[i]; + } + } + } + + if( gd->m_GradMagSqr > vnl_math::eps ) + { + return (curvature_term / gd->m_GradMagSqr ); + } + else + { + return 0.; + } +} + +// Compute the Hessian matrix and various other derivatives. Some of these +// derivatives may be used by overloaded virtual functions. +template < class TInput, + class TFeature, + class TSharedData > +void +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ComputeHessian( const NeighborhoodType &it, GlobalDataStruct *gd ) +{ + const ScalarValueType inputValue = it.GetCenterPixel(); + + gd->m_GradMagSqr = 0.; + unsigned int i, j; + + for (i = 0; i < ImageDimension; i++) + { + const unsigned int positionA = + static_cast< unsigned int >( this->m_Center + this->m_xStride[i] ); + const unsigned int positionB = + static_cast< unsigned int >( this->m_Center - this->m_xStride[i] ); + + gd->m_dx[i] = 0.5 * ( it.GetPixel( positionA ) - it.GetPixel( positionB ) ); + gd->m_dxy[i][i] = + it.GetPixel( positionA ) + it.GetPixel( positionB ) - 2.0 * inputValue; + gd->m_dx_forward[i] = it.GetPixel( positionA ) - inputValue; + gd->m_dx_backward[i] = inputValue - it.GetPixel( positionB ); + gd->m_GradMagSqr += gd->m_dx[i] * gd->m_dx[i]; + + for (j = i+1; j < ImageDimension; j++ ) + { + const unsigned int positionAa = static_cast<unsigned int>( + this->m_Center - this->m_xStride[i] - this->m_xStride[j] ); + const unsigned int positionBa = static_cast<unsigned int>( + this->m_Center - this->m_xStride[i] + this->m_xStride[j] ); + const unsigned int positionCa = static_cast<unsigned int>( + this->m_Center + this->m_xStride[i] - this->m_xStride[j] ); + const unsigned int positionDa = static_cast<unsigned int>( + this->m_Center + this->m_xStride[i] + this->m_xStride[j] ); + + gd->m_dxy[i][j] = gd->m_dxy[j][i] = 0.25 *( + it.GetPixel( positionAa ) - + it.GetPixel( positionBa ) - + it.GetPixel( positionCa ) + + it.GetPixel( positionDa ) ); + } + } +} + +template < class TInput, + class TFeature, + class TSharedData > +typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData >::PixelType +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ComputeUpdate( const NeighborhoodType &it, void *globalData, + const FloatOffsetType& offset ) +{ + // Access the neighborhood center pixel of phi + const ScalarValueType inputValue = it.GetCenterPixel(); + + ScalarValueType laplacian_term = 0.; + ScalarValueType curvature_term = 0.; + ScalarValueType curvature = 0.; + ScalarValueType globalTerm = 0.; + + // Access the global data structure + GlobalDataStruct *gd = (GlobalDataStruct *)globalData; + + ComputeHessian( it, gd ); + + ScalarValueType dh = m_DomainFunction->EvaluateDerivative( - inputValue ); + + // Computing the curvature term + // Used to regularized using the length of contour + if ( ( dh != 0. ) && + ( this->m_CurvatureWeight != NumericTraits< ScalarValueType >::Zero ) ) + { + //NOTE: Why the curvature_term is multiplied by gd->m_GradMagSqr? + //NOTE: in ComputeCurvatureTerm the result has been divided by gd->m_GradMagSqr... + //NOTE: According to the definition of the mean curavture it must not be, so + // I commented this product + curvature = this->ComputeCurvatureTerm( it, offset, gd ); + curvature_term *= this->m_CurvatureWeight * //gd->m_GradMagSqr * + this->CurvatureSpeed(it, offset) * + dh; + + gd->m_MaxCurvatureChange = + vnl_math_max( gd->m_MaxCurvatureChange, vnl_math_abs( curvature_term ) ); + } + + // Computing the laplacian term + // Used in maintaining squared distance function + if( this->m_LaplacianSmoothingWeight != NumericTraits<ScalarValueType>::Zero) + { + if( this->m_CurvatureWeight != NumericTraits< ScalarValueType >::Zero ) + { + laplacian_term = this->ComputeLaplacian( gd ) - curvature; + } + else + { + laplacian_term = this->ComputeLaplacianTerm( it, offset, gd ); + } + // Use the laplacian to maintain signed distance function + + laplacian_term *= this->m_LaplacianSmoothingWeight * + this->LaplacianSmoothingSpeed(it,offset, gd); + } + + // Update value from curvature length and laplacian term + PixelType updateVal = + static_cast< PixelType >( curvature_term + laplacian_term ); + + /* Compute the globalTerm - rms difference of image with c_0 or c_1*/ + if ( dh != 0. ) + { + globalTerm = dh * this->ComputeGlobalTerm( inputValue, it.GetIndex() ); + } + + /* Final update value is the local terms of curvature lengths and laplacian + squared distances - global terms of rms differences of image and piecewise + constant regions*/ + updateVal = updateVal - globalTerm; + + /* If MaxGlobalChange recorded is lower than the current globalTerm */ + if( vnl_math_abs( gd->m_MaxGlobalChange) < vnl_math_abs( globalTerm ) ) + { + gd->m_MaxGlobalChange = globalTerm; + } + + return updateVal; +} + +template < class TInput, class TFeature, class TSharedData > +typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ScalarValueType +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ComputeLaplacianTerm( const NeighborhoodType &neighborhood, + const FloatOffsetType &offset, GlobalDataStruct *gd ) +{ + ScalarValueType laplacian = ComputeLaplacian( gd ); + ScalarValueType curvature = ComputeCurvatureTerm( neighborhood, offset, gd ); + + return laplacian - curvature; +} + + +template < class TInput, class TFeature, class TSharedData > +typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ScalarValueType +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ComputeLaplacian( GlobalDataStruct *gd ) +{ + ScalarValueType laplacian = 0.; + + // Compute the laplacian using the existing second derivative values + for( unsigned int i = 0; i < ImageDimension; i++ ) + { + laplacian += gd->m_dxy[i][i]; + } + + return laplacian; +} + +template < class TInput, class TFeature, class TSharedData > +typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ScalarValueType +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ComputeVolumeRegularizationTerm( ) +{ + return 2 * ( this->m_SharedData->m_LevelSetDataPointerVector[this->m_FunctionId]->m_WeightedNumberOfPixelsInsideLevelSet - this->m_Volume ); +} + +/* Computes the fidelity term (eg: (intensity - mean)2 ). +Most of the code is concerned with using the appropriate combination +of Heaviside and dirac delta for each part of the fidelity term. +- the final dH is the dirac delta term corresponding to the current +level set we are updating. */ +template < class TInput, class TFeature, class TSharedData > +typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ScalarValueType +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::ComputeGlobalTerm( +const ScalarValueType& itkNotUsed( inputPixel ), +const InputIndexType& inputIndex ) +{ + ScalarValueType product = 1; // computes if it belongs to background + + // Assuming only 1 level set function to be present + FeatureIndexType featIndex = static_cast< FeatureIndexType >( inputIndex ); + + const FeaturePixelType featureVal = + this->m_FeatureImage->GetPixel ( inputIndex ); + + ScalarValueType overlapTerm = 0.; + + // This conditional statement computes the amount of overlap s + // and the presence of background pr + if ( ( this->m_SharedData->m_FunctionCount > 1 ) && + ( this->m_OverlapPenaltyWeight != NumericTraits<ScalarValueType>::Zero ) ) + { + featIndex = this->m_SharedData->m_LevelSetDataPointerVector[this->m_FunctionId]->GetFeatureIndex( inputIndex ); + overlapTerm = this->m_OverlapPenaltyWeight * + ComputeOverlapParameters( featIndex, product ); + } + + ScalarValueType inTerm = this->m_Lambda1 * this->ComputeInternalTerm( featureVal, featIndex ); + ScalarValueType outTerm = this->m_Lambda2 * product * this->ComputeExternalTerm( featureVal, featIndex ); + + ScalarValueType regularizationTerm = this->m_VolumeMatchingWeight * + ComputeVolumeRegularizationTerm() - this->m_AreaWeight; + + //NOTE: regularizationTerm here MUST take into account the curvature term!!! + + ScalarValueType globalTerm = - inTerm + outTerm - overlapTerm - regularizationTerm; + + return globalTerm; +} + +} // end namespace + +#endif diff --git a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.h b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.h new file mode 100644 index 0000000000..0ff3b651d1 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.h @@ -0,0 +1,149 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRegionBasedLevelSetFunctionData.h,v $ + Language: C++ + Date: $Date: 2009-05-14 21:46:48 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRegionBasedLevelSetFunctionData_h +#define __itkRegionBasedLevelSetFunctionData_h + +#include "itkLightObject.h" + +#include "itkVector.h" +#include "itkListSample.h" +#include "itkKdTree.h" +#include "itkKdTreeGenerator.h" + +#include "itkImageRegionIterator.h" +#include "itkImageRegionIteratorWithIndex.h" + +namespace itk +{ + +/** \class RegionBasedLevelSetFunctionData + * + * \brief Helper class used to share data in the ScalarChanAndVeseLevelSetFunction. + * + * This class holds cache data used during the computation of the LevelSet updates. + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template < class TInputImage, class TFeatureImage > +class RegionBasedLevelSetFunctionData : public LightObject +{ +public: + + typedef RegionBasedLevelSetFunctionData Self; + typedef LightObject Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + itkStaticConstMacro( ImageDimension, unsigned int, TFeatureImage::ImageDimension ); + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + itkTypeMacro(RegionBasedLevelSetFunctionData, LightObject); + + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::PixelType InputPixelType; + typedef typename InputImageType::RegionType InputRegionType; + typedef typename InputImageType::SizeType InputSizeType; + typedef typename InputSizeType::SizeValueType InputSizeValueType; + typedef typename InputImageType::SpacingType InputSpacingType; + typedef typename InputImageType::IndexType InputIndexType; + typedef typename InputIndexType::IndexValueType InputIndexValueType; + typedef typename InputImageType::PointType InputPointType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeaturePixelType; + typedef typename FeatureImageType::RegionType FeatureRegionType; + typedef typename FeatureImageType::SizeType FeatureSizeType; + typedef typename FeatureSizeType::SizeValueType FeatureSizeValueType; + typedef typename FeatureImageType::SpacingType FeatureSpacingType; + typedef typename FeatureImageType::IndexType FeatureIndexType; + typedef typename FeatureImageType::PointType FeaturePointType; + + void CreateHeavisideFunctionOfLevelSetImage( const InputImageType * image ); + + template< class TIndex > + bool VerifyInsideRegion( const TIndex& featureIndex ) + { + for( unsigned int j = 0; j < ImageDimension; j++ ) + { + if( (featureIndex[j] < static_cast< InputIndexValueType >(this->m_Start[j]) ) + || (featureIndex[j] > static_cast< InputIndexValueType >(this->m_End[j])) ) + { + return false; + } + } + return true; + } + + InputIndexType GetIndex( const FeatureIndexType& featureIndex ); + + FeatureIndexType GetFeatureIndex( const InputIndexType& inputIndex ); + + + double m_WeightedNumberOfPixelsInsideLevelSet; + double m_WeightedNumberOfPixelsOutsideLevelSet; + + InputImagePointer m_HeavisideFunctionOfLevelSetImage; + InputIndexType m_Start; + InputIndexType m_End; + +protected: + RegionBasedLevelSetFunctionData(); + virtual ~RegionBasedLevelSetFunctionData() {} + +private: + RegionBasedLevelSetFunctionData(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} //end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkRegionBasedLevelSetFunctionData.txx" +#endif +#endif diff --git a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.txx b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.txx new file mode 100644 index 0000000000..a2146d645d --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.txx @@ -0,0 +1,89 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRegionBasedLevelSetFunctionData.txx,v $ + Language: C++ + Date: $Date: 2009-05-14 21:46:48 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRegionBasedLevelSetFunctionData_txx +#define __itkRegionBasedLevelSetFunctionData_txx + +#include "itkRegionBasedLevelSetFunctionData.h" + +namespace itk +{ + +template < class TInputImage, class TFeatureImage > +RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage > +::RegionBasedLevelSetFunctionData() +{ + m_WeightedNumberOfPixelsInsideLevelSet = 0.; + m_WeightedNumberOfPixelsOutsideLevelSet = 0.; + + m_HeavisideFunctionOfLevelSetImage = 0; +} + +template < class TInputImage, class TFeatureImage > +void +RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage > +::CreateHeavisideFunctionOfLevelSetImage( const InputImageType * image ) +{ + const InputRegionType region = image->GetLargestPossibleRegion(); + this->m_HeavisideFunctionOfLevelSetImage = InputImageType::New(); + this->m_HeavisideFunctionOfLevelSetImage->CopyInformation( image ); + this->m_HeavisideFunctionOfLevelSetImage->SetRegions( region ); + this->m_HeavisideFunctionOfLevelSetImage->Allocate(); + this->m_HeavisideFunctionOfLevelSetImage->FillBuffer( 0 ); + + const InputPointType origin = image->GetOrigin(); + const InputSpacingType spacing = image->GetSpacing(); + + for( unsigned int i = 0; i < ImageDimension; i++ ) + { + // FIXME : This computation of Start index is suspicious. + // See similar computation in the Shrink image filter. + this->m_Start[i] = static_cast< InputIndexValueType >( origin[i] / spacing[i] ); + this->m_End[i] = this->m_Start[i] + static_cast< InputIndexValueType >( region.GetSize()[i] ) - 1; + } +} + +template < class TInputImage, class TFeatureImage > +typename RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage >::InputIndexType +RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage > +::GetIndex( const FeatureIndexType& featureIndex ) +{ + InputIndexType index; + for( unsigned int i = 0; i < ImageDimension; i++ ) + { + index[i] = featureIndex[i] - static_cast< InputIndexValueType >( this->m_Start[i] ); + } + + return index; +} + +template < class TInputImage, class TFeatureImage > +typename RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage >::FeatureIndexType +RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage > +::GetFeatureIndex( const InputIndexType& inputIndex ) +{ + FeatureIndexType index; + for( unsigned int i = 0; i < ImageDimension; i++ ) + { + index[i] = inputIndex[i] + static_cast< InputIndexValueType >( this->m_Start[i] ); + } + + return index; +} + +} //end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionSharedData.h b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionSharedData.h new file mode 100644 index 0000000000..bd617502e3 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionSharedData.h @@ -0,0 +1,188 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRegionBasedLevelSetFunctionSharedData.h,v $ + Language: C++ + Date: $Date: 2009-05-14 21:46:49 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRegionBasedLevelSetFunctionSharedData_h +#define __itkRegionBasedLevelSetFunctionSharedData_h + +#include "itkLightObject.h" + +#include "itkVector.h" +#include "itkListSample.h" +#include "itkKdTree.h" +#include "itkKdTreeGenerator.h" + +#include "itkImageRegionIterator.h" +#include "itkImageRegionIteratorWithIndex.h" + +namespace itk +{ + +/** \class RegionBasedLevelSetFunctionSharedData + * + * \brief Helper class used to share data in the ScalarChanAndVeseLevelSetFunction. + * + * This class holds cache data used during the computation of the LevelSet updates. + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template < class TInputImage, class TFeatureImage, class TSingleData > +class RegionBasedLevelSetFunctionSharedData : public LightObject +{ +public: + + typedef RegionBasedLevelSetFunctionSharedData Self; + typedef LightObject Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + itkStaticConstMacro( ImageDimension, unsigned int, TFeatureImage::ImageDimension ); + + itkTypeMacro(RegionBasedLevelSetFunctionSharedData, LightObject); + + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::PixelType InputPixelType; + typedef typename InputImageType::RegionType InputRegionType; + typedef typename InputImageType::SizeType InputSizeType; + typedef typename InputSizeType::SizeValueType InputSizeValueType; + typedef typename InputImageType::SpacingType InputSpacingType; + typedef typename InputImageType::IndexType InputIndexType; + typedef typename InputIndexType::IndexValueType InputIndexValueType; + typedef typename InputImageType::PointType InputPointType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeaturePixelType; + typedef typename FeatureImageType::RegionType FeatureRegionType; + typedef typename FeatureImageType::SizeType FeatureSizeType; + typedef typename FeatureSizeType::SizeValueType FeatureSizeValueType; + typedef typename FeatureImageType::SpacingType FeatureSpacingType; + typedef typename FeatureImageType::IndexType FeatureIndexType; + typedef typename FeatureImageType::PointType FeaturePointType; + + typedef std::list< unsigned int > ListPixelType; + typedef Image< ListPixelType, itkGetStaticConstMacro(ImageDimension) > + ListImageType; + typedef typename ListImageType::Pointer ListImagePointer; + typedef typename ListImageType::ConstPointer ListImageConstPointer; + typedef typename ListImageType::RegionType ListRegionType; + typedef typename ListImageType::SizeType ListSizeType; + typedef typename ListSizeType::SizeValueType ListSizeValueType; + typedef typename ListImageType::SpacingType ListSpacingType; + typedef typename ListImageType::IndexType ListIndexType; + typedef typename ListIndexType::IndexValueType ListIndexValueType; + typedef typename ListImageType::PointType ListPointType; + typedef ImageRegionIteratorWithIndex< ListImageType > ListIteratorType; + + typedef Vector< float, itkGetStaticConstMacro(ImageDimension) > + CentroidVectorType; + typedef itk::Statistics::ListSample< CentroidVectorType > SampleType; + typedef itk::Statistics::KdTreeGenerator< SampleType > TreeGeneratorType; + typedef typename TreeGeneratorType::Pointer TreePointer; + typedef typename TreeGeneratorType::KdTreeType TreeType; + typedef typename TreeType::Pointer KdTreePointer; + + typedef TSingleData LevelSetDataType; + typedef typename LevelSetDataType::Pointer LevelSetDataPointer; + typedef std::vector< LevelSetDataPointer > LevelSetDataPointerVector; + typedef typename LevelSetDataPointerVector::iterator LevelSetDataPointerVectorIterator; + + void SetFunctionCount( const unsigned int& n ) + { + this->m_FunctionCount = n; + this->m_LevelSetDataPointerVector.resize( n, 0 ); + + LevelSetDataPointerVectorIterator it = m_LevelSetDataPointerVector.begin(); + LevelSetDataPointerVectorIterator end = m_LevelSetDataPointerVector.end(); + while( it != end ) + { + (*it) = LevelSetDataType::New(); + it++; + } + } + + void SetNumberOfNeighbors( const unsigned int& n ) + { + this->m_NumberOfNeighbors = n; + } + + void CreateHeavisideFunctionOfLevelSetImage( const unsigned int& j, const InputImageType * image ) + { + m_LevelSetDataPointerVector[j]->CreateHeavisideFunctionOfLevelSetImage( image ); + } + + void SetKdTree( KdTreePointer kdtree ) + { + this->m_KdTree = kdtree; + } + + void AllocateListImage( const FeatureImageType * featureImage ) + { + this->m_NearestNeighborListImage = ListImageType::New(); + this->m_NearestNeighborListImage->CopyInformation( featureImage ); + this->m_NearestNeighborListImage->SetRegions( featureImage->GetLargestPossibleRegion() ); + this->m_NearestNeighborListImage->Allocate(); + } + + virtual void PopulateListImage() = 0; + + LevelSetDataPointerVector m_LevelSetDataPointerVector; + + unsigned int m_FunctionCount; + unsigned int m_NumberOfNeighbors; + ListImagePointer m_NearestNeighborListImage; + KdTreePointer m_KdTree; + +protected: + RegionBasedLevelSetFunctionSharedData() : m_NumberOfNeighbors( 6 ), m_KdTree( 0 ){} + ~RegionBasedLevelSetFunctionSharedData(){} + +private: + RegionBasedLevelSetFunctionSharedData(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} //end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkRegularizedHeavisideStepFunction.h b/Utilities/ITK/Code/Review/itkRegularizedHeavisideStepFunction.h new file mode 100644 index 0000000000..af85adb4a4 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRegularizedHeavisideStepFunction.h @@ -0,0 +1,117 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRegularizedHeavisideStepFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-09 21:06:28 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkRegularizedHeavisideStepFunction_h +#define __itkRegularizedHeavisideStepFunction_h + +#include "itkHeavisideStepFunctionBase.h" +#include "itkNumericTraits.h" +#include "vnl/vnl_math.h" + +namespace itk +{ + +/** \class RegularizedHeavisideStepFunction + * + * \brief Base class of the Regularized (smoothed) Heaviside functions. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template< class TInput = float, class TOutput = double > +class RegularizedHeavisideStepFunction : public HeavisideStepFunctionBase< TInput, TOutput > +{ +public: + typedef RegularizedHeavisideStepFunction Self; + typedef HeavisideStepFunctionBase< TInput, TOutput > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::InputType InputType; + typedef typename Superclass::OutputType OutputType; + + typedef typename NumericTraits< InputType >::RealType RealType; + + /** Evaluate at the specified input position */ + virtual OutputType Evaluate( const InputType& input ) const = 0; + + /** Evaluate the derivative at the specified input position */ + virtual OutputType EvaluateDerivative( const InputType& input ) const = 0; + + void SetEpsilon( const RealType & ieps ) + { + this->m_Epsilon = ieps; + + if ( ieps > vnl_math::eps ) + { + m_OneOverEpsilon = 1.0 / ieps; + } + else + { + itkGenericExceptionMacro("ERROR: Epsilon needs to be greater than " << vnl_math::eps ); + } + } + + RealType GetEpsilon() const + { + return this->m_Epsilon; + } + + RealType GetOneOverEpsilon() const + { + return this->m_OneOverEpsilon; + } + +protected: + RegularizedHeavisideStepFunction() + { + this->m_Epsilon = 1.0; + this->m_OneOverEpsilon = 1.0; + } + + virtual ~RegularizedHeavisideStepFunction() {} + +private: + RegularizedHeavisideStepFunction(const Self& ); //purposely not implemented + void operator=(const Self& ); //purposely not implemented + + RealType m_Epsilon; + RealType m_OneOverEpsilon; +}; + +} + +#endif diff --git a/Utilities/ITK/Code/Review/itkRobustAutomaticThresholdCalculator.h b/Utilities/ITK/Code/Review/itkRobustAutomaticThresholdCalculator.h index 06ebdc0cb7..7746684646 100644 --- a/Utilities/ITK/Code/Review/itkRobustAutomaticThresholdCalculator.h +++ b/Utilities/ITK/Code/Review/itkRobustAutomaticThresholdCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRobustAutomaticThresholdCalculator.h,v $ Language: C++ - Date: $Date: 2009-02-18 14:34:10 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -82,7 +82,7 @@ public: } itkSetMacro(Pow, double); - itkGetMacro(Pow, double); + itkGetConstMacro(Pow, double); /** Compute moments of a new or modified image. * This method computes the moments of the image given as a diff --git a/Utilities/ITK/Code/Review/itkRobustAutomaticThresholdImageFilter.h b/Utilities/ITK/Code/Review/itkRobustAutomaticThresholdImageFilter.h index f61b5e10c5..58f572a715 100644 --- a/Utilities/ITK/Code/Review/itkRobustAutomaticThresholdImageFilter.h +++ b/Utilities/ITK/Code/Review/itkRobustAutomaticThresholdImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRobustAutomaticThresholdImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-18 14:37:10 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -91,20 +91,20 @@ public: itkSetMacro(OutsideValue,OutputPixelType); /** Get the "outside" pixel value. */ - itkGetMacro(OutsideValue,OutputPixelType); + itkGetConstMacro(OutsideValue,OutputPixelType); /** Set the "inside" pixel value. The default value * NumericTraits<OutputPixelType>::max() */ itkSetMacro(InsideValue,OutputPixelType); /** Get the "inside" pixel value. */ - itkGetMacro(InsideValue,OutputPixelType); + itkGetConstMacro(InsideValue,OutputPixelType); /** Get the computed threshold. */ - itkGetMacro(Threshold,InputPixelType); + itkGetConstMacro(Threshold,InputPixelType); itkSetMacro(Pow, double); - itkGetMacro(Pow, double); + itkGetConstMacro(Pow, double); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.h b/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.h new file mode 100644 index 0000000000..bee35018fb --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.h @@ -0,0 +1,156 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarChanAndVeseDenseLevelSetImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-16 12:35:10 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarChanAndVeseDenseLevelSetImageFilter_h +#define __itkScalarChanAndVeseDenseLevelSetImageFilter_h + +#include "itkMultiphaseDenseFiniteDifferenceImageFilter.h" +#include "itkRegionOfInterestImageFilter.h" + + +/** \class ScalarChanAndVeseDenseLevelSetImageFilter + * \brief Dense implementation of the Chan and Vese multiphase level set image filter. + * + * + * This code was adapted from the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + */ +namespace itk +{ +template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, + class TSharedData > +class ITK_EXPORT ScalarChanAndVeseDenseLevelSetImageFilter: + public MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction > +{ +public: + + typedef ScalarChanAndVeseDenseLevelSetImageFilter Self; + typedef MultiphaseDenseFiniteDifferenceImageFilter< + TInputImage, TOutputImage, TFunction > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( ScalarChanAndVeseDenseLevelSetImageFilter, + MultiphaseDenseFiniteDifferenceImageFilter ); + + itkStaticConstMacro( ImageDimension, unsigned int, TInputImage::ImageDimension ); + + /** Inherited typedef from the superclass. */ + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::PixelType FeaturePixelType; + typedef typename FeatureImageType::IndexType FeatureIndexType; + typedef typename FeatureIndexType::IndexValueType FeatureIndexValueType; + typedef typename FeatureImageType::RegionType FeatureRegionType; + + /** Output image type typedefs */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::InputSpacingType InputSpacingType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::ValueType ValueType; + typedef typename OutputImageType::IndexType IndexType; + typedef typename OutputImageType::PixelType OutputPixelType; + + typedef typename Superclass::TimeStepType TimeStepType; + + typedef typename Superclass::FiniteDifferenceFunctionType FiniteDifferenceFunctionType; + + typedef TFunction FunctionType; + typedef typename FunctionType::Pointer FunctionPointer; + + typedef TSharedData SharedDataType; + typedef typename SharedDataType::Pointer SharedDataPointer; + + typedef RegionOfInterestImageFilter< + FeatureImageType, FeatureImageType > ROIFilterType; + typedef typename ROIFilterType::Pointer ROIFilterPointer; + + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(OutputHasNumericTraitsCheck, + (Concept::HasNumericTraits<OutputPixelType>) ); + /** End concept checking */ +#endif + + /** Set/Get the feature image to be used for speed function of the level set + * equation. Equivalent to calling Set/GetInput(1, ..) */ + virtual void SetFeatureImage(const FeatureImageType *f) + { + this->ProcessObject::SetNthInput( 0, const_cast< FeatureImageType * >(f) ); + } + + virtual const FeatureImageType * GetFeatureImage() const + { + return (static_cast<const FeatureImageType *>(this->ProcessObject::GetInput(0))); + } + +protected: + ScalarChanAndVeseDenseLevelSetImageFilter() + { + this->m_SharedData = SharedDataType::New(); + } + ~ScalarChanAndVeseDenseLevelSetImageFilter(){} + + SharedDataPointer m_SharedData; + + virtual void Initialize(); + virtual void InitializeIteration(); + +private: + ScalarChanAndVeseDenseLevelSetImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} //end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScalarChanAndVeseDenseLevelSetImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.txx b/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.txx new file mode 100644 index 0000000000..10efbe1028 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.txx @@ -0,0 +1,134 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarChanAndVeseDenseLevelSetImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-20 22:03:45 $ + Version: $Revision: 1.5 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarChanAndVeseDenseLevelSetImageFilter_txx +#define __itkScalarChanAndVeseDenseLevelSetImageFilter_txx + +#include "itkScalarChanAndVeseDenseLevelSetImageFilter.h" + +namespace itk +{ +template < class TInput, + class TFeature, + class TFunction, + class TOutputPixel, + class TSharedData > +void +ScalarChanAndVeseDenseLevelSetImageFilter< TInput, TFeature, + TFunction, TOutputPixel, TSharedData >:: +Initialize() +{ + // Set the feature image for the individual level-set functions + for( unsigned int i = 0; i < this->m_FunctionCount; i++) + { + InputImagePointer input = this->m_LevelSet[i]; + InputPointType origin = input->GetOrigin(); + InputSpacingType spacing = input->GetSpacing(); + + // In the context of the global coordinates + FeatureIndexType start; + + // FIXME: This is suspicious code. It looks like we should + // have used first IndexToPhysicalPoint and then PhysicalPointToIndex + // as it was done in the ShrinkImagefilter... + for ( unsigned int j = 0; j < ImageDimension; j++ ) + { + start[j] = static_cast<FeatureIndexValueType>( origin[j]/spacing[j] ); + } + + // Defining roi region + FeatureRegionType region; + region.SetSize( input->GetLargestPossibleRegion().GetSize() ); + region.SetIndex( start ); + + // Initialize the ROI filter with the feature image + ROIFilterPointer roi = ROIFilterType::New(); + roi->SetInput( this->GetFeatureImage() ); + roi->SetRegionOfInterest( region ); + roi->Update(); + + // Assign roi output + FeatureImagePointer feature = roi->GetOutput(); + this->m_DifferenceFunctions[i]->SetFeatureImage( feature ); + this->m_DifferenceFunctions[i]->SetInitialImage( input ); + } + + // Initialize the function count in shared data + this->m_SharedData->SetFunctionCount ( this->m_FunctionCount ); + + // Set the KdTree pointer + if ( this->m_KdTree ) + { + this->m_SharedData->SetKdTree( this->m_KdTree ); + } + + for ( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_DifferenceFunctions[i]->SetFunctionId( i ); + + this->m_SharedData->CreateHeavisideFunctionOfLevelSetImage ( i, this->m_LevelSet[i] ); + + // Share the this->m_SharedData structure + this->m_DifferenceFunctions[i]->SetSharedData( this->m_SharedData ); + } + + this->m_SharedData->AllocateListImage( this->GetFeatureImage() ); + + this->m_SharedData->PopulateListImage(); + + this->Superclass::Initialize(); + + for (unsigned int i = 0; i < this->m_FunctionCount; i++) + { + this->m_DifferenceFunctions[i]->UpdateSharedData(true); + } + + for ( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_DifferenceFunctions[i]->UpdateSharedData( false ); + } +} + + +/** Overrides parent implementation */ +// This function is called at the end of each iteration +template < class TInput, + class TFeature, + class TFunction, + class TOutputPixel, + class TSharedData > +void +ScalarChanAndVeseDenseLevelSetImageFilter< TInput, TFeature, TFunction, TOutputPixel, TSharedData > +::InitializeIteration() +{ + this->Superclass::InitializeIteration(); + + for( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_DifferenceFunctions[i]->SetInitialImage( this->m_LevelSet[i] ); + this->m_DifferenceFunctions[i]->UpdateSharedData ( true ); + } + + for( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_DifferenceFunctions[i]->UpdateSharedData ( false ); + } +} + +} /* end namespace itk */ + +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.h b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.h new file mode 100644 index 0000000000..a612a1e9cb --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.h @@ -0,0 +1,149 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarChanAndVeseLevelSetFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-14 21:46:50 $ + Version: $Revision: 1.8 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarChanAndVeseLevelSetFunction_h +#define __itkScalarChanAndVeseLevelSetFunction_h + +#include "itkScalarRegionBasedLevelSetFunction.h" + +namespace itk { + +/** \class ScalarChanAndVeseLevelSetFunction + * + * \brief LevelSet function that computes a speed image based on regional integrals of probabilities + * + * This class implements a level set function that computes the speed image by + * integrating values on the image domain. + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template < class TInputImage, +class TFeatureImage, +class TSharedData > +class ITK_EXPORT ScalarChanAndVeseLevelSetFunction +: public ScalarRegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +{ +public: + typedef ScalarChanAndVeseLevelSetFunction Self; + typedef ScalarRegionBasedLevelSetFunction< + TInputImage, TFeatureImage, TSharedData > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods) */ + itkTypeMacro( ScalarChanAndVeseLevelSetFunction, ScalarLevelSetFunction ); + + itkStaticConstMacro( ImageDimension, unsigned int, TFeatureImage::ImageDimension ); + + typedef TInputImage InputImageType; + typedef typename Superclass::InputImageConstPointer InputImageConstPointer; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputPixelType InputPixelType; + typedef typename Superclass::InputIndexType InputIndexType; + typedef typename Superclass::InputIndexValueType InputIndexValueType; + typedef typename Superclass::InputSizeType InputSizeType; + typedef typename Superclass::InputSizeValueType InputSizeValueType; + typedef typename Superclass::InputRegionType InputRegionType; + typedef typename Superclass::InputPointType InputPointType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename Superclass::FeaturePixelType FeaturePixelType; + typedef typename Superclass::FeatureIndexType FeatureIndexType; + typedef typename Superclass::FeatureOffsetType FeatureOffsetType; + + typedef typename Superclass::ScalarValueType ScalarValueType; + typedef typename Superclass::NeighborhoodType NeighborhoodType; + typedef typename Superclass::FloatOffsetType FloatOffsetType; + typedef typename Superclass::RadiusType RadiusType; + typedef typename Superclass::TimeStepType TimeStepType; + typedef typename Superclass::GlobalDataStruct GlobalDataStruct; + typedef typename Superclass::PixelType PixelType; + typedef typename Superclass::VectorType VectorType; + + typedef typename Superclass::SharedDataType SharedDataType; + typedef typename Superclass::SharedDataPointer SharedDataPointer; + + typedef typename Superclass::ImageIteratorType ImageIteratorType; + typedef typename Superclass::ConstImageIteratorType ConstImageIteratorType; + typedef typename Superclass::FeatureImageIteratorType FeatureImageIteratorType; + typedef typename Superclass::ConstFeatureIteratorType ConstFeatureIteratorType; + + typedef typename Superclass::ListPixelType ListPixelType; + typedef typename Superclass::ListPixelConstIterator ListPixelConstIterator; + typedef typename Superclass::ListPixelIterator ListPixelIterator; + typedef typename Superclass::ListImageType ListImageType; + +protected: + ScalarChanAndVeseLevelSetFunction() : Superclass() {} + ~ScalarChanAndVeseLevelSetFunction(){} + + void ComputeParameters(); + void UpdateSharedDataParameters(); + + ScalarValueType ComputeInternalTerm( const FeaturePixelType& iValue, + const FeatureIndexType& iIdx ); + + ScalarValueType ComputeExternalTerm( const FeaturePixelType& iValue, + const FeatureIndexType& iIdx ); + + void UpdateSharedDataInsideParameters( const unsigned int& iId, + const bool& iBool, const FeaturePixelType&, const ScalarValueType& ); + void UpdateSharedDataOutsideParameters( const unsigned int& iId, + const bool& iBool, const FeaturePixelType&, const ScalarValueType& ); + +private: + ScalarChanAndVeseLevelSetFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScalarChanAndVeseLevelSetFunction.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.txx b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.txx new file mode 100644 index 0000000000..a8ac2d7c9a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.txx @@ -0,0 +1,194 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarChanAndVeseLevelSetFunction.txx,v $ + Language: C++ + Date: $Date: 2009-05-22 16:46:18 $ + Version: $Revision: 1.15 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarChanAndVeseLevelSetFunction_txx +#define __itkScalarChanAndVeseLevelSetFunction_txx + +#include "itkScalarChanAndVeseLevelSetFunction.h" + +namespace itk { + +template < class TInputImage, class TFeatureImage, class TSharedData > +void +ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +::UpdateSharedDataParameters() +{ + unsigned int fId = this->m_FunctionId; + + if ( this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsInsideLevelSet > vnl_math::eps ) + { + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_ForegroundConstantValues = + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedSumOfPixelValuesInsideLevelSet / + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsOutsideLevelSet; + } + else + { + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_ForegroundConstantValues = 0; + } + + if ( this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsOutsideLevelSet > vnl_math::eps ) + { + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_BackgroundConstantValues = + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedSumOfPixelValuesOutsideLevelSet / + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsOutsideLevelSet; + } + else + { + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_BackgroundConstantValues = 0; + } +} + +template < class TInputImage, class TFeatureImage, class TSharedData > +void +ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +::UpdateSharedDataInsideParameters( const unsigned int& iId, + const bool& iA, const FeaturePixelType& iVal, const ScalarValueType& iH ) +{ + if( iA ) + { + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsInsideLevelSet += iH; + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesInsideLevelSet += iVal * iH; + } + else + { + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsInsideLevelSet -= iH; + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesInsideLevelSet -= iVal * iH; + } +} + +template < class TInputImage, class TFeatureImage, class TSharedData > +void +ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +::UpdateSharedDataOutsideParameters( const unsigned int& iId, + const bool& iA, const FeaturePixelType& iVal, const ScalarValueType& iH ) +{ + if( iA ) + { + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsOutsideLevelSet += iH; + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesOutsideLevelSet += iVal * iH; + } + else + { + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsOutsideLevelSet -= iH; + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesOutsideLevelSet -= iVal * iH; + } +} + +/* Calculates the numerator and denominator for c_i for each region. As part of +the optimization, it is called once at the beginning of the code, and then the +cNum and cDen are updated during the evolution without iterating through the +entire image. */ +template < class TInputImage, class TFeatureImage, class TSharedData > +void +ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +::ComputeParameters() +{ + unsigned int fId = this->m_FunctionId; + + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsInsideLevelSet = 0; + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedSumOfPixelValuesInsideLevelSet = 0; + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_ForegroundConstantValues = 0; + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsOutsideLevelSet = 0; + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedSumOfPixelValuesOutsideLevelSet = 0; + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_BackgroundConstantValues = 0; + + FeatureImageConstPointer featureImage = this->m_FeatureImage; + + ImageIteratorType It( this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_HeavisideFunctionOfLevelSetImage, + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_HeavisideFunctionOfLevelSetImage->GetLargestPossibleRegion() ); + ConstFeatureIteratorType fIt( this->m_FeatureImage, + this->m_FeatureImage->GetLargestPossibleRegion() ); + + FeaturePixelType featureVal; + FeatureIndexType globalIndex; + InputIndexType itInputIndex, inputIndex; + InputPixelType hVal; + ListPixelType L; + + // Reference: + // Dufour, Shinin, Tajbakhsh, Guillen-Aghion, Olivo-Marin + // Segmenting and Tracking Fluorescent Cells in Dynamic 3-D + // Microscopy With Coupled Active Surfaces + // IEEE Transactions on Image Processing, vol. 14, No 9, September 2005 + // In the paper: + // m_WeightedSumOfPixelValuesInsideLevelSet = \sum I(x) * H(\phi_i(x)) + // m_WeightedNumberOfPixelsInsideLevelSet = \sum H(\phi_i(x)) + // m_WeightedSumOfPixelValuesOutsideLevelSet = \sum \left( I(x) \prod \left( 1 - H(\phi_i(x))\right) \right) + // m_WeightedNumberOfPixelsInsideLevelSet = \sum \prod \left( 1 - H(\phi_i(x))\right) + + for( It.GoToBegin(), fIt.GoToBegin(); !It.IsAtEnd(); + ++It, ++fIt ) + { + featureVal = fIt.Get(); + inputIndex = It.GetIndex(); + InputPixelType prod = 1.; + + globalIndex = this->m_SharedData->m_LevelSetDataPointerVector[fId]->GetFeatureIndex( inputIndex ); + + L = this->m_SharedData->m_NearestNeighborListImage->GetPixel( globalIndex ); + +// bool inBgrnd = true; // assume the pixel is in background + for( ListPixelConstIterator it = L.begin(); it != L.end(); ++it ) + { + itInputIndex = this->m_SharedData->m_LevelSetDataPointerVector[*it]->GetIndex( globalIndex ); + hVal = this->m_SharedData->m_LevelSetDataPointerVector[*it]->m_HeavisideFunctionOfLevelSetImage->GetPixel( itInputIndex ); + prod *= ( 1. - hVal ); + + if (*it == fId) + { + this->m_SharedData->m_LevelSetDataPointerVector[*it]->m_WeightedSumOfPixelValuesInsideLevelSet += featureVal * hVal; + this->m_SharedData->m_LevelSetDataPointerVector[*it]->m_WeightedNumberOfPixelsInsideLevelSet += hVal; + } + } + + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedSumOfPixelValuesOutsideLevelSet += featureVal * prod; + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsOutsideLevelSet += prod; + } +} + + +template < class TInputImage, class TFeatureImage, class TSharedData > +typename ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +::ScalarValueType +ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData >:: +ComputeInternalTerm( const FeaturePixelType& iValue, + const FeatureIndexType& itkNotUsed(iIdx) ) +{ + const unsigned int fId = this->m_FunctionId; + const ScalarValueType cVals = this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_ForegroundConstantValues; + const ScalarValueType t = ( iValue - cVals ); + return t * t; +} + + +template < class TInputImage, class TFeatureImage, class TSharedData > +typename ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +::ScalarValueType +ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +::ComputeExternalTerm( const FeaturePixelType& iValue, + const FeatureIndexType& itkNotUsed(iIdx) ) +{ + const unsigned int fId = this->m_FunctionId; + const ScalarValueType cBgrnd = this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_BackgroundConstantValues; // background + const ScalarValueType t = ( iValue - cBgrnd ); + + return t * t; +} + + +} // end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunctionData.h b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunctionData.h new file mode 100644 index 0000000000..ac20fbb279 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunctionData.h @@ -0,0 +1,123 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarChanAndVeseLevelSetFunctionData.h,v $ + Language: C++ + Date: $Date: 2009-05-14 21:46:50 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarChanAndVeseLevelSetFunctionData_h +#define __itkScalarChanAndVeseLevelSetFunctionData_h + +#include "itkRegionBasedLevelSetFunctionData.h" + +namespace itk +{ + +/** \class ScalarChanAndVeseLevelSetFunctionData + * + * \brief Helper class used to share data in the ScalarChanAndVeseLevelSetFunction. + * + * This class holds cache data used during the computation of the LevelSet updates. + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template < class TInputImage, class TFeatureImage > +class ScalarChanAndVeseLevelSetFunctionData : + public RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage > +{ +public: + + typedef ScalarChanAndVeseLevelSetFunctionData Self; + typedef RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + itkStaticConstMacro( ImageDimension, unsigned int, TFeatureImage::ImageDimension ); + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + itkTypeMacro(ScalarChanAndVeseLevelSetFunctionData, RegionBasedLevelSetFunctionData ); + + typedef TInputImage InputImageType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputImageConstPointer InputImageConstPointer; + typedef typename Superclass::InputPixelType InputPixelType; + typedef typename Superclass::InputRegionType InputRegionType; + typedef typename Superclass::InputSizeType InputSizeType; + typedef typename Superclass::InputSizeValueType InputSizeValueType; + typedef typename Superclass::InputSpacingType InputSpacingType; + typedef typename Superclass::InputIndexType InputIndexType; + typedef typename Superclass::InputIndexValueType InputIndexValueType; + typedef typename Superclass::InputPointType InputPointType; + + typedef TFeatureImage FeatureImageType; + typedef typename Superclass::FeatureImagePointer FeatureImagePointer; + typedef typename Superclass::FeatureImageConstPointer FeatureImageConstPointer; + typedef typename Superclass::FeaturePixelType FeaturePixelType; + typedef typename Superclass::FeatureRegionType FeatureRegionType; + typedef typename Superclass::FeatureSizeType FeatureSizeType; + typedef typename Superclass::FeatureSizeValueType FeatureSizeValueType; + typedef typename Superclass::FeatureSpacingType FeatureSpacingType; + typedef typename Superclass::FeatureIndexType FeatureIndexType; + typedef typename Superclass::FeaturePointType FeaturePointType; + + double m_BackgroundConstantValues; + double m_ForegroundConstantValues; + double m_WeightedSumOfPixelValuesInsideLevelSet; + double m_WeightedSumOfPixelValuesOutsideLevelSet; + +protected: + ScalarChanAndVeseLevelSetFunctionData() : Superclass() + { + m_BackgroundConstantValues = 0.; + m_ForegroundConstantValues = 0.; + m_WeightedSumOfPixelValuesInsideLevelSet = 0.; + m_WeightedSumOfPixelValuesOutsideLevelSet = 0.; + } + virtual ~ScalarChanAndVeseLevelSetFunctionData() {} + +private: + ScalarChanAndVeseLevelSetFunctionData(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} //end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.h b/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.h new file mode 100644 index 0000000000..9c020e985f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.h @@ -0,0 +1,157 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarChanAndVeseSparseLevelSetImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-16 12:35:12 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarChanAndVeseSparseLevelSetImageFilter_h +#define __itkScalarChanAndVeseSparseLevelSetImageFilter_h + +#include "itkMultiphaseSparseFiniteDifferenceImageFilter.h" +#include "itkRegionOfInterestImageFilter.h" + +/** \class ScalarChanAndVeseSparseLevelSetImageFilter + * \brief Sparse implementation of the Chan and Vese multiphase level set image filter. + * + * + * This code was adapted from the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + */ +namespace itk +{ +template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, + class TSharedData, typename TIdCell = unsigned int > +class ITK_EXPORT ScalarChanAndVeseSparseLevelSetImageFilter : +public MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +{ +public: + typedef ScalarChanAndVeseSparseLevelSetImageFilter Self; + typedef MultiphaseSparseFiniteDifferenceImageFilter< + TInputImage, TOutputImage, TFunction, TIdCell > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( ScalarChanAndVeseSparseLevelSetImageFilter, + MultiphaseSparseFiniteDifferenceImageFilter ); + + itkStaticConstMacro( ImageDimension, unsigned int, TInputImage::ImageDimension ); + + /** Inherited typedef from the superclass. */ + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePtr; + typedef typename FeatureImageType::PixelType FeaturePixelType; + typedef typename FeatureImageType::IndexType FeatureIndexType; + typedef typename FeatureIndexType::IndexValueType FeatureIndexValueType; + typedef typename FeatureImageType::RegionType FeatureRegionType; + + /** Output image type typedefs */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::InputSpacingType InputSpacingType; + + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename OutputImageType::ValueType ValueType; + typedef typename OutputImageType::IndexType IndexType; + typedef typename OutputImageType::PixelType OutputPixelType; + + typedef typename Superclass::TimeStepType TimeStepType; + typedef typename Superclass::FiniteDifferenceFunctionType + FiniteDifferenceFunctionType; + + typedef typename Superclass::IdCellType IdCellType; + + typedef TFunction FunctionType; + typedef typename FunctionType::Pointer FunctionPtr; + + typedef TSharedData SharedDataType; + typedef typename SharedDataType::Pointer SharedDataPointer; + + typedef RegionOfInterestImageFilter< + FeatureImageType, FeatureImageType > ROIFilterType; + typedef typename ROIFilterType::Pointer ROIFilterPointer; + + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(OutputHasNumericTraitsCheck, + (Concept::HasNumericTraits<OutputPixelType>) ); + /** End concept checking */ +#endif + + /** Set/Get the feature image to be used for speed function of the level set + * equation. Equivalent to calling Set/GetInput(1, ..) */ + virtual void SetFeatureImage(const FeatureImageType *f) + { + this->ProcessObject::SetNthInput( 0, const_cast< FeatureImageType *>(f) ); + } + + virtual const FeatureImageType * GetFeatureImage() const + { + return (static_cast< const FeatureImageType*>(this->ProcessObject::GetInput(0))); + } + +protected: + ScalarChanAndVeseSparseLevelSetImageFilter() + { + this->SetNumberOfLayers(5); // Narrow-band usage + this->m_SharedData = SharedDataType::New(); + } + + ~ScalarChanAndVeseSparseLevelSetImageFilter() {} + + SharedDataPointer m_SharedData; + + virtual void Initialize(); + virtual void InitializeIteration(); + virtual void UpdatePixel( unsigned int functionIndex, + unsigned int idx, NeighborhoodIterator< OutputImageType > &iterator, + ValueType &newValue, bool &status ); +}; + +} //end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScalarChanAndVeseSparseLevelSetImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.txx b/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.txx new file mode 100644 index 0000000000..f54d34969a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.txx @@ -0,0 +1,139 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarChanAndVeseSparseLevelSetImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-16 12:35:12 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarChanAndVeseSparseLevelSetImageFilter_txx +#define __itkScalarChanAndVeseSparseLevelSetImageFilter_txx + +#include "itkScalarChanAndVeseSparseLevelSetImageFilter.h" + +namespace itk +{ +template < class TInput, class TFeature, class TFunction, +class TOutputPixel, class TSharedData, typename TIdCell > +void +ScalarChanAndVeseSparseLevelSetImageFilter< TInput, TFeature, TFunction, +TOutputPixel, TSharedData, TIdCell >:: +Initialize() +{ + // Set the feature image for the individual level-set functions + for( IdCellType i = 0; i < this->m_FunctionCount; i++) + { + InputImagePointer input = this->m_LevelSet[i]; + InputPointType origin = input->GetOrigin(); + InputSpacingType spacing = input->GetSpacing(); + + // In the context of the global coordinates + FeatureIndexType start; + for( unsigned int j = 0; j < ImageDimension; j++ ) + { + start[j] = static_cast<FeatureIndexValueType>( origin[j]/spacing[j] ); + } + + // Defining roi region + FeatureRegionType region; + region.SetSize( input->GetLargestPossibleRegion().GetSize() ); + region.SetIndex( start ); + + // Initialize the ROI filter with the feature image + ROIFilterPointer roi = ROIFilterType::New(); + roi->SetInput( this->GetFeatureImage() ); + roi->SetRegionOfInterest( region ); + roi->Update(); + + // Assign roi output + FeatureImagePtr feature = roi->GetOutput(); + this->m_DifferenceFunctions[i]->SetFeatureImage( feature ); + this->m_DifferenceFunctions[i]->SetInitialImage( input ); + } + + // Initialize the function count in m_SharedData + this->m_SharedData->SetFunctionCount ( this->m_FunctionCount ); + + // Set the KdTree pointer + if ( this->m_KdTree ) + { + this->m_SharedData->SetKdTree( this->m_KdTree ); + } + + for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + FunctionPtr typedPointer = this->m_DifferenceFunctions[i]; + + typedPointer->SetFunctionId( i ); + + this->m_SharedData->CreateHeavisideFunctionOfLevelSetImage ( i, this->m_LevelSet[i] ); + + // Share the m_SharedData structure + typedPointer->SetSharedData( this->m_SharedData ); + } + + this->m_SharedData->AllocateListImage( this->GetFeatureImage() ); + + this->m_SharedData->PopulateListImage(); + + Superclass::Initialize(); + + for (IdCellType i = 0; i < this->m_FunctionCount; i++) + { + this->m_DifferenceFunctions[i]->UpdateSharedData(true); + } + + for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + { + this->m_DifferenceFunctions[i]->UpdateSharedData( false ); + } +} + +/** Overrides parent implementation */ +// This function is called at the end of each iteration +template < class TInput, class TFeature, class TFunction, +class TOutputPixel, class TSharedData, typename TIdCell > +void +ScalarChanAndVeseSparseLevelSetImageFilter< TInput, TFeature, +TFunction, TOutputPixel, TSharedData, TIdCell > :: +InitializeIteration() +{ + Superclass::InitializeIteration(); + + for (IdCellType i = 0; i < this->m_FunctionCount; i++) + { + this->m_DifferenceFunctions[i]->UpdateSharedData( false ); + } + + // Estimate the progress of the filter + this->SetProgress( ( ( float ) this->m_ElapsedIterations + / ( float ) this->m_NumberOfIterations ) ); +} + +template < class TInput, class TFeature, class TFunction, +class TOutputPixel, class TSharedData, typename TIdCell > +void +ScalarChanAndVeseSparseLevelSetImageFilter< TInput, TFeature, +TFunction, TOutputPixel, TSharedData, TIdCell > :: +UpdatePixel ( unsigned int functionIndex, unsigned int idx, +NeighborhoodIterator< OutputImageType > &iterator, ValueType &newValue, +bool &status ) +{ + FunctionPtr typedPointer = this->m_DifferenceFunctions[functionIndex]; + typedPointer->UpdatePixel( idx, iterator, newValue, status ); + + iterator.SetPixel(idx, newValue, status); +} + +} /* end namespace itk */ + +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.h b/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.h new file mode 100644 index 0000000000..4108ee4348 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.h @@ -0,0 +1,153 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarRegionBasedLevelSetFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-13 14:23:05 $ + Version: $Revision: 1.7 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarRegionBasedLevelSetFunction_h +#define __itkScalarRegionBasedLevelSetFunction_h + +#include "itkRegionBasedLevelSetFunction.h" +#include "itkNeighborhoodIterator.h" +#include "itkImageRegionConstIterator.h" + +namespace itk { + + +/** \class ScalarRegionBasedLevelSetFunction + * + * \brief LevelSet function that computes a speed image based on regional integrals + * + * This class implements a level set function that computes the speed image by + * integrating values on the image domain. + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template < class TInputImage, class TFeatureImage, class TSharedData > +class ITK_EXPORT ScalarRegionBasedLevelSetFunction +: public RegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +{ +public: + typedef ScalarRegionBasedLevelSetFunction Self; + typedef RegionBasedLevelSetFunction< + TInputImage, TFeatureImage, TSharedData > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + // itkNewMacro() is purposely not provided since this is an abstract class. + + /** Run-time type information (and related methods) */ + itkTypeMacro( ScalarRegionBasedLevelSetFunction, RegionBasedLevelSetFunction ); + + itkStaticConstMacro( ImageDimension, unsigned int, TFeatureImage::ImageDimension ); + + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::InputImageConstPointer InputImageConstPointer; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputPixelType InputPixelType; + typedef typename Superclass::InputIndexType InputIndexType; + typedef typename Superclass::InputIndexValueType InputIndexValueType; + typedef typename Superclass::InputSizeType InputSizeType; + typedef typename Superclass::InputSizeValueType InputSizeValueType; + typedef typename Superclass::InputRegionType InputRegionType; + typedef typename Superclass::InputPointType InputPointType; + + typedef typename Superclass::FeatureImageType FeatureImageType; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename Superclass::FeaturePixelType FeaturePixelType; + typedef typename Superclass::FeatureIndexType FeatureIndexType; + typedef typename Superclass::FeatureOffsetType FeatureOffsetType; + + typedef typename Superclass::ScalarValueType ScalarValueType; + typedef typename Superclass::NeighborhoodType NeighborhoodType; + typedef typename Superclass::FloatOffsetType FloatOffsetType; + typedef typename Superclass::RadiusType RadiusType; + typedef typename Superclass::TimeStepType TimeStepType; + typedef typename Superclass::GlobalDataStruct GlobalDataStruct; + typedef typename Superclass::PixelType PixelType; + typedef typename Superclass::VectorType VectorType; + + typedef typename Superclass::SharedDataType SharedDataType; + typedef typename Superclass::SharedDataPointer SharedDataPointer; + + typedef ImageRegionIteratorWithIndex< InputImageType > ImageIteratorType; + typedef ImageRegionConstIteratorWithIndex< InputImageType > ConstImageIteratorType; + typedef ImageRegionIteratorWithIndex< FeatureImageType > FeatureImageIteratorType; + typedef ImageRegionConstIterator< FeatureImageType > ConstFeatureIteratorType; + + typedef std::list< unsigned int > ListPixelType; + typedef typename ListPixelType::const_iterator ListPixelConstIterator; + typedef typename ListPixelType::iterator ListPixelIterator; + typedef Image< ListPixelType, itkGetStaticConstMacro(ImageDimension) > + ListImageType; + + /** \brief Performs the narrow-band update of the Heaviside function for each + voxel. The characteristic function of each region is recomputed (note the + shared data which contains information from the other level sets). Using the + new H values, the previous c_i are updated. */ + void UpdatePixel( const unsigned int& idx, + NeighborhoodIterator<TInputImage> &iterator, + InputPixelType &newValue, + bool &status ); + +protected: + ScalarRegionBasedLevelSetFunction() : Superclass(){} + ~ScalarRegionBasedLevelSetFunction(){} + + ScalarValueType ComputeOverlapParameters( const FeatureIndexType& featIndex, + ScalarValueType& product ); + + virtual void UpdateSharedDataInsideParameters( const unsigned int& iId, + const bool& iBool, const FeaturePixelType& iVal, const ScalarValueType& iH ) = 0; + virtual void UpdateSharedDataOutsideParameters( const unsigned int& iId, + const bool& iBool, const FeaturePixelType& iVal, const ScalarValueType& iH ) = 0; + +private: + ScalarRegionBasedLevelSetFunction(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScalarRegionBasedLevelSetFunction.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.txx b/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.txx new file mode 100644 index 0000000000..08d899fa6f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.txx @@ -0,0 +1,133 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarRegionBasedLevelSetFunction.txx,v $ + Language: C++ + Date: $Date: 2009-05-21 22:03:29 $ + Version: $Revision: 1.14 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkScalarRegionBasedLevelSetFunction_txx +#define __itkScalarRegionBasedLevelSetFunction_txx + +#include "itkScalarRegionBasedLevelSetFunction.h" + +namespace itk { + +template < class TInputImage, class TFeatureImage, class TSharedData > +typename ScalarRegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData >::ScalarValueType +ScalarRegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +::ComputeOverlapParameters( const FeatureIndexType& globalIndex, ScalarValueType& product ) +{ +// This conditional statement computes the amount of overlap s +// and the presence of background pr + unsigned int fId = this->m_FunctionId; + + // accumulates the overlap across all functions + ScalarValueType sum = 0; + product = 1.; + + ListPixelType L; + L = this->m_SharedData->m_NearestNeighborListImage->GetPixel( globalIndex ); + + InputPixelType hVal; + InputIndexType otherIndex; + + for ( ListPixelIterator it = L.begin(); it != L.end(); ++it ) + { + unsigned int id = *it; + if ( id != fId ) + { + otherIndex = this->m_SharedData->m_LevelSetDataPointerVector[id]->GetIndex( globalIndex ); + hVal = this->m_SharedData->m_LevelSetDataPointerVector[id]->m_HeavisideFunctionOfLevelSetImage->GetPixel( otherIndex ); + + sum += hVal; + product *= hVal; + } + } + return sum; +} + +/* Performs the narrow-band update of the Heaviside function for each voxel. The +characteristic function of each region is recomputed (note the shared +data which contains information from the other level sets). Using the +new H values, the previous c_i are updated. */ +template < class TInputImage, class TFeatureImage, class TSharedData > +void +ScalarRegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData > +::UpdatePixel( const unsigned int& idx, NeighborhoodIterator< TInputImage > +&iterator, InputPixelType &newValue, bool & itkNotUsed(status) ) +{ + unsigned int fId = this->m_FunctionId; + + // For each affected h val: h val = new hval (this will dirty some cvals) + InputIndexType inputIndex = iterator.GetIndex( idx ); + FeatureIndexType globalIndex = this->m_SharedData->m_LevelSetDataPointerVector[fId]->GetFeatureIndex( inputIndex ); + + FeaturePixelType featureVal = this->m_FeatureImage->GetPixel( inputIndex ); + + ScalarValueType oldH = this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_HeavisideFunctionOfLevelSetImage->GetPixel( inputIndex ); + ScalarValueType newH = this->m_DomainFunction->Evaluate( - newValue ); + + // Check if it is in other foreground + ListPixelType L = this->m_SharedData->m_NearestNeighborListImage->GetPixel( globalIndex ); + InputIndexType itInputIndex; + ScalarValueType hVal; + + bool inBgrnd = true; // assume the pixel is in background + for( ListPixelType::const_iterator it = L.begin(); it != L.end(); ++it ) + { + itInputIndex = this->m_SharedData->m_LevelSetDataPointerVector[*it]->GetIndex( globalIndex ); + hVal = this->m_SharedData->m_LevelSetDataPointerVector[*it]->m_HeavisideFunctionOfLevelSetImage->GetPixel( itInputIndex ); + + if ( ( hVal > 0.5 ) && ( *it != fId ) ) + { + inBgrnd = false; // belongs to foreground elsewhere + } + } + + // if pixel belonged to current foreground but not anymore so + if ( ( oldH > 0.5 ) && ( newH <= 0.5 ) ) + { + UpdateSharedDataInsideParameters( fId, false, featureVal, newH ); + + // have to update level-set backgrounds overlapping + // at the current pixel + if ( inBgrnd ) + { + for( ListPixelType::const_iterator it = L.begin(); it != L.end(); ++it ) + { + UpdateSharedDataOutsideParameters( *it, true, featureVal, newH ); + } + } + } + + // if pixel entered the foreground + if ( ( oldH <= 0.5 ) && ( newH > 0.5 ) ) + { + UpdateSharedDataInsideParameters( fId, true, featureVal, newH ); + // have to update level-set backgrounds overlapping + // at the current pixel + if ( inBgrnd ) + { + for( ListPixelType::const_iterator it = L.begin(); it != L.end(); ++it ) + { + UpdateSharedDataOutsideParameters( *it, false, featureVal, newH ); + } + } + } + + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_HeavisideFunctionOfLevelSetImage->SetPixel( inputIndex, newH ); +} + + +} // end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarToRGBColormapImageFilter.h b/Utilities/ITK/Code/Review/itkScalarToRGBColormapImageFilter.h new file mode 100644 index 0000000000..bc20c2a489 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarToRGBColormapImageFilter.h @@ -0,0 +1,138 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarToRGBColormapImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-05-15 12:51:13 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScalarToRGBColormapImageFilter_h +#define __itkScalarToRGBColormapImageFilter_h + +#include "itkImageToImageFilter.h" + +#include "itkColormapFunctor.h" + +namespace itk +{ + +/** \class ScalarToRGBColormapImageFilter + * \brief Implements pixel-wise intensity->rgb mapping operation on one image. + * + * This class is parameterized over the type of the input image and + * the type of the output image. + * + * ScalarToRGBColormapImageFilter + * + * \sa BinaryFunctorImageFilter TernaryFunctorImageFilter + * + * \ingroup IntensityImageFilters Multithreaded + */ +template <class TInputImage, class TOutputImage> +class ITK_EXPORT ScalarToRGBColormapImageFilter +: public ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef ScalarToRGBColormapImageFilter Self; + typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( ScalarToRGBColormapImageFilter, ImageToImageFilter ); + + /** Some typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::ConstPointer InputImagePointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + typedef Functor::ColormapFunctor<InputImagePixelType, + OutputImagePixelType> ColormapType; + + /** + * Set/Get the colormap object. + */ + typename ColormapType::Pointer GetColormap() { return m_Colormap; } + + void SetColormap( ColormapType *colormap ) + { + if ( m_Colormap != colormap ) + { + m_Colormap = colormap; + this->Modified(); + } + } + + /** + * Enum type that provides for an easy interface to existing colormaps. + */ + typedef enum { Red, Green, Blue, Grey, Hot, Cool, Spring, Summer, + Autumn, Winter, Copper, Jet, HSV, OverUnder } ColormapEnumType; + + void SetColormap( ColormapEnumType ); + + /** + * Set/Get UseInputImageExtremaForScaling. If 'true', the colormap uses the + * min and max values from the image to scale appropriately. Otherwise, + * these values can be set in the colormap manually. + */ + itkSetMacro( UseInputImageExtremaForScaling, bool ); + itkGetConstMacro( UseInputImageExtremaForScaling, bool ); + itkBooleanMacro( UseInputImageExtremaForScaling ); + +protected: + ScalarToRGBColormapImageFilter(); + virtual ~ScalarToRGBColormapImageFilter() {}; + + void PrintSelf( std::ostream& os, Indent indent ) const; + + /** ScalarToRGBColormapImageFilter + * can be implemented as a multithreaded filter. + * Therefore, this implementation provides a ThreadedGenerateData() routine + * which is called for each processing thread. The output image data is + * allocated automatically by the superclass prior to calling + * ThreadedGenerateData(). ThreadedGenerateData can only write to the + * portion of the output image specified by the parameter + * "outputRegionForThread" + * + * \sa ImageToImageFilter::ThreadedGenerateData(), + * ImageToImageFilter::GenerateData() */ + void ThreadedGenerateData( const OutputImageRegionType& outputRegionForThread, + int threadId ); + + /** Process to execute before entering the multithreaded section */ + void BeforeThreadedGenerateData(); + +private: + ScalarToRGBColormapImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + typename ColormapType::Pointer m_Colormap; + + bool m_UseInputImageExtremaForScaling; +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScalarToRGBColormapImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarToRGBColormapImageFilter.txx b/Utilities/ITK/Code/Review/itkScalarToRGBColormapImageFilter.txx new file mode 100644 index 0000000000..148bbfd2da --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScalarToRGBColormapImageFilter.txx @@ -0,0 +1,275 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScalarToRGBColormapImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 12:51:14 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScalarToRGBColormapImageFilter_txx +#define __itkScalarToRGBColormapImageFilter_txx + +#include "itkScalarToRGBColormapImageFilter.h" + +#include "itkImageRegionIterator.h" +#include "itkImageRegionConstIterator.h" +#include "itkProgressReporter.h" + +#include "itkRedColormapFunctor.h" +#include "itkGreenColormapFunctor.h" +#include "itkBlueColormapFunctor.h" +#include "itkGreyColormapFunctor.h" +#include "itkHotColormapFunctor.h" +#include "itkCoolColormapFunctor.h" +#include "itkSpringColormapFunctor.h" +#include "itkSummerColormapFunctor.h" +#include "itkAutumnColormapFunctor.h" +#include "itkWinterColormapFunctor.h" +#include "itkCopperColormapFunctor.h" +#include "itkHSVColormapFunctor.h" +#include "itkJetColormapFunctor.h" +#include "itkOverUnderColormapFunctor.h" + +namespace itk +{ + +/** + * Constructor + */ +template <class TInputImage, class TOutputImage> +ScalarToRGBColormapImageFilter<TInputImage, TOutputImage> +::ScalarToRGBColormapImageFilter() +{ + this->SetNumberOfRequiredInputs( 1 ); + + this->m_UseInputImageExtremaForScaling = true; + + typedef Functor::GreyColormapFunctor< + InputImagePixelType, OutputImagePixelType> DefaultColormapType; + + typename DefaultColormapType::Pointer greyColormap = DefaultColormapType::New(); + this->SetColormap( greyColormap ); +} + +/** + * BeforeThreadedGenerateData + */ +template <class TInputImage, class TOutputImage> +void +ScalarToRGBColormapImageFilter<TInputImage,TOutputImage> +::BeforeThreadedGenerateData() +{ + if( this->m_UseInputImageExtremaForScaling == true ) + { + ImageRegionConstIterator<InputImageType> It( this->GetInput(), + this->GetInput()->GetRequestedRegion() ); + + InputImagePixelType minimumValue = NumericTraits<InputImagePixelType>::max(); + InputImagePixelType maximumValue = NumericTraits<InputImagePixelType>::min(); + + for( It.GoToBegin(); !It.IsAtEnd(); ++It ) + { + InputImagePixelType value = It.Get(); + if( value < minimumValue ) + { + minimumValue = value; + } + if( value > maximumValue ) + { + maximumValue = value; + } + } + + this->GetColormap()->SetMinimumInputValue( minimumValue ); + this->GetColormap()->SetMaximumInputValue( maximumValue ); + } +} + +/** + * ThreadedGenerateData performs the pixel-wise mapping + */ +template <class TInputImage, class TOutputImage> +void +ScalarToRGBColormapImageFilter<TInputImage,TOutputImage> +::ThreadedGenerateData( const OutputImageRegionType &outputRegionForThread, + int threadId ) +{ + InputImagePointer inputPtr = this->GetInput(); + OutputImagePointer outputPtr = this->GetOutput(); + + // Define the portion of the input to walk for this thread, using + // the CallCopyOutputRegionToInputRegion method allows for the input + // and output images to be different dimensions + InputImageRegionType inputRegionForThread; + this->CallCopyOutputRegionToInputRegion(inputRegionForThread, outputRegionForThread); + + // Define the iterators + ImageRegionConstIterator<TInputImage> inputIt(inputPtr, inputRegionForThread); + ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); + + ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels()); + + inputIt.GoToBegin(); + outputIt.GoToBegin(); + + while( !inputIt.IsAtEnd() ) + { + outputIt.Set( this->m_Colormap->operator()( inputIt.Get() ) ); + ++inputIt; + ++outputIt; + progress.CompletedPixel(); // potential exception thrown here + } +} + +template <class TInputImage, class TOutputImage> +void +ScalarToRGBColormapImageFilter<TInputImage,TOutputImage> +::SetColormap( ColormapEnumType map ) +{ + switch( map ) + { + case Red: + { + typedef Functor::RedColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Green: + { + typedef Functor::GreenColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Blue: + { + typedef Functor::BlueColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Grey: default: + { + typedef Functor::GreyColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Hot: + { + typedef Functor::HotColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Cool: + { + typedef Functor::CoolColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Spring: + { + typedef Functor::SpringColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Summer: + { + typedef Functor::SummerColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Autumn: + { + typedef Functor::AutumnColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Winter: + { + typedef Functor::WinterColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Copper: + { + typedef Functor::CopperColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case Jet: + { + typedef Functor::JetColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case HSV: + { + typedef Functor::HSVColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + case OverUnder: + { + typedef Functor::OverUnderColormapFunctor< + InputImagePixelType, OutputImagePixelType> SpecificColormapType; + typename SpecificColormapType::Pointer colormap = SpecificColormapType::New(); + this->SetColormap( colormap ); + break; + } + } + +} + +template <class TInputImage, class TOutputImage> +void +ScalarToRGBColormapImageFilter<TInputImage,TOutputImage> +::PrintSelf( std::ostream& os, Indent indent ) const +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "Class Name: " << this->GetNameOfClass( ) << std::endl; + if( this->m_Colormap.IsNotNull() ) + { + os << indent << "Colormap " << this->m_Colormap << std::endl; + } + else + { + os << indent << "Colormap is NULL " << std::endl; + } + os << indent << "Use Input Image Extrema for Scaling " << this->m_UseInputImageExtremaForScaling << std::endl; +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapedFloodFilledFunctionConditionalConstIterator.h b/Utilities/ITK/Code/Review/itkShapedFloodFilledFunctionConditionalConstIterator.h index 9b2b819647..a77f5e9ed3 100644 --- a/Utilities/ITK/Code/Review/itkShapedFloodFilledFunctionConditionalConstIterator.h +++ b/Utilities/ITK/Code/Review/itkShapedFloodFilledFunctionConditionalConstIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShapedFloodFilledFunctionConditionalConstIterator.h,v $ Language: C++ - Date: $Date: 2009-02-16 21:17:19 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-28 16:16:25 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,6 +34,9 @@ namespace itk * \class ShapedFloodFilledFunctionConditionalConstIterator * \brief Iterates over a flood-filled spatial function. * + * Contributed as a paper to the Insight Journal: + * http://hdl.handle.net/1926/1320 + * * \ingroup ImageIterators * */ diff --git a/Utilities/ITK/Code/Review/itkShapedFloodFilledImageFunctionConditionalConstIterator.h b/Utilities/ITK/Code/Review/itkShapedFloodFilledImageFunctionConditionalConstIterator.h index e6edb45193..6167e9ec6b 100644 --- a/Utilities/ITK/Code/Review/itkShapedFloodFilledImageFunctionConditionalConstIterator.h +++ b/Utilities/ITK/Code/Review/itkShapedFloodFilledImageFunctionConditionalConstIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShapedFloodFilledImageFunctionConditionalConstIterator.h,v $ Language: C++ - Date: $Date: 2009-02-16 21:17:19 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-28 16:16:25 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,6 +26,9 @@ namespace itk * \class ShapedFloodFilledImageFunctionConditionalConstIterator * \brief Iterates over a flood-filled image function. * + * Contributed as a paper to the Insight Journal: + * http://hdl.handle.net/1926/1320 + * * \ingroup ImageIterators * */ diff --git a/Utilities/ITK/Code/Review/itkShapedFloodFilledImageFunctionConditionalIterator.h b/Utilities/ITK/Code/Review/itkShapedFloodFilledImageFunctionConditionalIterator.h index dc497737ca..3a8ed0ff78 100644 --- a/Utilities/ITK/Code/Review/itkShapedFloodFilledImageFunctionConditionalIterator.h +++ b/Utilities/ITK/Code/Review/itkShapedFloodFilledImageFunctionConditionalIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShapedFloodFilledImageFunctionConditionalIterator.h,v $ Language: C++ - Date: $Date: 2009-02-16 21:17:19 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-28 16:16:26 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,6 +26,9 @@ namespace itk * \class ShapedFloodFilledImageFunctionConditionalIterator * \brief Iterates over a flood-filled image function. * + * Contributed as a paper to the Insight Journal: + * http://hdl.handle.net/1926/1320 + * * \ingroup ImageIterators * */ diff --git a/Utilities/ITK/Code/Review/itkSharedMorphologyUtilities.txx b/Utilities/ITK/Code/Review/itkSharedMorphologyUtilities.txx index 6556734588..9e2196b4dd 100644 --- a/Utilities/ITK/Code/Review/itkSharedMorphologyUtilities.txx +++ b/Utilities/ITK/Code/Review/itkSharedMorphologyUtilities.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSharedMorphologyUtilities.txx,v $ Language: C++ - Date: $Date: 2009-02-21 20:42:23 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-06 13:46:38 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -94,12 +94,12 @@ int ComputeStartEnd(const typename TImage::IndexType StartIndex, unsigned perpdir = 0; for (unsigned i = 0; i< TImage::RegionType::ImageDimension; i++) { - if (fabs(line[i]) > domdir) + if (vcl_fabs(line[i]) > domdir) { - domdir = fabs(line[i]); + domdir = vcl_fabs(line[i]); perpdir = i; } - if (fabs(line[i]) > tol) + if (vcl_fabs(line[i]) > tol) { int P1 = ImStart[i] - StartIndex[i]; int P2 = ImStart[i] + ImSize[i] - 1 - StartIndex[i]; @@ -132,8 +132,8 @@ int ComputeStartEnd(const typename TImage::IndexType StartIndex, } } } - sPos = (int)(Tnear*fabs(line[perpdir]) + 0.5); - ePos = (int)(Tfar*fabs(line[perpdir]) + 0.5); + sPos = (int)(Tnear*vcl_fabs(line[perpdir]) + 0.5); + ePos = (int)(Tfar*vcl_fabs(line[perpdir]) + 0.5); //std::cout << Tnear << " " << Tfar << std::endl; if (Tfar < Tnear) // seems to need some margin @@ -324,9 +324,9 @@ FaceCalculatorType; // figure out the dominant direction of the line for (unsigned i = 0;i< TInputImage::RegionType::ImageDimension;i++) { - if (fabs(line[i]) > MaxComp) + if (vcl_fabs(line[i]) > MaxComp) { - MaxComp = fabs(line[i]); + MaxComp = vcl_fabs(line[i]); DomDir = i; } } @@ -378,8 +378,7 @@ FaceCalculatorType; { if (i != NonFaceDim) { - int Pad = (int)ceil((float)(NonFaceLen) * line[i]/fabs(line[NonFaceDim])); -// int Pad = (int)((float)(NonFaceLen) * line[i]/fabs(line[NonFaceDim])); + int Pad = (int)vcl_ceil((float)(NonFaceLen) * line[i]/vcl_fabs(line[NonFaceDim])); if (Pad < 0) { // just increase the size - no need to change the start @@ -470,7 +469,7 @@ unsigned int GetLinePixels(const TLine line) for (unsigned int i = 0; i < TLine::Dimension; i++) { - float tt = fabs(line[i]/N); + float tt = vcl_fabs(line[i]/N); if (tt > correction) correction=tt; } diff --git a/Utilities/ITK/Code/Review/itkSinRegularizedHeavisideStepFunction.h b/Utilities/ITK/Code/Review/itkSinRegularizedHeavisideStepFunction.h new file mode 100644 index 0000000000..3976d60aa8 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkSinRegularizedHeavisideStepFunction.h @@ -0,0 +1,119 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSinRegularizedHeavisideStepFunction.h,v $ + Language: C++ + Date: $Date: 2009-05-09 21:35:53 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkSinRegularizedHeavisideStepFunction_h +#define __itkSinRegularizedHeavisideStepFunction_h + +#include "itkRegularizedHeavisideStepFunction.h" + +namespace itk +{ + +/** \class SinRegularizedHeavisideStepFunction + * + * \brief Sin-based implementation of the Regularized (smoothed) Heaviside functions. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template< class TInput = float, class TOutput = double > +class SinRegularizedHeavisideStepFunction : + public RegularizedHeavisideStepFunction< TInput, TOutput > +{ +public: + typedef SinRegularizedHeavisideStepFunction Self; + typedef RegularizedHeavisideStepFunction< TInput, TOutput > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + itkNewMacro( Self ); + + itkTypeMacro( SinRegularizedHeavisideStepFunction, RegularizedHeavisideStepFunction ); + + typedef typename Superclass::InputType InputType; + typedef typename Superclass::OutputType OutputType; + typedef typename Superclass::RealType RealType; + + /** Evaluate at the specified input position */ + virtual OutputType Evaluate( const InputType& input ) const + { + if( input > this->GetEpsilon() ) + { + return 1.0; + } + else + { + if( input < -this->GetEpsilon() ) + { + return 0.0; + } + else + { + const RealType angleFactor = 0.5 * vnl_math::pi * this->GetOneOverEpsilon(); + const RealType angle = input * angleFactor; + return 0.5 * ( 1.0 + vcl_sin( angle ) ); + } + } + } + + /** Evaluate the derivative at the specified input position */ + virtual OutputType EvaluateDerivative( const InputType& input ) const + { + if( vnl_math_abs( input ) > this->GetEpsilon() ) + { + return 0.0; + } + else + { + const RealType angleFactor = 0.5 * vnl_math::pi * this->GetOneOverEpsilon(); + const RealType angle = input * angleFactor; + return 0.5 * angleFactor * vcl_cos( angle ); + } + } + +protected: + SinRegularizedHeavisideStepFunction() {} + virtual ~SinRegularizedHeavisideStepFunction() {} + +private: + SinRegularizedHeavisideStepFunction(const Self& ); //purposely not implemented + void operator=(const Self& ); //purposely not implemented + +}; + +} + +#endif diff --git a/Utilities/ITK/Code/Review/itkSliceBySliceImageFilter.h b/Utilities/ITK/Code/Review/itkSliceBySliceImageFilter.h index e4bbfdda82..ad8aad5a64 100644 --- a/Utilities/ITK/Code/Review/itkSliceBySliceImageFilter.h +++ b/Utilities/ITK/Code/Review/itkSliceBySliceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSliceBySliceImageFilter.h,v $ Language: C++ - Date: $Date: 2008-12-04 18:37:10 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -128,7 +128,7 @@ public: InternalInputImageType::ImageDimension); itkSetMacro(Dimension, unsigned int); - itkGetMacro(Dimension, unsigned int); + itkGetConstMacro(Dimension, unsigned int); void SetFilter(InputFilterType * filter); InputFilterType * GetFilter() @@ -151,7 +151,7 @@ public: * used with the IterationEvent sent before the processing of each object. It contains * a relevant value only during the filter update. */ - itkGetMacro(SliceIndex, long); + itkGetConstMacro(SliceIndex, long); protected: SliceBySliceImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkSpringColormapFunctor.h b/Utilities/ITK/Code/Review/itkSpringColormapFunctor.h new file mode 100644 index 0000000000..bca47d52ed --- /dev/null +++ b/Utilities/ITK/Code/Review/itkSpringColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSpringColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSpringColormapFunctor_h +#define __itkSpringColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class SpringColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT SpringColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef SpringColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + SpringColormapFunctor() {}; + ~SpringColormapFunctor() {}; + +private: + SpringColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkSpringColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkSpringColormapFunctor.txx b/Utilities/ITK/Code/Review/itkSpringColormapFunctor.txx new file mode 100644 index 0000000000..c96c4ced00 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkSpringColormapFunctor.txx @@ -0,0 +1,56 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSpringColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSpringColormapFunctor_txx +#define __itkSpringColormapFunctor_txx + +#include "itkSpringColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename SpringColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +SpringColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color mapping. + RealType red = 1.0; + + RealType green = value; + + RealType blue = 1.0 - value; + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkStochasticFractalDimensionImageFilter.h b/Utilities/ITK/Code/Review/itkStochasticFractalDimensionImageFilter.h new file mode 100644 index 0000000000..4f382f51e0 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStochasticFractalDimensionImageFilter.h @@ -0,0 +1,117 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStochasticFractalDimensionImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-04-30 01:58:27 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStochasticFractalDimensionImageFilter_h +#define __itkStochasticFractalDimensionImageFilter_h + +#include "itkImageToImageFilter.h" + +#include "itkConstNeighborhoodIterator.h" + +namespace itk { + +/** \class StochasticFractalDimensionImageFilter + * \brief This filter computes the stochastic fractal dimension of the input image. + * + * The methodology is based on Madelbrot’s fractal theory and the concept of + * fractional Brownian motion and yields images which have been used for + * classification and edge enhancement. + * + * This class which is templated over the input and output images as well as a + * mask image type. The input is a scalar image, an optional neighborhood + * radius (default = 2), and an optional mask. The mask can be specified to + * decrease computation time since, as the authors point out, calculation is + * time-consuming. + * + * This filter was contributed by Nick Tustison and James Gee + * from the PICSL lab, at the University of Pennsylvania + * as an paper to the Insight Journal: + * + * "Stochastic Fractal Dimension Image" + * http://hdl.handle.net/1926/1525 + * http://www.insight-journal.org/browse/publication/318 + * + * \author Nick Tustison + * + */ +template<class TInputImage, class TMaskImage = Image<unsigned char, + ::itk::GetImageDimension<TInputImage>::ImageDimension>, + class TOutputImage = TInputImage> +class ITK_EXPORT StochasticFractalDimensionImageFilter : + public ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef StochasticFractalDimensionImageFilter Self; + typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Standard New method. */ + itkNewMacro( Self ); + + /** ImageDimension constants */ + itkStaticConstMacro( ImageDimension, unsigned int, TInputImage::ImageDimension ); + + /** Some convenient typedefs. */ + typedef float RealType; + typedef TInputImage InputImageType; + typedef TMaskImage MaskImageType; + typedef TOutputImage OutputImageType; + + /** Runtime information support. */ + itkTypeMacro( StochasticFractalDimensionImageFilter, ImageToImageFilter ); + + + /** Set/Get the input mask image that will constraint the computation of the + * fractal dimension to pixels that are on in the mask. This is intended to + * reduce the computation time. */ + void SetMaskImage( const MaskImageType * mask ); + const MaskImageType * GetMaskImage() const; + + /** Type of the neighborhood iterator used to evaluate similarity between the + * image pixels. */ + typedef ConstNeighborhoodIterator<InputImageType> ConstNeighborhoodIteratorType; + typedef typename ConstNeighborhoodIteratorType::RadiusType RadiusType; + + /** Manhattan radius used for evaluating the fractal dimension. */ + itkSetMacro( NeighborhoodRadius, RadiusType ); + itkGetConstMacro( NeighborhoodRadius, RadiusType ); + +protected: + StochasticFractalDimensionImageFilter(); + ~StochasticFractalDimensionImageFilter(); + + void PrintSelf( std::ostream& os, Indent indent ) const; + + void GenerateData(); + +private: + StochasticFractalDimensionImageFilter( const Self& ); //purposely not implemented + void operator=( const Self& ); //purposely not implemented + + RadiusType m_NeighborhoodRadius; + typename MaskImageType::Pointer m_MaskImage; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkStochasticFractalDimensionImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkStochasticFractalDimensionImageFilter.txx b/Utilities/ITK/Code/Review/itkStochasticFractalDimensionImageFilter.txx new file mode 100644 index 0000000000..40ef84fc04 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStochasticFractalDimensionImageFilter.txx @@ -0,0 +1,232 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStochasticFractalDimensionImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-04-30 01:58:27 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStochasticFractalDimensionImageFilter_txx +#define __itkStochasticFractalDimensionImageFilter_txx + +#include "itkStochasticFractalDimensionImageFilter.h" + +#include "itkNeighborhoodAlgorithm.h" +#include "itkProgressReporter.h" + +#include <vector> + +namespace itk { + +template <class TInputImage, class TMaskImage, class TOutputImage> +StochasticFractalDimensionImageFilter<TInputImage, TMaskImage, TOutputImage> +::StochasticFractalDimensionImageFilter() +{ + this->m_NeighborhoodRadius.Fill( 2 ); + + this->m_MaskImage = NULL; +} + +template <class TInputImage, class TMaskImage, class TOutputImage> +StochasticFractalDimensionImageFilter<TInputImage, TMaskImage, TOutputImage> +::~StochasticFractalDimensionImageFilter() +{ +} + +template<class TInputImage, class TMaskImage, class TOutputImage> +void +StochasticFractalDimensionImageFilter<TInputImage, TMaskImage, TOutputImage> +::SetMaskImage( const MaskImageType * mask ) +{ + this->SetNthInput( 1, const_cast<MaskImageType *>( mask ) ); +} + +template<class TInputImage, class TMaskImage, class TOutputImage> +const typename StochasticFractalDimensionImageFilter<TInputImage, TMaskImage, TOutputImage>::MaskImageType * +StochasticFractalDimensionImageFilter<TInputImage, TMaskImage, TOutputImage> +::GetMaskImage() const +{ + const MaskImageType * maskImage = + dynamic_cast< const MaskImageType * >( this->ProcessObject::GetInput( 1 ) ); + + return maskImage; +} + +template<class TInputImage, class TMaskImage, class TOutputImage> +void +StochasticFractalDimensionImageFilter<TInputImage, TMaskImage, TOutputImage> +::GenerateData() +{ + this->AllocateOutputs(); + + typedef typename InputImageType::PixelType InputPixelType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename InputImageType::PointType PointType; + + const InputImageType * inputImage = this->GetInput(); + + typename InputImageType::RegionType region = inputImage->GetRequestedRegion(); + + ProgressReporter progress( this, 0, region.GetNumberOfPixels(), 100 ); + + typedef typename NeighborhoodAlgorithm + ::ImageBoundaryFacesCalculator<InputImageType> FaceCalculatorType; + FaceCalculatorType faceCalculator; + + typename FaceCalculatorType::FaceListType faceList + = faceCalculator( inputImage, region, this->m_NeighborhoodRadius ); + + typename FaceCalculatorType::FaceListType::iterator fit; + + typename InputImageType::SpacingType spacing = inputImage->GetSpacing(); + + RealType minSpacing = spacing[0]; + + for( unsigned int d = 0; d < ImageDimension; d++ ) + { + if( spacing[d] < minSpacing ) + { + minSpacing = spacing[d]; + } + } + + std::vector<RealType> distances; + std::vector<RealType> distancesFrequency; + std::vector<RealType> averageAbsoluteIntensityDifference; + + for( fit = faceList.begin(); fit != faceList.end(); ++fit ) + { + ConstNeighborhoodIteratorType It( + this->m_NeighborhoodRadius, this->GetInput(), *fit ); + + NeighborhoodIterator<OutputImageType> ItO( + this->m_NeighborhoodRadius, this->GetOutput(), *fit ); + + for( It.GoToBegin(), ItO.GoToBegin(); !It.IsAtEnd(); ++It, ++ItO ) + { + if( this->m_MaskImage && !this->m_MaskImage->GetPixel( It.GetIndex() ) ) + { + ItO.SetCenterPixel( NumericTraits< OutputPixelType >::Zero ); + progress.CompletedPixel(); + continue; + } + + distances.clear(); + distancesFrequency.clear(); + averageAbsoluteIntensityDifference.clear(); + + for( unsigned int i = 0; i < It.GetNeighborhood().Size(); i++ ) + { + bool IsInBounds1; + InputPixelType pixel1 = It.GetPixel( i, IsInBounds1 ); + + if( !IsInBounds1 ) + { + continue; + } + + if( !this->m_MaskImage || this->m_MaskImage->GetPixel( It.GetIndex( i ) ) ) + { + PointType point1; + this->GetInput()->TransformIndexToPhysicalPoint( It.GetIndex( i ), point1 ); + + for( unsigned int j = 0; j < It.GetNeighborhood().Size(); j++ ) + { + if( i == j ) + { + continue; + } + + bool IsInBounds2; + InputPixelType pixel2 = It.GetPixel( j, IsInBounds2 ); + + if( !IsInBounds2 ) + { + continue; + } + + if( !this->m_MaskImage || this->m_MaskImage->GetPixel( It.GetIndex( j ) ) ) + { + PointType point2; + this->GetInput()->TransformIndexToPhysicalPoint( It.GetIndex( j ), point2 ); + + const RealType distance = point1.SquaredEuclideanDistanceTo( point2 ); + + bool distanceFound = false; + for( unsigned int k = 0; k < distances.size(); k++ ) + { + if( vnl_math_abs( distances[k] - distance ) < 0.5 * minSpacing ) + { + distancesFrequency[k]++; + averageAbsoluteIntensityDifference[k] += vnl_math_abs( pixel1 - pixel2 ); + distanceFound = true; + break; + } + } + + if( !distanceFound ) + { + distances.push_back( distance ); + distancesFrequency.push_back( 1 ); + averageAbsoluteIntensityDifference.push_back( vnl_math_abs( pixel1 - pixel2 ) ); + } + } + } + } + } + + RealType sumY = 0.0; + RealType sumX = 0.0; + RealType sumXY = 0.0; + RealType sumXX = 0.0; + + for( unsigned int k = 0; k < distances.size(); k++ ) + { + if( distancesFrequency[k] == 0 ) + { + continue; + } + + averageAbsoluteIntensityDifference[k] /= static_cast<RealType>( distancesFrequency[k] ); + averageAbsoluteIntensityDifference[k] = vcl_log( averageAbsoluteIntensityDifference[k] ); + + const RealType distance = vcl_log( vcl_sqrt( distances[k] ) ); + + sumY += averageAbsoluteIntensityDifference[k]; + sumX += distance; + sumXX += ( distance * distance ); + sumXY += ( averageAbsoluteIntensityDifference[k] * distance ); + } + + const RealType N = static_cast<RealType>( distances.size() ); + + const RealType slope = ( N * sumXY - sumX * sumY ) / ( N * sumXX - sumX * sumX ); + + ItO.SetCenterPixel( static_cast<OutputPixelType>( 3.0 - slope ) ); + + progress.CompletedPixel(); + } + } +} + +template<class TInputImage, class TMaskImage, class TOutputImage> +void +StochasticFractalDimensionImageFilter<TInputImage, TMaskImage, TOutputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf( os, indent ); + + os << indent << "Neighborhood radius: " << this->m_NeighborhoodRadius << std::endl; +} + +}// end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkSummerColormapFunctor.h b/Utilities/ITK/Code/Review/itkSummerColormapFunctor.h new file mode 100644 index 0000000000..52a97be674 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkSummerColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSummerColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSummerColormapFunctor_h +#define __itkSummerColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class SummerColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT SummerColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef SummerColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + SummerColormapFunctor() {}; + ~SummerColormapFunctor() {}; + +private: + SummerColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkSummerColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkSummerColormapFunctor.txx b/Utilities/ITK/Code/Review/itkSummerColormapFunctor.txx new file mode 100644 index 0000000000..bef1ef8853 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkSummerColormapFunctor.txx @@ -0,0 +1,56 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkSummerColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkSummerColormapFunctor_txx +#define __itkSummerColormapFunctor_txx + +#include "itkSummerColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename SummerColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +SummerColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color mapping. + RealType red = value; + + RealType green = 0.5 * value + 0.5; + + RealType blue = 0.4; + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/Review/itkTransformFileWriterWithFactory.h b/Utilities/ITK/Code/Review/itkTransformFileWriterWithFactory.h index 392777c452..97b53b42cc 100644 --- a/Utilities/ITK/Code/Review/itkTransformFileWriterWithFactory.h +++ b/Utilities/ITK/Code/Review/itkTransformFileWriterWithFactory.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransformFileWriterWithFactory.h,v $ Language: C++ - Date: $Date: 2007-08-10 15:41:28 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -67,7 +67,7 @@ public: /** Set/Get the precision of the writing */ itkSetMacro(Precision,unsigned int); - itkGetMacro(Precision,unsigned int); + itkGetConstMacro(Precision,unsigned int); /** Write out the transform */ void Update(); diff --git a/Utilities/ITK/Code/Review/itkTransformIOBase.h b/Utilities/ITK/Code/Review/itkTransformIOBase.h index 439c6e694f..84725cab4a 100644 --- a/Utilities/ITK/Code/Review/itkTransformIOBase.h +++ b/Utilities/ITK/Code/Review/itkTransformIOBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransformIOBase.h,v $ Language: C++ - Date: $Date: 2007-08-10 15:40:36 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-05-11 16:37:30 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -75,13 +75,15 @@ public: /** Get the list of transforms resulting from a file read */ TransformListType &GetTransformList() { return m_ReadTransformList; } + TransformListType &GetReadTransformList() { return m_ReadTransformList; } + ConstTransformListType &GetWriteTransformList() { return m_WriteTransformList; } /** Set the list of transforms before writing */ void SetTransformList(ConstTransformListType &transformList); /** Set the writer to append to the specified file */ itkSetMacro( AppendMode, bool ); - itkGetMacro( AppendMode, bool ); + itkGetConstMacro( AppendMode, bool ); itkBooleanMacro( AppendMode ); protected: @@ -92,6 +94,7 @@ protected: void OpenStream(std::ofstream &out, bool binary); void CreateTransform(TransformPointer &ptr, const std::string &ClassName); +private: std::string m_FileName; TransformListType m_ReadTransformList; ConstTransformListType m_WriteTransformList; diff --git a/Utilities/ITK/Code/Review/itkTransformToDeformationFieldSource.txx b/Utilities/ITK/Code/Review/itkTransformToDeformationFieldSource.txx index 707f58b250..cff7a7227b 100644 --- a/Utilities/ITK/Code/Review/itkTransformToDeformationFieldSource.txx +++ b/Utilities/ITK/Code/Review/itkTransformToDeformationFieldSource.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransformToDeformationFieldSource.txx,v $ Language: C++ - Date: $Date: 2008-08-01 13:42:00 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-29 23:54:31 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,7 @@ Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. -This software is distributed WITHOUT ANY WARRANTY; without even +This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. @@ -39,13 +39,12 @@ PURPOSE. See the above copyright notices for more information. namespace itk { - /** * Constructor */ template <class TOutputImage, class TTransformPrecisionType> -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::TransformToDeformationFieldSource() +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::TransformToDeformationFieldSource() { this->m_OutputSpacing.Fill(1.0); this->m_OutputOrigin.Fill(0.0); @@ -54,15 +53,14 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> SizeType size; size.Fill( 0 ); this->m_OutputRegion.SetSize( size ); - + IndexType index; index.Fill( 0 ); this->m_OutputRegion.SetIndex( index ); - - this->m_Transform = IdentityTransform<TTransformPrecisionType, ImageDimension>::New(); - -} // end Constructor + this->m_Transform + = IdentityTransform<TTransformPrecisionType, ImageDimension>::New(); +} // end Constructor /** * Print out a description of self @@ -70,142 +68,133 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> * \todo Add details about this class */ template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::PrintSelf( std::ostream & os, Indent indent ) const +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::PrintSelf( std::ostream & os, Indent indent ) const { Superclass::PrintSelf( os, indent ); - + os << indent << "OutputRegion: " << this->m_OutputRegion << std::endl; os << indent << "OutputSpacing: " << this->m_OutputSpacing << std::endl; os << indent << "OutputOrigin: " << this->m_OutputOrigin << std::endl; os << indent << "OutputDirection: " << this->m_OutputDirection << std::endl; os << indent << "Transform: " << this->m_Transform.GetPointer() << std::endl; - } // end PrintSelf() - /** * Set the output image size. */ template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::SetOutputSize( const SizeType & size ) +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::SetOutputSize( const SizeType & size ) { this->m_OutputRegion.SetSize( size ); } - /** * Get the output image size. */ template <class TOutputImage, class TTransformPrecisionType> -const typename TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::SizeType & -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::GetOutputSize() +const typename TransformToDeformationFieldSource<TOutputImage, + TTransformPrecisionType> + ::SizeType & +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::GetOutputSize() { return this->m_OutputRegion.GetSize(); } - /** * Set the output image index. */ template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::SetOutputIndex( const IndexType & index ) +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::SetOutputIndex( const IndexType & index ) { this->m_OutputRegion.SetIndex( index ); } - /** * Get the output image index. */ template <class TOutputImage, class TTransformPrecisionType> -const typename TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::IndexType & -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::GetOutputIndex() +const typename TransformToDeformationFieldSource<TOutputImage, + TTransformPrecisionType> + ::IndexType & +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::GetOutputIndex() { return this->m_OutputRegion.GetIndex(); } - /** * Set the output image spacing. */ template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::SetOutputSpacing( const double* spacing ) +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::SetOutputSpacing( const double *spacing ) { SpacingType s( spacing ); - this->SetOutputSpacing( s ); + this->SetOutputSpacing( s ); } // end SetOutputSpacing() - /** * Set the output image origin. */ template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::SetOutputOrigin( const double* origin ) +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::SetOutputOrigin( const double *origin ) { OriginType p( origin ); - this->SetOutputOrigin( p ); + this->SetOutputOrigin( p ); } /** Helper method to set the output parameters based on this image */ template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::SetOutputParametersFromImage ( const ImageBaseType * image ) +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::SetOutputParametersFromImage ( const ImageBaseType *image ) { - if( !image ) + if ( !image ) { itkExceptionMacro(<< "Cannot use a null image reference"); } - + this->SetOutputOrigin( image->GetOrigin() ); this->SetOutputSpacing( image->GetSpacing() ); this->SetOutputDirection( image->GetDirection() ); this->SetOutputRegion( image->GetLargestPossibleRegion() ); - } // end SetOutputParametersFromImage() - /** * Set up state of filter before multi-threading. * InterpolatorType::SetInputImage is not thread-safe and hence * has to be set up before ThreadedGenerateData */ template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::BeforeThreadedGenerateData( void ) +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::BeforeThreadedGenerateData( void ) { - if( !this->m_Transform ) + if ( !this->m_Transform ) { itkExceptionMacro(<< "Transform not set"); } - } // end BeforeThreadedGenerateData() - /** * ThreadedGenerateData */ template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::ThreadedGenerateData( +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, int threadId ) { @@ -221,20 +210,18 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> // Otherwise, we use the normal method where the transform is called // for computing the transformation of every point. this->NonlinearThreadedGenerateData( outputRegionForThread, threadId ); - } // end ThreadedGenerateData() - template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::NonlinearThreadedGenerateData( +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::NonlinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, int threadId ) { // Get the output pointer OutputImagePointer outputPtr = this->GetOutput(); - + // Create an iterator that will walk the output region for this thread. typedef ImageRegionIteratorWithIndex<TOutputImage> OutputIteratorType; OutputIteratorType outIt( outputPtr, outputRegionForThread ); @@ -246,8 +233,9 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> PixelType deformation; // the difference // Support for progress methods/callbacks - ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); - + ProgressReporter progress( this, threadId, + outputRegionForThread.GetNumberOfPixels() ); + // Walk the output region outIt.GoToBegin(); while ( !outIt.IsAtEnd() ) @@ -261,8 +249,9 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> // Compute the deformation for ( unsigned int i = 0; i < ImageDimension; ++i ) { - deformation[ i ] = static_cast<PixelValueType>( transformedPoint[ i ] - outputPoint[ i ] ); - } + deformation[i] = static_cast<PixelValueType>( + transformedPoint[i] - outputPoint[i] ); + } // Set it outIt.Set( deformation ); @@ -271,23 +260,22 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> progress.CompletedPixel(); ++outIt; } - } // end NonlinearThreadedGenerateData() - template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::LinearThreadedGenerateData( +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::LinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, int threadId ) { // Get the output pointer - OutputImagePointer outputPtr = this->GetOutput(); + OutputImagePointer outputPtr = this->GetOutput(); // Create an iterator that will walk the output region for this thread. typedef ImageLinearIteratorWithIndex<TOutputImage> OutputIteratorType; OutputIteratorType outIt( outputPtr, outputRegionForThread ); + outIt.SetDirection( 0 ); // Define a few indices that will be used to translate from an input pixel @@ -295,20 +283,21 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> PointType outputPoint; // Coordinates of current output pixel PointType transformedPoint; // Coordinates of transformed pixel PixelType deformation; // the difference - + IndexType index; // Support for progress methods/callbacks - ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); - + ProgressReporter progress( this, threadId, + outputRegionForThread.GetNumberOfPixels() ); + // Determine the position of the first pixel in the scanline outIt.GoToBegin(); index = outIt.GetIndex(); outputPtr->TransformIndexToPhysicalPoint( index, outputPoint ); - + // Compute corresponding transformed pixel position transformedPoint = this->m_Transform->TransformPoint( outputPoint ); - + // Compare with the ResampleImageFilter // Compute delta @@ -318,9 +307,10 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> VectorType delta; ++index[0]; outputPtr->TransformIndexToPhysicalPoint( index, outputPointNeighbour ); - transformedPointNeighbour = this->m_Transform->TransformPoint( outputPointNeighbour ); - SpacingType sp; sp.Fill( 0.0 ); sp[ 0 ] = this->m_OutputSpacing[ 0 ]; - delta = transformedPointNeighbour - transformedPoint - sp; + transformedPointNeighbour = this->m_Transform->TransformPoint( + outputPointNeighbour ); + delta = transformedPointNeighbour - transformedPoint + - ( outputPointNeighbour - outputPoint ); // loop over the vector image while ( !outIt.IsAtEnd() ) @@ -337,7 +327,8 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> // Compute the deformation for ( unsigned int i = 0; i < ImageDimension; ++i ) { - deformation[ i ] = static_cast<PixelValueType>( transformedPoint[ i ] - outputPoint[ i ] ); + deformation[i] = static_cast<PixelValueType>( + transformedPoint[i] - outputPoint[i] ); } // Set it @@ -351,17 +342,15 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> outIt.NextLine(); } - } // end LinearThreadedGenerateData() - -/** +/** * Inform pipeline of required output region */ template <class TOutputImage, class TTransformPrecisionType> -void -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::GenerateOutputInformation( void ) +void +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::GenerateOutputInformation( void ) { // call the superclass' implementation of this method Superclass::GenerateOutputInformation(); @@ -378,23 +367,21 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> outputPtr->SetSpacing( m_OutputSpacing ); outputPtr->SetOrigin( m_OutputOrigin ); outputPtr->SetDirection( m_OutputDirection ); - } // end GenerateOutputInformation() - -/** +/** * Verify if any of the components has been modified. */ template <class TOutputImage, class TTransformPrecisionType> -unsigned long -TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> -::GetMTime( void ) const +unsigned long +TransformToDeformationFieldSource<TOutputImage, TTransformPrecisionType> + ::GetMTime( void ) const { - unsigned long latestTime = Object::GetMTime(); + unsigned long latestTime = Object::GetMTime(); - if( this->m_Transform ) + if ( this->m_Transform ) { - if( latestTime < this->m_Transform->GetMTime() ) + if ( latestTime < this->m_Transform->GetMTime() ) { latestTime = this->m_Transform->GetMTime(); } @@ -402,8 +389,6 @@ TransformToDeformationFieldSource<TOutputImage,TTransformPrecisionType> return latestTime; } // end GetMTime() - - } // end namespace itk #endif // end #ifndef _itkTransformToDeformationFieldSource_txx diff --git a/Utilities/ITK/Code/Review/itkTriangleHelper.h b/Utilities/ITK/Code/Review/itkTriangleHelper.h index 3550fdbdf1..e9d51521c6 100644 --- a/Utilities/ITK/Code/Review/itkTriangleHelper.h +++ b/Utilities/ITK/Code/Review/itkTriangleHelper.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTriangleHelper.h,v $ Language: C++ - Date: $Date: 2008-10-06 00:02:06 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-03-25 21:20:16 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,6 @@ namespace itk /** \class TriangleHelper * \brief Convenient class for various triangles elements computation in * 2D or 3D - * \author Arnaud GELAS */ template< typename TPoint > class TriangleHelper @@ -38,201 +37,47 @@ public: itkStaticConstMacro( PointDimension, unsigned int, PointType::PointDimension ); - static bool IsObtuse( const PointType& iA, const PointType& iB, const PointType& iC ) - { - VectorType v01 = iB - iA; - VectorType v02 = iC - iA; - VectorType v12 = iC - iB; - - if( v01 * v02 < 0.0 ) - { - return true; - } - else - { - if( v02 * v12 < 0.0 ) - { - return true; - } - else - { - if( v01 * -v12 < 0.0 ) - { - return true; - } - else - { - return false; - } - } - } - } - + /** \brief return true if (iA,iB,iC) forms an Obtuse angle (above 90 degrees)*/ + static bool IsObtuse( const PointType& iA, const PointType& iB, const PointType& iC ); + + /** \brief Compute Normal vector to the triangle formed by (iA,iB,iC)*/ static VectorType ComputeNormal ( const PointType& iA, const PointType& iB, - const PointType& iC ) - { - CrossVectorType cross; - VectorType w = cross ( iB - iA, iC - iA ); - CoordRepType l2 = w.GetSquaredNorm(); - - if( l2 != 0.0 ) - { - w /= vcl_sqrt( l2 ); - } - - return w; - } + const PointType& iC ); + /** \brief Compute cotangent(iA,iB,iC)*/ static CoordRepType Cotangent ( const PointType& iA, const PointType& iB, - const PointType& iC ) - { - VectorType v21 = iA - iB; - v21.Normalize(); - - VectorType v23 = iC - iB; - v23.Normalize(); - - CoordRepType bound( 0.999999 ); - - CoordRepType cos_theta = vnl_math_max( -bound, - vnl_math_min( bound, v21 * v23 ) ); - - return 1.0 / vcl_tan( vcl_acos( cos_theta ) ); - } + const PointType& iC ); + /** \brief Compute barycenter, with given weights*/ static PointType ComputeBarycenter ( const CoordRepType& iA1, const PointType& iP1, const CoordRepType& iA2, const PointType& iP2, - const CoordRepType& iA3, const PointType& iP3 ) - { - PointType oPt; - - for ( unsigned int dim = 0; dim < PointDimension; dim++ ) - { - oPt[dim] = iA1 * iP1[dim] + iA2 * iP2[dim] + iA3 * iP3[dim]; - } - - return oPt; - } + const CoordRepType& iA3, const PointType& iP3 ); + /** \brief Compute angles (iA,iB,iC)*/ static CoordRepType ComputeAngle( const PointType& iP1, const PointType& iP2, - const PointType& iP3 ) - { - VectorType v21 = iP1 - iP2; - VectorType v23 = iP3 - iP2; - - CoordRepType v21_l2 = v21.GetSquaredNorm(); - CoordRepType v23_l2 = v23.GetSquaredNorm(); - - if( v21_l2 != 0.0 ) - v21 /= v21_l2; - if( v23_l2 != 0.0 ) - v23 /= v23_l2; - - CoordRepType bound( 0.999999 ); - - CoordRepType cos_theta = vnl_math_max( -bound, - vnl_math_min( bound, v21 * v23 ) ); - - return vcl_acos( cos_theta ); - } + const PointType& iP3 ); + /** \brief Compute center of mass*/ static PointType ComputeGravityCenter ( const PointType& iP1, const PointType& iP2, - const PointType& iP3 ) - { - PointType oPt; - CoordRepType inv_3 = 1.0 / 3.; - - for ( unsigned int dim = 0; dim < PointDimension; dim++ ) - { - oPt[dim] = ( iP1[dim] + iP2[dim] + iP3[dim] ) * inv_3; - } - - return oPt; - } + const PointType& iP3 ); + /** \brief Compute circum center*/ static PointType ComputeCircumCenter ( const PointType& iP1, const PointType& iP2, - const PointType& iP3 ) - { - PointType oPt; - oPt.Fill ( 0.0 ); - - CoordRepType a = iP2.SquaredEuclideanDistanceTo ( iP3 ); - CoordRepType b = iP1.SquaredEuclideanDistanceTo ( iP3 ); - CoordRepType c = iP2.SquaredEuclideanDistanceTo ( iP1 ); - - CoordRepType Weight[3]; - Weight[0] = a * ( b + c - a ); - Weight[1] = b * ( c + a - b ); - Weight[2] = c * ( a + b - c ); - - CoordRepType SumWeight = Weight[0] + Weight[1] + Weight[2]; - - if ( SumWeight != 0.0 ) - { - SumWeight = 1.0 / SumWeight; - - for ( unsigned int dim = 0; dim < PointDimension; dim++ ) - { - oPt[dim] = ( Weight[0] * iP1[dim] + Weight[1] * iP2[dim] + Weight[2] * iP3[dim] ) * SumWeight; - } - } - - - return oPt; - } + const PointType& iP3 ); + /** \brief Compute circum center constrained to be inside the triangle.*/ static PointType ComputeConstrainedCircumCenter ( const PointType& iP1, - const PointType& iP2, const PointType& iP3 ) - { - PointType oPt; - CoordRepType a = iP2.SquaredEuclideanDistanceTo ( iP3 ); - CoordRepType b = iP1.SquaredEuclideanDistanceTo ( iP3 ); - CoordRepType c = iP2.SquaredEuclideanDistanceTo ( iP1 ); - - CoordRepType Weight[3]; - Weight[0] = a * ( b + c - a ); - Weight[1] = b * ( c + a - b ); - Weight[2] = c * ( a + b - c ); - - for ( unsigned int i = 0; i < 3; i++ ) - { - if ( Weight[i] < 0.0 ) - { - Weight[i] = 0.; - } - } - - CoordRepType SumWeight = Weight[0] + Weight[1] + Weight[2]; - - if ( SumWeight != 0.0 ) - { - SumWeight = 1.0 / SumWeight; - - for ( unsigned int dim = 0; dim < PointDimension; dim++ ) - { - oPt[dim] = ( Weight[0] * iP1[dim] + Weight[1] * iP2[dim] + Weight[2] * iP3[dim] ) * SumWeight; - } - } - - return oPt; - } - - static CoordRepType ComputeArea ( const PointType& iP1, const PointType& iP2, const PointType& iP3 ) - { - CoordRepType a = iP2.EuclideanDistanceTo ( iP3 ); - CoordRepType b = iP1.EuclideanDistanceTo ( iP3 ); - CoordRepType c = iP2.EuclideanDistanceTo ( iP1 ); - - CoordRepType s = 0.5 * ( a + b + c ); - return static_cast< CoordRepType > ( vcl_sqrt ( s * ( s - a ) * ( s - b ) * ( s - c ) ) ); - } + const PointType& iP2, const PointType& iP3 ); + + /** \brief Compute Area.*/ + static CoordRepType ComputeArea ( const PointType& iP1, const PointType& iP2, const PointType& iP3 ); protected: TriangleHelper( ); @@ -247,4 +92,5 @@ private: }; } +#include "itkTriangleHelper.txx" #endif diff --git a/Utilities/ITK/Code/Review/itkTriangleHelper.txx b/Utilities/ITK/Code/Review/itkTriangleHelper.txx new file mode 100644 index 0000000000..69acb9bb06 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkTriangleHelper.txx @@ -0,0 +1,238 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkTriangleHelper.txx,v $ + Language: C++ + Date: $Date: 2009-03-26 15:00:27 $ + Version: $Rev$ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkTriangleHelper_txx +#define __itkTriangleHelper_txx + +#include "itkTriangleHelper.h" + +namespace itk +{ +template< typename TPoint > +bool TriangleHelper< TPoint >:: +IsObtuse( const PointType& iA, const PointType& iB, const PointType& iC ) +{ + VectorType v01 = iB - iA; + VectorType v02 = iC - iA; + VectorType v12 = iC - iB; + + if( v01 * v02 < 0.0 ) + { + return true; + } + else + { + if( v02 * v12 < 0.0 ) + { + return true; + } + else + { + if( v01 * -v12 < 0.0 ) + { + return true; + } + else + { + return false; + } + } + } +} + +template< typename TPoint > +typename TriangleHelper< TPoint >::VectorType +TriangleHelper< TPoint >::ComputeNormal( const PointType& iA, + const PointType& iB, + const PointType& iC ) +{ + CrossVectorType cross; + VectorType w = cross ( iB - iA, iC - iA ); + CoordRepType l2 = w.GetSquaredNorm(); + + if( l2 != 0.0 ) + { + w /= vcl_sqrt( l2 ); + } + + return w; +} + +template< typename TPoint > +typename TriangleHelper< TPoint >::CoordRepType +TriangleHelper< TPoint >::Cotangent ( const PointType& iA, + const PointType& iB, + const PointType& iC ) +{ + VectorType v21 = iA - iB; + CoordRepType v21_l2 = v21.GetSquaredNorm(); + if( v21_l2 != 0.0 ) + { + v21 /= vcl_sqrt( v21_l2 ); + } + else + { + } + + VectorType v23 = iC - iB; + CoordRepType v23_l2 = v23.GetSquaredNorm(); + if( v23_l2 != 0.0 ) + { + v23 /= vcl_sqrt( v23_l2 ); + } + else + { + } + + CoordRepType bound( 0.999999 ); + + CoordRepType cos_theta = vnl_math_max( -bound, + vnl_math_min( bound, v21 * v23 ) ); + + return 1.0 / vcl_tan( vcl_acos( cos_theta ) ); +} + +template< typename TPoint > +typename TriangleHelper< TPoint >::PointType +TriangleHelper< TPoint >::ComputeBarycenter ( + const CoordRepType& iA1, const PointType& iP1, + const CoordRepType& iA2, const PointType& iP2, + const CoordRepType& iA3, const PointType& iP3 ) +{ + PointType oPt; + + CoordRepType total = iA1 + iA2 + iA3; + if( total == 0. ) + { + //in such case there is no barycenter; + oPt.Fill( 0. ); + return oPt; + } + + CoordRepType inv_total = 1. / total; + CoordRepType a1 = iA1 * inv_total; + CoordRepType a2 = iA2 * inv_total; + CoordRepType a3 = iA3 * inv_total; + + for ( unsigned int dim = 0; dim < PointDimension; ++dim ) + { + oPt[dim] = a1 * iP1[dim] + a2 * iP2[dim] + a3 * iP3[dim]; + } + + return oPt; +} + +template< typename TPoint > +typename TriangleHelper< TPoint >::CoordRepType +TriangleHelper< TPoint >::ComputeAngle( const PointType& iP1, + const PointType& iP2, + const PointType& iP3 ) +{ + VectorType v21 = iP1 - iP2; + VectorType v23 = iP3 - iP2; + + CoordRepType v21_l2 = v21.GetSquaredNorm(); + CoordRepType v23_l2 = v23.GetSquaredNorm(); + + if( v21_l2 != 0.0 ) + v21 /= vcl_sqrt( v21_l2 ); + if( v23_l2 != 0.0 ) + v23 /= vcl_sqrt( v23_l2 ); + + CoordRepType bound( 0.999999 ); + + CoordRepType cos_theta = vnl_math_max( -bound, + vnl_math_min( bound, v21 * v23 ) ); + + return vcl_acos( cos_theta ); +} + +template< typename TPoint > +typename TriangleHelper< TPoint >::PointType +TriangleHelper< TPoint >::ComputeGravityCenter ( + const PointType& iP1, + const PointType& iP2, + const PointType& iP3 ) +{ + return ComputeBarycenter( 1., iP1, 1., iP2, 1., iP3 ); +} + +template< typename TPoint > +typename TriangleHelper< TPoint >::PointType +TriangleHelper< TPoint >::ComputeCircumCenter ( + const PointType& iP1, + const PointType& iP2, + const PointType& iP3 ) +{ + PointType oPt; + oPt.Fill ( 0.0 ); + + CoordRepType a = iP2.SquaredEuclideanDistanceTo ( iP3 ); + CoordRepType b = iP1.SquaredEuclideanDistanceTo ( iP3 ); + CoordRepType c = iP2.SquaredEuclideanDistanceTo ( iP1 ); + + CoordRepType Weight[3]; + Weight[0] = a * ( b + c - a ); + Weight[1] = b * ( c + a - b ); + Weight[2] = c * ( a + b - c ); + + return ComputeBarycenter( Weight[0], iP1, Weight[1], iP2, Weight[2], iP3 ); +} + +template< typename TPoint > +typename TriangleHelper< TPoint >::PointType +TriangleHelper< TPoint >::ComputeConstrainedCircumCenter ( const PointType& iP1, + const PointType& iP2, const PointType& iP3 ) +{ + PointType oPt; + CoordRepType a = iP2.SquaredEuclideanDistanceTo ( iP3 ); + CoordRepType b = iP1.SquaredEuclideanDistanceTo ( iP3 ); + CoordRepType c = iP2.SquaredEuclideanDistanceTo ( iP1 ); + + CoordRepType Weight[3]; + Weight[0] = a * ( b + c - a ); + Weight[1] = b * ( c + a - b ); + Weight[2] = c * ( a + b - c ); + + for ( unsigned int i = 0; i < 3; i++ ) + { + if ( Weight[i] < 0.0 ) + { + Weight[i] = 0.; + } + } + + return ComputeBarycenter( Weight[0], iP1, Weight[1], iP2, Weight[2], iP3 ); +} + +template< typename TPoint > +typename TriangleHelper< TPoint >::CoordRepType +TriangleHelper< TPoint >::ComputeArea ( const PointType& iP1, + const PointType& iP2, + const PointType& iP3 ) +{ + CoordRepType a = iP2.EuclideanDistanceTo ( iP3 ); + CoordRepType b = iP1.EuclideanDistanceTo ( iP3 ); + CoordRepType c = iP2.EuclideanDistanceTo ( iP1 ); + + CoordRepType s = 0.5 * ( a + b + c ); + return static_cast< CoordRepType > ( vcl_sqrt ( s * ( s - a ) * ( s - b ) * ( s - c ) ) ); +} + +} + +#endif diff --git a/Utilities/ITK/Code/Review/itkTxtTransformIO.cxx b/Utilities/ITK/Code/Review/itkTxtTransformIO.cxx index 3bd65d307b..5fad35cad6 100644 --- a/Utilities/ITK/Code/Review/itkTxtTransformIO.cxx +++ b/Utilities/ITK/Code/Review/itkTxtTransformIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTxtTransformIO.cxx,v $ Language: C++ - Date: $Date: 2008-07-25 18:02:39 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-05-11 16:37:34 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,12 +81,12 @@ Read() { TransformPointer transform; std::ifstream in; - in.open ( m_FileName.c_str(), std::ios::in | std::ios::binary ); + in.open ( this->GetFileName(), std::ios::in | std::ios::binary ); if( in.fail() ) { in.close(); itkExceptionMacro ( "The file could not be opened for read access " - << std::endl << "Filename: \"" << m_FileName << "\"" ); + << std::endl << "Filename: \"" << this->GetFileName() << "\"" ); } OStringStream InData; @@ -158,7 +158,7 @@ Read() if ( Name == "Transform" ) { this->CreateTransform(transform,Value); - m_ReadTransformList.push_back ( transform ); + this->GetReadTransformList().push_back ( transform ); } else if ( Name == "Parameters" || Name == "FixedParameters" ) { @@ -220,14 +220,14 @@ void TxtTransformIO:: Write() { - ConstTransformListType::iterator it = m_WriteTransformList.begin(); + ConstTransformListType::iterator it = this->GetWriteTransformList().begin(); vnl_vector<double> TempArray; std::ofstream out; this->OpenStream(out,false); out << "#Insight Transform File V1.0" << std::endl; int count = 0; - while(it != m_WriteTransformList.end()) + while(it != this->GetWriteTransformList().end()) { out << "# Transform " << count << std::endl; out << "Transform: " << (*it)->GetTransformTypeAsString() << std::endl; diff --git a/Utilities/ITK/Code/Review/itkUnconstrainedRegionBasedLevelSetFunctionSharedData.h b/Utilities/ITK/Code/Review/itkUnconstrainedRegionBasedLevelSetFunctionSharedData.h new file mode 100644 index 0000000000..2b39d5f86f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkUnconstrainedRegionBasedLevelSetFunctionSharedData.h @@ -0,0 +1,147 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkUnconstrainedRegionBasedLevelSetFunctionSharedData.h,v $ + Language: C++ + Date: $Date: 2009-05-21 22:03:29 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkUnconstrainedRegionBasedLevelSetFunctionSharedData_h +#define __itkUnconstrainedRegionBasedLevelSetFunctionSharedData_h + +#include "itkRegionBasedLevelSetFunctionSharedData.h" + +namespace itk +{ + +/** \class UnconstrainedRegionBasedLevelSetFunctionSharedData + * + * \brief Helper class used to share data in the ScalarChanAndVeseLevelSetFunction. + * + * This class holds cache data used during the computation of the LevelSet updates. + * + * Based on the paper: + * + * "An active contour model without edges" + * T. Chan and L. Vese. + * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. + * + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * This code was taken from the Insight Journal paper: + * + * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" + * http://www.insight-journal.org/browse/publication/642 + * http://hdl.handle.net/10380/3055 + * + * That is based on the papers: + * + * "Level Set Segmentation: Active Contours without edge" + * http://www.insight-journal.org/browse/publication/322 + * http://hdl.handle.net/1926/1532 + * + * and + * + * "Level set segmentation using coupled active surfaces" + * http://www.insight-journal.org/browse/publication/323 + * http://hdl.handle.net/1926/1533 + * + * + */ +template < class TInputImage, class TFeatureImage, class TSingleData > +class UnconstrainedRegionBasedLevelSetFunctionSharedData : + public RegionBasedLevelSetFunctionSharedData< TInputImage, TFeatureImage, TSingleData > +{ +public: + + typedef UnconstrainedRegionBasedLevelSetFunctionSharedData Self; + typedef RegionBasedLevelSetFunctionSharedData< TInputImage, TFeatureImage, TSingleData > + Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + itkStaticConstMacro( ImageDimension, unsigned int, TFeatureImage::ImageDimension ); + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + itkTypeMacro(UnconstrainedRegionBasedLevelSetFunctionSharedData, RegionBasedLevelSetFunctionSharedData); + + typedef TInputImage InputImageType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputImageConstPointer InputImageConstPointer; + typedef typename Superclass::InputPixelType InputPixelType; + typedef typename Superclass::InputRegionType InputRegionType; + typedef typename Superclass::InputSizeType InputSizeType; + typedef typename Superclass::InputSizeValueType InputSizeValueType; + typedef typename Superclass::InputSpacingType InputSpacingType; + typedef typename Superclass::InputIndexType InputIndexType; + typedef typename Superclass::InputIndexValueType InputIndexValueType; + typedef typename Superclass::InputPointType InputPointType; + + typedef TFeatureImage FeatureImageType; + typedef typename Superclass::FeatureImagePointer FeatureImagePointer; + typedef typename Superclass::FeatureImageConstPointer FeatureImageConstPointer; + typedef typename Superclass::FeaturePixelType FeaturePixelType; + typedef typename Superclass::FeatureRegionType FeatureRegionType; + typedef typename Superclass::FeatureSizeType FeatureSizeType; + typedef typename Superclass::FeatureSizeValueType FeatureSizeValueType; + typedef typename Superclass::FeatureSpacingType FeatureSpacingType; + typedef typename Superclass::FeatureIndexType FeatureIndexType; + typedef typename Superclass::FeaturePointType FeaturePointType; + + typedef typename Superclass::ListPixelType ListPixelType; + typedef typename Superclass::ListImageType ListImageType; + typedef typename Superclass::ListImagePointer ListImagePointer; + typedef typename Superclass::ListImageConstPointer ListImageConstPointer; + typedef typename Superclass::ListRegionType ListRegionType; + typedef typename Superclass::ListSizeType ListSizeType; + typedef typename Superclass::ListSizeValueType ListSizeValueType; + typedef typename Superclass::ListSpacingType ListSpacingType; + typedef typename Superclass::ListIndexType ListIndexType; + typedef typename Superclass::ListIndexValueType ListIndexValueType; + typedef typename Superclass::ListPointType ListPointType; + typedef typename Superclass::ListIteratorType ListIteratorType; + + typedef typename Superclass::CentroidVectorType CentroidVectorType; + typedef typename Superclass::SampleType SampleType; + typedef typename Superclass::TreeGeneratorType TreeGeneratorType; + typedef typename Superclass::TreePointer TreePointer; + typedef typename Superclass::TreeType TreeType; + typedef typename Superclass::KdTreePointer KdTreePointer; + + typedef TSingleData LevelSetDataType; + typedef typename Superclass::LevelSetDataPointer LevelSetDataPointer; + typedef typename Superclass::LevelSetDataPointerVector LevelSetDataPointerVector; + typedef typename Superclass::LevelSetDataPointerVectorIterator LevelSetDataPointerVectorIterator; + + void PopulateListImage() + { + ListPixelType L; + for( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + { + L.push_back( i ); + } + this->m_NearestNeighborListImage->FillBuffer( L ); + } + +protected: + UnconstrainedRegionBasedLevelSetFunctionSharedData() : Superclass( ){} + ~UnconstrainedRegionBasedLevelSetFunctionSharedData(){} + +private: + UnconstrainedRegionBasedLevelSetFunctionSharedData(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented +}; + +} //end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkVTKPolyDataReader.txx b/Utilities/ITK/Code/Review/itkVTKPolyDataReader.txx index 37ab09c0ee..508f1ac5fe 100644 --- a/Utilities/ITK/Code/Review/itkVTKPolyDataReader.txx +++ b/Utilities/ITK/Code/Review/itkVTKPolyDataReader.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVTKPolyDataReader.txx,v $ Language: C++ - Date: $Date: 2008-06-15 02:42:12 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-06 18:29:00 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,6 +20,7 @@ #include "itkVTKPolyDataReader.h" #include <fstream> #include <stdio.h> +#include <string.h> namespace itk { diff --git a/Utilities/ITK/Code/Review/itkVTKPolyDataWriter.txx b/Utilities/ITK/Code/Review/itkVTKPolyDataWriter.txx index 67fd707a38..3ab6f9fca2 100644 --- a/Utilities/ITK/Code/Review/itkVTKPolyDataWriter.txx +++ b/Utilities/ITK/Code/Review/itkVTKPolyDataWriter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVTKPolyDataWriter.txx,v $ Language: C++ - Date: $Date: 2009-01-08 00:20:05 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-05-15 19:12:49 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,9 +25,9 @@ namespace itk { -// +// // Constructor -// +// template<class TInputMesh> VTKPolyDataWriter<TInputMesh> ::VTKPolyDataWriter() @@ -36,18 +36,18 @@ VTKPolyDataWriter<TInputMesh> this->m_FileName = ""; } -// +// // Destructor -// +// template<class TInputMesh> VTKPolyDataWriter<TInputMesh> ::~VTKPolyDataWriter() { } -// +// // Set the input mesh -// +// template<class TInputMesh> void VTKPolyDataWriter<TInputMesh> @@ -56,9 +56,9 @@ VTKPolyDataWriter<TInputMesh> this->m_Input = input; } -// +// // Write the input mesh to the output file -// +// template<class TInputMesh> void VTKPolyDataWriter<TInputMesh> ::Update() @@ -66,9 +66,9 @@ void VTKPolyDataWriter<TInputMesh> this->GenerateData(); } -// +// // Write the input mesh to the output file -// +// template<class TInputMesh> void VTKPolyDataWriter<TInputMesh> ::Write() @@ -110,7 +110,7 @@ VTKPolyDataWriter<TInputMesh> outputFile << "POINTS " << numberOfPoints << " float" << std::endl; const PointsContainer * points = this->m_Input->GetPoints(); - + std::map< PointIdentifier, PointIdentifier > IdMap; PointIdentifier k = 0; @@ -123,7 +123,20 @@ VTKPolyDataWriter<TInputMesh> while( pointIterator != pointEnd ) { PointType point = pointIterator.Value(); - outputFile << point[0] << " " << point[1] << " " << point[2] << std::endl; + + outputFile << point[0] << " " << point[1]; + + if( TInputMesh::PointDimension > 2 ) + { + outputFile << " " << point[2]; + } + else + { + outputFile << " " << "0.0"; + } + + outputFile << std::endl; + IdMap[ pointIterator.Index() ] = k++; pointIterator++; } @@ -155,11 +168,11 @@ VTKPolyDataWriter<TInputMesh> case 2: //TRIANGLE_CELL: case 3: //QUADRILATERAL_CELL: case 4: //POLYGON_CELL: - case 8: //QUADRATIC_TRIANGLE_CELL: + case 8: //QUADRATIC_TRIANGLE_CELL: numberOfPolygons++; break; default: - std::cerr << "Unhandled cell (volumic?)." << std::endl; + std::cerr << "Unhandled cell (volumic?)." << std::endl; } cellIterator++; } @@ -174,7 +187,7 @@ VTKPolyDataWriter<TInputMesh> { outputFile << "LINES " << numberOfEdges << " " << 3*numberOfEdges; outputFile << std::endl; - + cellIterator = cells->Begin(); while( cellIterator != cellEnd ) { @@ -206,14 +219,15 @@ VTKPolyDataWriter<TInputMesh> if( numberOfPolygons ) { // This could be optimized but at least now any polygonal - // mesh can be saved. + // mesh can be saved. cellIterator = cells->Begin(); unsigned long n( 0 ); while( cellIterator != cells->End() ) { CellType * cellPointer = cellIterator.Value(); - if( cellPointer->GetType() != 1 ) + if( cellPointer->GetType() != CellType::VERTEX_CELL && + cellPointer->GetType() != CellType::LINE_CELL ) { n += cellPointer->GetNumberOfPoints(); } @@ -221,7 +235,7 @@ VTKPolyDataWriter<TInputMesh> } outputFile << "POLYGONS " << numberOfPolygons << " " << n+numberOfPolygons; outputFile << std::endl; - + cellIterator = cells->Begin(); while( cellIterator != cellEnd ) { @@ -231,7 +245,7 @@ VTKPolyDataWriter<TInputMesh> case 2: //TRIANGLE_CELL: case 3: //QUADRILATERAL_CELL: case 4: //POLYGON_CELL: - case 8: //QUADRATIC_TRIANGLE_CELL: + case 8: //QUADRATIC_TRIANGLE_CELL: { PointIdIterator pointIdIterator = cellPointer->PointIdsBegin(); PointIdIterator pointIdEnd = cellPointer->PointIdsEnd(); diff --git a/Utilities/ITK/Code/Review/itkValuedRegionalExtremaImageFilter.h b/Utilities/ITK/Code/Review/itkValuedRegionalExtremaImageFilter.h index 70f167ba2d..ca36a60f4d 100644 --- a/Utilities/ITK/Code/Review/itkValuedRegionalExtremaImageFilter.h +++ b/Utilities/ITK/Code/Review/itkValuedRegionalExtremaImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkValuedRegionalExtremaImageFilter.h,v $ Language: C++ - Date: $Date: 2008-02-07 15:58:06 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -129,7 +129,7 @@ public: /** * Get whether the image is flat or not. */ - itkGetMacro(Flat, bool); + itkGetConstMacro(Flat, bool); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ diff --git a/Utilities/ITK/Code/Review/itkVanHerkGilWermanErodeDilateImageFilter.h b/Utilities/ITK/Code/Review/itkVanHerkGilWermanErodeDilateImageFilter.h index 0acf5707c4..8d897ab931 100644 --- a/Utilities/ITK/Code/Review/itkVanHerkGilWermanErodeDilateImageFilter.h +++ b/Utilities/ITK/Code/Review/itkVanHerkGilWermanErodeDilateImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVanHerkGilWermanErodeDilateImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-07 03:20:20 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -78,7 +78,7 @@ public: /** Set/Get the boundary value. */ void SetBoundary( const InputImagePixelType value ); - itkGetMacro(Boundary, InputImagePixelType); + itkGetConstMacro(Boundary, InputImagePixelType); protected: diff --git a/Utilities/ITK/Code/Review/itkVanHerkGilWermanUtilities.txx b/Utilities/ITK/Code/Review/itkVanHerkGilWermanUtilities.txx index eae612485f..e013f35931 100644 --- a/Utilities/ITK/Code/Review/itkVanHerkGilWermanUtilities.txx +++ b/Utilities/ITK/Code/Review/itkVanHerkGilWermanUtilities.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVanHerkGilWermanUtilities.txx,v $ Language: C++ - Date: $Date: 2008-10-20 16:32:08 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-05-08 19:48:04 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -352,17 +352,26 @@ void DoFace(typename TImage::ConstPointer input, const typename TImage::RegionType face) { // iterate over the face - typedef ImageRegionConstIteratorWithIndex<TImage> ItType; - ItType it(input, face); - it.GoToBegin(); + + // we can't use an iterator with a region outside the image. All we need here is to + // iterate over all the indexes of the face, without accessing the content of the image. + // I can't find any cleaner way, so we use a dumb image, not even allocated, to iterate + // over all the indexes inside the region. + // + // typedef ImageRegionConstIteratorWithIndex<TImage> ItType; + // ItType it(input, face); + + typename TImage::Pointer dumbImg = TImage::New(); + dumbImg->SetRegions( face ); + TLine NormLine = line; NormLine.Normalize(); // set a generous tolerance float tol = 1.0/LineOffsets.size(); TFunction m_TF; - while (!it.IsAtEnd()) + for( unsigned int it=0; it<face.GetNumberOfPixels(); it++ ) { - typename TImage::IndexType Ind = it.GetIndex(); + typename TImage::IndexType Ind = dumbImg->ComputeIndex( it ); unsigned start, end, len; if (FillLineBuffer<TImage, TBres, TLine>(input, Ind, NormLine, tol, LineOffsets, AllImage, pixbuffer, start, end)) @@ -441,7 +450,6 @@ void DoFace(typename TImage::ConstPointer input, CopyLineToImage<TImage, TBres>(output, Ind, LineOffsets, pixbuffer, start, end); } - ++it; } } diff --git a/Utilities/ITK/Code/Review/itkVectorCentralDifferenceImageFunction.h b/Utilities/ITK/Code/Review/itkVectorCentralDifferenceImageFunction.h index 9d687348da..a8549e4bda 100644 --- a/Utilities/ITK/Code/Review/itkVectorCentralDifferenceImageFunction.h +++ b/Utilities/ITK/Code/Review/itkVectorCentralDifferenceImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorCentralDifferenceImageFunction.h,v $ Language: C++ - Date: $Date: 2008-07-04 23:09:49 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -139,6 +139,21 @@ public: return this->EvaluateAtIndex( index ); } + /** The UseImageDirection flag determines whether image derivatives are + * computed with respect to the image grid or with respect to the physical + * space. When this flag is ON the derivatives are computed with respect to + * the coordinate system of physical space. The difference is whether we take + * into account the image Direction or not. The flag ON will take into + * account the image direction and will result in an extra matrix + * multiplication compared to the amount of computation performed when the + * flag is OFF. + * The default value of this flag is the same as the CMAKE option + * ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE (i.e ON by default when ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE is ON, + * and OFF by default when ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE is OFF).*/ + itkSetMacro( UseImageDirection, bool ); + itkGetConstMacro( UseImageDirection, bool ); + itkBooleanMacro( UseImageDirection ); + protected: VectorCentralDifferenceImageFunction(); ~VectorCentralDifferenceImageFunction(){}; @@ -148,6 +163,10 @@ private: VectorCentralDifferenceImageFunction( const Self& ); //purposely not implemented void operator=( const Self& ); //purposely not implemented + // flag to take or not the image direction into account + // when computing the derivatives. + bool m_UseImageDirection; + }; } // end namespace itk diff --git a/Utilities/ITK/Code/Review/itkVectorCentralDifferenceImageFunction.txx b/Utilities/ITK/Code/Review/itkVectorCentralDifferenceImageFunction.txx index 7fa3858841..ce2f6cdaa4 100644 --- a/Utilities/ITK/Code/Review/itkVectorCentralDifferenceImageFunction.txx +++ b/Utilities/ITK/Code/Review/itkVectorCentralDifferenceImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorCentralDifferenceImageFunction.txx,v $ Language: C++ - Date: $Date: 2008-07-04 23:09:49 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-03-16 15:52:13 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -31,6 +31,11 @@ template <class TInputImage, class TCoordRep> VectorCentralDifferenceImageFunction<TInputImage,TCoordRep> ::VectorCentralDifferenceImageFunction() { +#if defined(ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE) + this->m_UseImageDirection = true; +#else + this->m_UseImageDirection = false; +#endif } @@ -43,6 +48,7 @@ VectorCentralDifferenceImageFunction<TInputImage,TCoordRep> ::PrintSelf(std::ostream& os, Indent indent) const { this->Superclass::PrintSelf(os,indent); + os << indent << "UseImageDirection = " << this->m_UseImageDirection << std::endl; } @@ -59,7 +65,6 @@ VectorCentralDifferenceImageFunction<TInputImage,TCoordRep> derivative.Fill( 0.0 ); IndexType neighIndex = index; - InputPixelType pix; const typename InputImageType::SizeType& size = this->GetInputImage()->GetBufferedRegion().GetSize(); @@ -80,26 +85,50 @@ VectorCentralDifferenceImageFunction<TInputImage,TCoordRep> } // compute derivative + const double deriv_weight = 0.5 / this->GetInputImage()->GetSpacing()[dim]; + neighIndex[dim] += 1; - pix = this->GetInputImage()->GetPixel( neighIndex ); + const InputPixelType & pixf = this->GetInputImage()->GetPixel( neighIndex ); for (unsigned int vdim=0; vdim<Dimension; ++vdim) { - derivative(vdim,dim) = pix[vdim]; + derivative(vdim,dim) = pixf[vdim]; } neighIndex[dim] -= 2; - pix = this->GetInputImage()->GetPixel( neighIndex ); + const InputPixelType & pixb = this->GetInputImage()->GetPixel( neighIndex ); for (unsigned int vdim=0; vdim<Dimension; ++vdim) { - derivative(vdim,dim) -= pix[vdim]; + derivative(vdim,dim) -= pixb[vdim]; + derivative(vdim,dim) *= deriv_weight; } + + neighIndex[dim] += 1; + } - for (unsigned int vdim=0; vdim<Dimension; ++vdim) +#ifdef ITK_USE_ORIENTED_IMAGE_DIRECTION + if( this->m_UseImageDirection ) + { + OutputType orientedderivative; + const typename InputImageType::DirectionType & direction + = this->GetInputImage()->GetDirection(); + for ( unsigned int i = 0; i < TInputImage::ImageDimension; ++i ) { - derivative(vdim,dim) *= 0.5 / this->GetInputImage()->GetSpacing()[dim]; + std::vector<double> sums(Dimension,0.0); + for ( unsigned int j = 0; j < TInputImage::ImageDimension; ++j ) + { + for (unsigned int vdim=0; vdim<Dimension; ++vdim) + { + sums[vdim] += direction[i][j] * derivative(vdim,j); + } + } + for (unsigned int vdim=0; vdim<Dimension; ++vdim) + { + orientedderivative(vdim,i) = static_cast<TCoordRep>( sums[vdim] ); + } } - neighIndex[dim] += 1; + return orientedderivative; } +#endif return ( derivative ); diff --git a/Utilities/ITK/Code/Review/itkVectorLinearInterpolateNearestNeighborExtrapolateImageFunction.txx b/Utilities/ITK/Code/Review/itkVectorLinearInterpolateNearestNeighborExtrapolateImageFunction.txx index e5d06da987..928ff46b7f 100644 --- a/Utilities/ITK/Code/Review/itkVectorLinearInterpolateNearestNeighborExtrapolateImageFunction.txx +++ b/Utilities/ITK/Code/Review/itkVectorLinearInterpolateNearestNeighborExtrapolateImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorLinearInterpolateNearestNeighborExtrapolateImageFunction.txx,v $ Language: C++ - Date: $Date: 2008-09-30 14:04:52 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -69,9 +69,9 @@ VectorLinearInterpolateNearestNeighborExtrapolateImageFunction< TInputImage, TCo unsigned int dim; // index over dimension /** - * Compute base index = closest index below point - * Compute distance from point to base index - */ + * Compute base index = closest index below point + * Compute distance from point to base index + */ signed long baseIndex[ImageDimension]; IndexType neighIndex; double distance[ImageDimension]; diff --git a/Utilities/ITK/Code/Review/itkWarpHarmonicEnergyCalculator.h b/Utilities/ITK/Code/Review/itkWarpHarmonicEnergyCalculator.h index 6fbae29b9c..d4bdc1f643 100644 --- a/Utilities/ITK/Code/Review/itkWarpHarmonicEnergyCalculator.h +++ b/Utilities/ITK/Code/Review/itkWarpHarmonicEnergyCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkWarpHarmonicEnergyCalculator.h,v $ Language: C++ - Date: $Date: 2008-09-30 18:07:03 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-23 03:43:42 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -108,7 +108,7 @@ public: /** Set/Get whether or not the filter will use the spacing of the input * image in its calculations */ void SetUseImageSpacing(bool); - itkGetMacro(UseImageSpacing, bool); + itkGetConstMacro(UseImageSpacing, bool); /** Directly Set/Get the array of weights used in the gradient calculations. * Note that calling UseImageSpacingOn will clobber these values. */ @@ -122,7 +122,7 @@ public: void Compute(void); /** Return the smoothness value. */ - itkGetMacro(HarmonicEnergy,double); + itkGetConstMacro(HarmonicEnergy,double); /** Set the region over which the values will be computed */ void SetRegion( const RegionType & region ); diff --git a/Utilities/ITK/Code/Review/itkWinterColormapFunctor.h b/Utilities/ITK/Code/Review/itkWinterColormapFunctor.h new file mode 100644 index 0000000000..4e9f03afbf --- /dev/null +++ b/Utilities/ITK/Code/Review/itkWinterColormapFunctor.h @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkWinterColormapFunctor.h,v $ + Language: C++ + Date: $Date: 2009-05-15 19:22:31 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkWinterColormapFunctor_h +#define __itkWinterColormapFunctor_h + +#include "itkColormapFunctor.h" + +namespace itk { + +namespace Functor { + +/** + * \class WinterColormapFunctor + * \brief Function object which maps a scalar value into an RGB colormap value. + * + * \author Nicholas Tustison, Hui Zhang, Gaetan Lehmann, Paul Yushkevich and ̈James C. Gee + * + * This code was contributed in the Insight Journal paper: + * + * "Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK" + * http://www.insight-journal.org/browse/publication/285 + * http://hdl.handle.net/1926/1452 + * + */ +template< class TScalar, class TRGBPixel > +class ITK_EXPORT WinterColormapFunctor +: public ColormapFunctor<TScalar, TRGBPixel> +{ +public: + + typedef WinterColormapFunctor Self; + typedef ColormapFunctor<TScalar, TRGBPixel> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro( Self ); + + typedef typename Superclass::RGBPixelType RGBPixelType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::RealType RealType; + + virtual RGBPixelType operator()( const TScalar & ) const; + +protected: + WinterColormapFunctor() {}; + ~WinterColormapFunctor() {}; + +private: + WinterColormapFunctor(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace functor + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkWinterColormapFunctor.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkWinterColormapFunctor.txx b/Utilities/ITK/Code/Review/itkWinterColormapFunctor.txx new file mode 100644 index 0000000000..e4554e8bdc --- /dev/null +++ b/Utilities/ITK/Code/Review/itkWinterColormapFunctor.txx @@ -0,0 +1,56 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkWinterColormapFunctor.txx,v $ + Language: C++ + Date: $Date: 2009-05-15 02:47:59 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkWinterColormapFunctor_txx +#define __itkWinterColormapFunctor_txx + +#include "itkWinterColormapFunctor.h" + +namespace itk { + +namespace Functor { + +template <class TScalar, class TRGBPixel> +typename WinterColormapFunctor<TScalar, TRGBPixel>::RGBPixelType +WinterColormapFunctor<TScalar, TRGBPixel> +::operator()( const TScalar & v ) const +{ + // Map the input scalar between [0, 1]. + RealType value = this->RescaleInputValue( v ); + + // Apply the color map. + RealType red = 0.0; + + RealType green = value; + + RealType blue = 1.0 - 0.5 * value; + + // Set the rgb components after rescaling the values. + RGBPixelType pixel; + + pixel[0] = this->RescaleRGBComponentValue( red ); + pixel[1] = this->RescaleRGBComponentValue( green ); + pixel[2] = this->RescaleRGBComponentValue( blue ); + + return pixel; +} + +} // end namespace Functor + +} // end namespace itk + + +#endif diff --git a/Utilities/ITK/Code/SpatialObject/itkAffineGeometryFrame.h b/Utilities/ITK/Code/SpatialObject/itkAffineGeometryFrame.h index acf0b74e7c..0592d14fd5 100644 --- a/Utilities/ITK/Code/SpatialObject/itkAffineGeometryFrame.h +++ b/Utilities/ITK/Code/SpatialObject/itkAffineGeometryFrame.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAffineGeometryFrame.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:26 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-07 14:33:52 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -29,11 +29,11 @@ namespace itk * \brief Describes the geometry of a data object */ template <class TScalarType = double, unsigned int NDimensions = 3> -class AffineGeometryFrame : public itk::Object +class ITK_EXPORT AffineGeometryFrame : public Object { public: typedef AffineGeometryFrame Self; - typedef itk::Object Superclass; + typedef Object Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; @@ -101,6 +101,7 @@ protected: AffineGeometryFrame(); virtual ~AffineGeometryFrame(); + void PrintSelf( std::ostream & os, Indent indent) const; /** used in clone to initialize the newly created geometry */ virtual void InitializeGeometry(Self * newGeometry) const; diff --git a/Utilities/ITK/Code/SpatialObject/itkAffineGeometryFrame.txx b/Utilities/ITK/Code/SpatialObject/itkAffineGeometryFrame.txx index 69e505743f..a1739c8d4f 100644 --- a/Utilities/ITK/Code/SpatialObject/itkAffineGeometryFrame.txx +++ b/Utilities/ITK/Code/SpatialObject/itkAffineGeometryFrame.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAffineGeometryFrame.txx,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:21 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-07 14:33:54 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,6 +32,8 @@ AffineGeometryFrame<TScalarType, NDimensions> m_IndexToObjectTransform->SetIdentity(); m_ObjectToNodeTransform = TransformType::New(); m_ObjectToNodeTransform->SetIdentity(); + m_IndexToNodeTransform = TransformType::New(); + m_IndexToNodeTransform->SetIdentity(); m_IndexToWorldTransform = 0; } @@ -140,6 +142,32 @@ AffineGeometryFrame<TScalarType, NDimensions> } } +/** Print the object */ +template<class TScalarType, unsigned int NDimensions> +void +AffineGeometryFrame<TScalarType, NDimensions> +::PrintSelf( std::ostream& os, Indent indent ) const +{ + Superclass::PrintSelf( os, indent ); + + if (m_BoundingBox) + { + os << indent << "BoundingBox: " + << m_BoundingBox << std::endl; + } + os << indent << "IndexToObjectTransform: " + << m_IndexToObjectTransform << std::endl; + os << indent << "ObjectToNodeTransform: " + << m_ObjectToNodeTransform << std::endl; + os << indent << "IndexToNodeTransform: " + << m_IndexToNodeTransform << std::endl; + if (m_IndexToWorldTransform) + { + os << indent << "IndexToWorldTransform: " + << m_IndexToWorldTransform << std::endl; + } +} + } //namespace #endif diff --git a/Utilities/ITK/Code/SpatialObject/itkArrowSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkArrowSpatialObject.h index cc27c9da3b..d788e455dc 100644 --- a/Utilities/ITK/Code/SpatialObject/itkArrowSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkArrowSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkArrowSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:26 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-07 14:33:56 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,7 +37,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class ArrowSpatialObject +class ITK_EXPORT ArrowSpatialObject :public SpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkBlobSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkBlobSpatialObject.h index d1a577f9c0..74a6e1a1c4 100644 --- a/Utilities/ITK/Code/SpatialObject/itkBlobSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkBlobSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBlobSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:26 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-04-07 14:33:56 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,7 +40,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class BlobSpatialObject +class ITK_EXPORT BlobSpatialObject :public PointBasedSpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkBlobSpatialObject.txx b/Utilities/ITK/Code/SpatialObject/itkBlobSpatialObject.txx index 0534c95829..35d326802a 100644 --- a/Utilities/ITK/Code/SpatialObject/itkBlobSpatialObject.txx +++ b/Utilities/ITK/Code/SpatialObject/itkBlobSpatialObject.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBlobSpatialObject.txx,v $ Language: C++ - Date: $Date: 2008-06-29 01:56:12 $ - Version: $Revision: 1.34 $ + Date: $Date: 2009-04-05 10:56:50 $ + Version: $Revision: 1.35 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -171,7 +171,7 @@ BlobSpatialObject< TDimension > transformedPoint - it->GetPosition(); - if(fabs(difference[0]) <= 0.5 && + if(vcl_fabs(difference[0]) <= 0.5 && vcl_fabs(difference[1]) <= 0.5) { if(TDimension == 3) diff --git a/Utilities/ITK/Code/SpatialObject/itkBoxSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkBoxSpatialObject.h index d4a0bd03aa..36f68385b0 100644 --- a/Utilities/ITK/Code/SpatialObject/itkBoxSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkBoxSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBoxSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-07 14:33:56 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -33,7 +33,7 @@ namespace itk * */ template < unsigned int TDimension = 3 > -class BoxSpatialObject +class ITK_EXPORT BoxSpatialObject : public SpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkContourSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkContourSpatialObject.h index e82e15ea59..f1744bbb7d 100644 --- a/Utilities/ITK/Code/SpatialObject/itkContourSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkContourSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkContourSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-07 14:33:56 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,7 +37,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class ContourSpatialObject +class ITK_EXPORT ContourSpatialObject :public PointBasedSpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkContourSpatialObjectPoint.h b/Utilities/ITK/Code/SpatialObject/itkContourSpatialObjectPoint.h index fbd798bdda..b51679828c 100644 --- a/Utilities/ITK/Code/SpatialObject/itkContourSpatialObjectPoint.h +++ b/Utilities/ITK/Code/SpatialObject/itkContourSpatialObjectPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkContourSpatialObjectPoint.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-07 14:33:56 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,7 +34,7 @@ namespace itk * \sa SpatialObjectPoint */ template < unsigned int TPointDimension = 3 > -class ContourSpatialObjectPoint +class ITK_EXPORT ContourSpatialObjectPoint : public SpatialObjectPoint<TPointDimension> { diff --git a/Utilities/ITK/Code/SpatialObject/itkCylinderSpatialObject.cxx b/Utilities/ITK/Code/SpatialObject/itkCylinderSpatialObject.cxx index 06c5ec46c7..0ee25bbf26 100644 --- a/Utilities/ITK/Code/SpatialObject/itkCylinderSpatialObject.cxx +++ b/Utilities/ITK/Code/SpatialObject/itkCylinderSpatialObject.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCylinderSpatialObject.cxx,v $ Language: C++ - Date: $Date: 2008-06-29 13:04:07 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-05 10:56:52 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -15,6 +15,7 @@ =========================================================================*/ #include "itkCylinderSpatialObject.h" +#include <string.h> namespace itk { diff --git a/Utilities/ITK/Code/SpatialObject/itkCylinderSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkCylinderSpatialObject.h index 47b19a1025..9a3ad8abd4 100644 --- a/Utilities/ITK/Code/SpatialObject/itkCylinderSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkCylinderSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCylinderSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-07 14:33:56 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -29,7 +29,7 @@ namespace itk * * \brief This class describe a cylinder in 3D only. */ -class CylinderSpatialObject +class ITK_EXPORT CylinderSpatialObject : public SpatialObject< 3 > { diff --git a/Utilities/ITK/Code/SpatialObject/itkDTITubeSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkDTITubeSpatialObject.h index 84ef1e419d..22a9fd7561 100644 --- a/Utilities/ITK/Code/SpatialObject/itkDTITubeSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkDTITubeSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDTITubeSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-07 14:33:56 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,7 +38,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class DTITubeSpatialObject : +class ITK_EXPORT DTITubeSpatialObject : public TubeSpatialObject< TDimension, DTITubeSpatialObjectPoint< TDimension > > { diff --git a/Utilities/ITK/Code/SpatialObject/itkDTITubeSpatialObjectPoint.h b/Utilities/ITK/Code/SpatialObject/itkDTITubeSpatialObjectPoint.h index d65fce7be6..c0eda3b93b 100644 --- a/Utilities/ITK/Code/SpatialObject/itkDTITubeSpatialObjectPoint.h +++ b/Utilities/ITK/Code/SpatialObject/itkDTITubeSpatialObjectPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDTITubeSpatialObjectPoint.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-07 14:33:56 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,7 +34,7 @@ namespace itk * \sa DTITubeSpatialObject */ template < unsigned int TPointDimension = 3 > -class DTITubeSpatialObjectPoint +class ITK_EXPORT DTITubeSpatialObjectPoint : public TubeSpatialObjectPoint<TPointDimension> { diff --git a/Utilities/ITK/Code/SpatialObject/itkEllipseSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkEllipseSpatialObject.h index ad66122c48..8c635f19f9 100644 --- a/Utilities/ITK/Code/SpatialObject/itkEllipseSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkEllipseSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEllipseSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.28 $ + Date: $Date: 2009-04-07 14:33:56 $ + Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -31,7 +31,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class EllipseSpatialObject +class ITK_EXPORT EllipseSpatialObject : public SpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkEllipseSpatialObject.txx b/Utilities/ITK/Code/SpatialObject/itkEllipseSpatialObject.txx index 30bb888f5d..9f46eef9e0 100644 --- a/Utilities/ITK/Code/SpatialObject/itkEllipseSpatialObject.txx +++ b/Utilities/ITK/Code/SpatialObject/itkEllipseSpatialObject.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkEllipseSpatialObject.txx,v $ Language: C++ - Date: $Date: 2008-06-29 01:56:12 $ - Version: $Revision: 1.33 $ + Date: $Date: 2009-04-05 10:56:52 $ + Version: $Revision: 1.34 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,6 +18,7 @@ #define __itkEllipseSpatialObject_txx #include "itkEllipseSpatialObject.h" +#include <string.h> namespace itk { diff --git a/Utilities/ITK/Code/SpatialObject/itkGaussianSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkGaussianSpatialObject.h index 915c00a2be..c94e5ff820 100644 --- a/Utilities/ITK/Code/SpatialObject/itkGaussianSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkGaussianSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-04-07 14:33:58 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,18 +32,18 @@ namespace itk * * The Gaussian function G(x) is given by * \f[ - * G(\vec{x}) = m e^{-\|\Sigma^{-1} \vec{x}\|^2 / 2}, + * G(\vec{x}) = m e^{-\|\S^{-1} \vec{x}\|^2 / 2}, * \f] - * where m is a scaling factor set by SetMaximum(), and \f$\Sigma\f$ is - * the (invertible) matrix associated to the IndexToObjectTransform of - * the object. If \f$\Sigma\f$ is symmetric and positive definite, - * and m is chosen so that the integral of G(x) is 1, - * then G will denote a normal distribution with mean 0 and - * covariance matrix \f$\Sigma\f$. + * where m is a scaling factor set by SetMaximum(), and \f$\S\f$ is the + * (invertible) matrix associated to the IndexToObjectTransform of the object + * multiplied by the Sigma parameter. If \f$\S\f$ is symmetric and positive + * definite, and m is chosen so that the integral of G(x) is 1, then G will + * denote a normal distribution with mean 0 and covariance matrix \f$\S \times + * Sigma\f$. */ template < unsigned int TDimension = 3 > -class GaussianSpatialObject +class ITK_EXPORT GaussianSpatialObject : public SpatialObject< TDimension > { @@ -71,6 +71,11 @@ public: itkSetMacro(Radius,ScalarType); itkGetConstReferenceMacro(Radius,ScalarType); + /** The Sigma parameter determines the fallout of the Gaussian inside of the + * region defined by the Radius parameter. */ + itkSetMacro(Sigma,ScalarType); + itkGetConstReferenceMacro(Sigma,ScalarType); + /** The maximum value of the Gaussian (its value at the origin of * the spatial object coordinate system). */ itkSetMacro(Maximum,ScalarType); @@ -119,6 +124,7 @@ protected: ScalarType m_Maximum; ScalarType m_Radius; + ScalarType m_Sigma; /** Print the object information in a stream. */ virtual void PrintSelf( std::ostream& os, Indent indent ) const; diff --git a/Utilities/ITK/Code/SpatialObject/itkGaussianSpatialObject.txx b/Utilities/ITK/Code/SpatialObject/itkGaussianSpatialObject.txx index 9f775cb2e5..e8b57e1a14 100644 --- a/Utilities/ITK/Code/SpatialObject/itkGaussianSpatialObject.txx +++ b/Utilities/ITK/Code/SpatialObject/itkGaussianSpatialObject.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianSpatialObject.txx,v $ Language: C++ - Date: $Date: 2008-06-29 01:56:12 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-02 14:51:02 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -31,6 +31,7 @@ GaussianSpatialObject< TDimension > this->SetTypeName("GaussianSpatialObject"); this->SetDimension(TDimension); m_Radius = 1.0; + m_Sigma = 1.0; m_Maximum = 1.0; } @@ -63,7 +64,7 @@ GaussianSpatialObject< TDimension > { r += transformedPoint[i] * transformedPoint[i]; } - return r; + return r / ( m_Sigma * m_Sigma ); } /** Test whether a point is inside or outside the object @@ -74,6 +75,11 @@ bool GaussianSpatialObject< TDimension > ::IsInside( const PointType & point) const { + if( m_Radius < vnl_math::eps ) + { + return false; + } + this->ComputeLocalBoundingBox(); if( !this->GetBounds()->IsInside(point) ) { @@ -91,21 +97,16 @@ GaussianSpatialObject< TDimension > double r = 0; for(unsigned int i=0;i<TDimension;i++) { - if(m_Radius!=0.0) - { - r += (transformedPoint[i]*transformedPoint[i])/(m_Radius*m_Radius); - } - else if(transformedPoint[i]>0.0) // Degenerate ellipse - { - r = 2; // Keeps function from returning true here - break; - } + r += transformedPoint[i] * transformedPoint[i]; } + + r /= ( m_Radius * m_Radius ); - if(r<1) + if( r < 1.0 ) { return true; } + return false; } @@ -276,7 +277,7 @@ GaussianSpatialObject< TDimension > Superclass::PrintSelf(os, indent); os << "Maximum: " << m_Maximum << std::endl; os << "Radius: " << m_Radius << std::endl; - + os << "Sigma: " << m_Sigma << std::endl; } } // end namespace itk diff --git a/Utilities/ITK/Code/SpatialObject/itkGroupSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkGroupSpatialObject.h index 4c31ef466a..0c2dd78ddb 100644 --- a/Utilities/ITK/Code/SpatialObject/itkGroupSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkGroupSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGroupSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-07 14:33:59 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,7 +36,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class GroupSpatialObject +class ITK_EXPORT GroupSpatialObject :public SpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkImageMaskSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkImageMaskSpatialObject.h index 1ee287c7b9..0340f03624 100644 --- a/Utilities/ITK/Code/SpatialObject/itkImageMaskSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkImageMaskSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageMaskSpatialObject.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:25:07 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-07 14:34:01 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,7 +35,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class ImageMaskSpatialObject +class ITK_EXPORT ImageMaskSpatialObject : public ImageSpatialObject< TDimension, unsigned char > { diff --git a/Utilities/ITK/Code/SpatialObject/itkImageSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkImageSpatialObject.h index e1790b77cf..1a48627bb5 100644 --- a/Utilities/ITK/Code/SpatialObject/itkImageSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkImageSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSpatialObject.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:38 $ - Version: $Revision: 1.28 $ + Date: $Date: 2009-04-07 14:34:01 $ + Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,7 +39,7 @@ namespace itk template < unsigned int TDimension = 3, class TPixelType = unsigned char > -class ImageSpatialObject +class ITK_EXPORT ImageSpatialObject : public SpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkImageSpatialObject.txx b/Utilities/ITK/Code/SpatialObject/itkImageSpatialObject.txx index 35ad90cddf..55fa2d49f5 100644 --- a/Utilities/ITK/Code/SpatialObject/itkImageSpatialObject.txx +++ b/Utilities/ITK/Code/SpatialObject/itkImageSpatialObject.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSpatialObject.txx,v $ Language: C++ - Date: $Date: 2008-11-02 16:03:30 $ - Version: $Revision: 1.60 $ + Date: $Date: 2009-04-07 14:34:02 $ + Version: $Revision: 1.61 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -352,6 +352,8 @@ ImageSpatialObject< TDimension, PixelType > Superclass::PrintSelf(os,indent); os << "Image: " << std::endl; os << indent << m_Image << std::endl; + os << "Interpolator: " << std::endl; + os << indent << m_Interpolator << std::endl; } /** Get the modification time */ diff --git a/Utilities/ITK/Code/SpatialObject/itkLandmarkSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkLandmarkSpatialObject.h index 3ea04bca84..8209ccdb65 100755 --- a/Utilities/ITK/Code/SpatialObject/itkLandmarkSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkLandmarkSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLandmarkSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-07 14:34:03 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,7 +36,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class LandmarkSpatialObject +class ITK_EXPORT LandmarkSpatialObject :public PointBasedSpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkLineSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkLineSpatialObject.h index eb5c0cfc34..5da64b401c 100644 --- a/Utilities/ITK/Code/SpatialObject/itkLineSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkLineSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLineSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-04-07 14:34:04 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,7 +36,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class LineSpatialObject +class ITK_EXPORT LineSpatialObject :public PointBasedSpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkLineSpatialObjectPoint.h b/Utilities/ITK/Code/SpatialObject/itkLineSpatialObjectPoint.h index f7a682055e..117e95b42b 100644 --- a/Utilities/ITK/Code/SpatialObject/itkLineSpatialObjectPoint.h +++ b/Utilities/ITK/Code/SpatialObject/itkLineSpatialObjectPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLineSpatialObjectPoint.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-07 14:34:04 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,7 +35,7 @@ namespace itk */ template < unsigned int TPointDimension = 3 > -class LineSpatialObjectPoint +class ITK_EXPORT LineSpatialObjectPoint : public SpatialObjectPoint<TPointDimension> { diff --git a/Utilities/ITK/Code/SpatialObject/itkMeshSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkMeshSpatialObject.h index dd02846342..f2d37d236f 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMeshSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkMeshSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeshSpatialObject.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:38 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-04-07 14:34:04 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,7 +35,7 @@ namespace itk */ template <class TMesh = Mesh<int> > -class MeshSpatialObject +class ITK_EXPORT MeshSpatialObject : public SpatialObject< ::itk::GetMeshDimension<TMesh>::PointDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaArrowConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaArrowConverter.h index ac2ed6d9a3..6dd6458ad6 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaArrowConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaArrowConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaArrowConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:38 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-07 14:34:04 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaArrowConverter +class ITK_EXPORT MetaArrowConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaBlobConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaBlobConverter.h index 0cd83d34eb..0ff1c8d082 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaBlobConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaBlobConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaBlobConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:38 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-07 14:34:04 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaBlobConverter +class ITK_EXPORT MetaBlobConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaContourConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaContourConverter.h index f397679f4b..343dde02a8 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaContourConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaContourConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaContourConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:38 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-07 14:34:04 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaContourConverter +class ITK_EXPORT MetaContourConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaDTITubeConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaDTITubeConverter.h index 2fa725bcd3..73a4f0d6ee 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaDTITubeConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaDTITubeConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaDTITubeConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:38 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-07 14:34:04 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaDTITubeConverter +class ITK_EXPORT MetaDTITubeConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaEllipseConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaEllipseConverter.h index 79f63ebd21..22845bc91e 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaEllipseConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaEllipseConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaEllipseConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:38 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-07 14:34:04 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaEllipseConverter +class ITK_EXPORT MetaEllipseConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaEvent.h b/Utilities/ITK/Code/SpatialObject/itkMetaEvent.h index 940c3a92fd..2fd04cc9cc 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaEvent.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaEvent.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaEvent.h,v $ Language: C++ - Date: $Date: 2009-01-16 11:37:59 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-07 14:34:04 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,7 +25,7 @@ namespace itk /** \class MetaEvent * \brief Event abstract class */ -class MetaEvent : public ::MetaEvent +class ITK_EXPORT MetaEvent : public ::MetaEvent { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaGaussianConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaGaussianConverter.h index 10c7fd5a74..7322773da5 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaGaussianConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaGaussianConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaGaussianConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:56 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-07 14:34:05 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaGaussianConverter +class ITK_EXPORT MetaGaussianConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaGroupConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaGroupConverter.h index c081c67b7b..3f34a5512f 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaGroupConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaGroupConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaGroupConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:56 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-07 14:34:05 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaGroupConverter +class ITK_EXPORT MetaGroupConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaImageConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaImageConverter.h index 33f829df6a..4222b81fed 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaImageConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaImageConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaImageConverter.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-07 14:34:06 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -29,7 +29,7 @@ namespace itk { template <unsigned int NDimensions = 3, class PixelType = unsigned char> -class MetaImageConverter +class ITK_EXPORT MetaImageConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaLandmarkConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaLandmarkConverter.h index c6310278a6..45d309a3cf 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaLandmarkConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaLandmarkConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaLandmarkConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:56 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-07 14:34:06 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaLandmarkConverter +class ITK_EXPORT MetaLandmarkConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaLineConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaLineConverter.h index 0fc85ae181..3791adc124 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaLineConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaLineConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaLineConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:56 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-07 14:34:07 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaLineConverter +class ITK_EXPORT MetaLineConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaMeshConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaMeshConverter.h index 4921514188..7fcd970024 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaMeshConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaMeshConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaMeshConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:56 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-07 14:34:08 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,7 @@ template <unsigned int NDimensions, typename TMeshTraits = DefaultStaticMeshTraits< PixelType , NDimensions, NDimensions > > -class MetaMeshConverter +class ITK_EXPORT MetaMeshConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaSceneConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaSceneConverter.h index 90ce14c307..3e04e5be61 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaSceneConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaSceneConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaSceneConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:56 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-04-07 14:34:10 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -31,7 +31,7 @@ template <unsigned int NDimensions, typename TMeshTraits = DefaultStaticMeshTraits< PixelType , NDimensions, NDimensions > > -class MetaSceneConverter +class ITK_EXPORT MetaSceneConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaSurfaceConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaSurfaceConverter.h index 117af2ef52..1c3ebe50ba 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaSurfaceConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaSurfaceConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaSurfaceConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:56 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-07 14:34:10 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaSurfaceConverter +class ITK_EXPORT MetaSurfaceConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaTubeConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaTubeConverter.h index de13066263..6a9c4db216 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaTubeConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaTubeConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaTubeConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:56 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-07 14:34:11 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaTubeConverter +class ITK_EXPORT MetaTubeConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkMetaVesselTubeConverter.h b/Utilities/ITK/Code/SpatialObject/itkMetaVesselTubeConverter.h index 4e2d38042d..470dcb1116 100644 --- a/Utilities/ITK/Code/SpatialObject/itkMetaVesselTubeConverter.h +++ b/Utilities/ITK/Code/SpatialObject/itkMetaVesselTubeConverter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaVesselTubeConverter.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:56 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-07 14:34:11 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,7 @@ namespace itk { template <unsigned int NDimensions = 3> -class MetaVesselTubeConverter +class ITK_EXPORT MetaVesselTubeConverter { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkPlaneSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkPlaneSpatialObject.h index 1e94b6dfce..04e426df4c 100644 --- a/Utilities/ITK/Code/SpatialObject/itkPlaneSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkPlaneSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPlaneSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-04-07 14:34:12 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -31,7 +31,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class PlaneSpatialObject +class ITK_EXPORT PlaneSpatialObject : public SpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkPlaneSpatialObject.txx b/Utilities/ITK/Code/SpatialObject/itkPlaneSpatialObject.txx index 2e3a046a15..efcf4ad546 100644 --- a/Utilities/ITK/Code/SpatialObject/itkPlaneSpatialObject.txx +++ b/Utilities/ITK/Code/SpatialObject/itkPlaneSpatialObject.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPlaneSpatialObject.txx,v $ Language: C++ - Date: $Date: 2008-06-29 01:56:12 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-04-07 14:34:13 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -183,6 +183,8 @@ PlaneSpatialObject< TDimension > ::PrintSelf( std::ostream& os, Indent indent ) const { Superclass::PrintSelf(os, indent); + os << indent << "LowerPoint: " << m_LowerPoint << std::endl; + os << indent << "UpperPoint: " << m_UpperPoint << std::endl; } } // end namespace itk diff --git a/Utilities/ITK/Code/SpatialObject/itkPointBasedSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkPointBasedSpatialObject.h index f2baf4af44..b2560ce714 100644 --- a/Utilities/ITK/Code/SpatialObject/itkPointBasedSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkPointBasedSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointBasedSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-07 14:34:13 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,7 +34,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class PointBasedSpatialObject +class ITK_EXPORT PointBasedSpatialObject :public SpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkPolygonGroupSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkPolygonGroupSpatialObject.h index 67d296b3f0..9850dba9b5 100644 --- a/Utilities/ITK/Code/SpatialObject/itkPolygonGroupSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkPolygonGroupSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPolygonGroupSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-04-07 14:34:14 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,8 +51,8 @@ namespace itk */ -template <unsigned int TDimension = 3> class -PolygonGroupSpatialObject +template <unsigned int TDimension = 3> +class ITK_EXPORT PolygonGroupSpatialObject :public GroupSpatialObject<TDimension> { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkPolygonSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkPolygonSpatialObject.h index e2c2b37c26..bba7f4e826 100644 --- a/Utilities/ITK/Code/SpatialObject/itkPolygonSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkPolygonSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPolygonSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-16 11:38:00 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-08 18:27:47 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,8 +26,8 @@ namespace itk * * \brief TODO */ -template <unsigned int TDimension = 3> class -PolygonSpatialObject +template <unsigned int TDimension = 3> +class ITK_EXPORT PolygonSpatialObject :public BlobSpatialObject<TDimension> { public: @@ -46,7 +46,7 @@ public: itkTypeMacro( PolygonSpatialObject, BlobSpatialObject ); /** Method returning plane alignment of strand */ - PolygonGroupOrientation Plane(); + PolygonGroupOrientation Plane() const; /** Method sets the thickness of the current strand */ itkSetMacro(Thickness,double); @@ -55,50 +55,50 @@ public: itkGetMacro(Thickness,double); /** Returns if the polygon is closed */ - bool IsClosed(); + bool IsClosed() const; /** Returns the number of points of the polygon */ unsigned int NumberOfPoints() const; /** Method returns the Point closest to the given point */ - PointType ClosestPoint(PointType &curPoint); + PointType ClosestPoint( const PointType & curPoint ) const; /** Method returns area of polygon described by points */ - double MeasureArea(); + double MeasureArea() const; /** Method returns the volume of the strand */ - double MeasureVolume(); + double MeasureVolume() const; /** Method returns the length of the perimeter */ - double MeasurePerimeter(); + double MeasurePerimeter() const; /** Method deletes a point from the strand */ - bool DeletePoint(PointType &pointToDelete); + bool DeletePoint( const PointType & pointToDelete ); /** Method adds a point to the end of the strand */ - bool AddPoint(PointType &pointToAdd); + bool AddPoint( const PointType & pointToAdd ); /** Method inserts point after point1 */ - bool InsertPoint(PointType &point1, PointType &pointToAdd); + bool InsertPoint( const PointType & point1, const PointType & pointToAdd ); /** Method replaces a point */ - bool ReplacePoint(PointType &oldpoint, PointType &newPoint); + bool ReplacePoint( const PointType & oldpoint, const PointType & newPoint ); /** Method removes the series of points between startpoint and endpoint */ - bool RemoveSegment(PointType &startpoint,PointType &endPoint); + bool RemoveSegment( const PointType & startpoint, const PointType & endPoint); /** Test whether a point is inside or outside the object. */ virtual bool IsInside( const PointType & point, unsigned int depth, char * name) const; - /** Test whether a point is inside or outside the object - * For computational speed purposes, it is faster if the method does not - * check the name of the class and the current depth */ - virtual bool IsInside( const PointType & point) const - { - return this->IsInside(point, 0, NULL); - }; + /** Test whether a point is inside or outside the object For + * computational speed purposes, it is faster if the method does not + * check the name of the class and the current depth. */ + virtual bool IsInside( const PointType & point) const; + +protected: + void PrintSelf( std::ostream & os, Indent indent) const; private: PolygonSpatialObject(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/SpatialObject/itkPolygonSpatialObject.txx b/Utilities/ITK/Code/SpatialObject/itkPolygonSpatialObject.txx index fb7ace1498..9107d34be9 100644 --- a/Utilities/ITK/Code/SpatialObject/itkPolygonSpatialObject.txx +++ b/Utilities/ITK/Code/SpatialObject/itkPolygonSpatialObject.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPolygonSpatialObject.txx,v $ Language: C++ -Date: $Date: 2008-06-29 01:56:14 $ -Version: $Revision: 1.22 $ +Date: $Date: 2009-04-08 18:27:47 $ +Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,14 +27,14 @@ namespace itk template <unsigned int TDimension > PolygonGroupOrientation PolygonSpatialObject<TDimension> -::Plane() +::Plane() const { PolygonGroupOrientation plane; // local typedef to shut up the compiler... - PointListType &points = this->GetPoints(); - typename PointListType::iterator it = points.begin(); - typename PointListType::iterator itend = points.end(); + const PointListType & points = this->GetPoints(); + typename PointListType::const_iterator it = points.begin(); + typename PointListType::const_iterator itend = points.end(); double min[3],max[3]; // x, y, z int i; for(i = 0; i < 3; i++) @@ -74,11 +74,11 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > bool PolygonSpatialObject<TDimension> -::IsClosed() +::IsClosed() const { - PointListType &points = this->GetPoints(); - typename PointListType::iterator it = points.begin(); - typename PointListType::iterator itend = points.end(); + const PointListType & points = this->GetPoints(); + typename PointListType::const_iterator it = points.begin(); + typename PointListType::const_iterator itend = points.end(); itend--; return (*it).GetPosition() == (*itend).GetPosition(); } @@ -94,11 +94,11 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > typename PolygonSpatialObject<TDimension>::PointType PolygonSpatialObject<TDimension> -::ClosestPoint(PointType &curPoint) +::ClosestPoint( const PointType & curPoint ) const { - PointListType &points = this->GetPoints(); - typename PointListType::iterator it = points.begin(); - typename PointListType::iterator itend = points.end(); + const PointListType &points = this->GetPoints(); + typename PointListType::const_iterator it = points.begin(); + typename PointListType::const_iterator itend = points.end(); double distance = NumericTraits<double>::max(); if(it == itend) @@ -110,6 +110,7 @@ PolygonSpatialObject<TDimension> } PointType closestPoint; + closestPoint.Fill(0.0); while (it != itend) { typename SpatialObjectPoint<TDimension>::PointType curpos @@ -128,7 +129,7 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > double PolygonSpatialObject<TDimension> -::MeasureArea() +::MeasureArea() const { //To find the area of a planar polygon not in the x-y plane, use: //2 A(P) = vcl_abs(N . (sum_{i=0}^{n-1} (v_i x v_{i+1}))) @@ -158,8 +159,8 @@ PolygonSpatialObject<TDimension> exception.SetDescription("File cannot be read"); throw exception; } - PointListType &points = this->GetPoints(); - typename PointListType::iterator it = points.begin(); + const PointListType & points = this->GetPoints(); + typename PointListType::const_iterator it = points.begin(); PointType start = (*it).GetPosition(); for(int i = 0; i < numpoints; i++) { @@ -189,7 +190,7 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > double PolygonSpatialObject<TDimension> -::MeasureVolume() +::MeasureVolume() const { return m_Thickness * this->MeasureArea(); } @@ -197,7 +198,7 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > double PolygonSpatialObject<TDimension> -::MeasurePerimeter() +::MeasurePerimeter() const { double perimeter = 0.0; int numpoints = this->NumberOfPoints(); @@ -205,8 +206,10 @@ PolygonSpatialObject<TDimension> { return 0; } - PointListType &points = this->GetPoints(); - typename PointListType::iterator it = points.begin(); + const PointListType & points = this->GetPoints(); + + typename PointListType::const_iterator it = points.begin(); + PointType start = (*it).GetPosition(); for(int i = 0; i < numpoints; i++) { @@ -236,7 +239,7 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > bool PolygonSpatialObject<TDimension> -::DeletePoint(PointType &pointToDelete) +::DeletePoint( const PointType & pointToDelete ) { PointListType &points = this->GetPoints(); @@ -265,7 +268,7 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > bool PolygonSpatialObject<TDimension> -::AddPoint(PointType &pointToAdd) +::AddPoint( const PointType & pointToAdd ) { BlobPointType newPoint; newPoint.SetPosition(pointToAdd); @@ -276,7 +279,7 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > bool PolygonSpatialObject<TDimension> -::InsertPoint(PointType &point1, PointType &pointToAdd) +::InsertPoint( const PointType & point1, const PointType & pointToAdd ) { PointListType &points = this->GetPoints(); @@ -310,7 +313,7 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > bool PolygonSpatialObject<TDimension> -::ReplacePoint(PointType &oldpoint, PointType &newPoint) +::ReplacePoint( const PointType & oldpoint, const PointType & newPoint ) { PointListType &points = this->GetPoints(); typename PointListType::iterator it = points.begin(); @@ -344,7 +347,7 @@ PolygonSpatialObject<TDimension> template <unsigned int TDimension > bool PolygonSpatialObject<TDimension> -::RemoveSegment(PointType &startPoint, PointType &endPoint) +::RemoveSegment( const PointType & startPoint, const PointType & endPoint ) { PointListType &points = this->GetPoints(); typename PointListType::iterator it = points.begin(); @@ -389,6 +392,14 @@ PolygonSpatialObject<TDimension> return true; } +template <unsigned int TDimension > +bool +PolygonSpatialObject<TDimension> +::IsInside( const PointType & point) const +{ + return this->IsInside(point, 0, NULL); +} + template <unsigned int TDimension > bool PolygonSpatialObject<TDimension> @@ -400,7 +411,7 @@ PolygonSpatialObject<TDimension> { return false; } - switch(const_cast<Self *>(this)->Plane()) + switch( this->Plane() ) { case Sagittal: X = 1; Y = 2; @@ -425,38 +436,46 @@ PolygonSpatialObject<TDimension> PointType transformedPoint = this->GetInternalInverseTransform()->TransformPoint(point); - PointListType &points = const_cast<Self *>(this)->GetPoints(); - typename PointListType::iterator it = points.begin(); - typename PointListType::iterator itend = points.end(); itend--; - PointType start = (*it).GetPosition(); - PointType last = (*itend).GetPosition(); - // - // if last point same as first, don't bother with it. - if(start == last) + const PointListType & points = this->GetPoints(); + typename PointListType::const_iterator it = points.begin(); + typename PointListType::const_iterator itend = points.end(); + itend--; + + PointType first = (*it).GetPosition(); + PointType last = (*itend).GetPosition(); + + // If last point same as first, don't bother with it. + if( this->IsClosed() ) { numpoints--; } + bool oddNodes = false; + + PointType node1; + PointType node2; + for(int i = 0; i < numpoints; i++) { - start = (*it).GetPosition(); + node1 = (*it).GetPosition(); it++; - PointType end; if(i == numpoints - 1) { - end = start; + node2 = first; } else { - end = (*it).GetPosition(); + node2 = (*it).GetPosition(); } - double x = transformedPoint[X]; double y = transformedPoint[Y]; - if((start[Y] < y && end[Y] >= y) || - (end[Y] < y && start[Y] >= y)) + const double x = transformedPoint[X]; + const double y = transformedPoint[Y]; + + if((node1[Y] < y && node2[Y] >= y) || + (node2[Y] < y && node1[Y] >= y)) { - if( start[X] + (y - start[Y])/ - (end[Y] - start[Y]) * (end[X] - start[X]) < x ) + if( node1[X] + (y - node1[Y])/ + (node2[Y] - node1[Y]) * (node2[X] - node1[X]) < x ) { oddNodes = !oddNodes; } @@ -464,5 +483,15 @@ PolygonSpatialObject<TDimension> } return oddNodes; } + +template <unsigned int TDimension > +void +PolygonSpatialObject<TDimension> +::PrintSelf( std::ostream& os, Indent indent ) const +{ + Superclass::PrintSelf( os, indent ); + os << indent << m_Thickness << std::endl; +} + } #endif diff --git a/Utilities/ITK/Code/SpatialObject/itkSceneSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkSceneSpatialObject.h index 60ea072800..38e059a57b 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSceneSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkSceneSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSceneSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-04-07 14:34:16 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,7 +35,7 @@ namespace itk */ template <unsigned int TSpaceDimension = 3> -class SceneSpatialObject +class ITK_EXPORT SceneSpatialObject : public Object { diff --git a/Utilities/ITK/Code/SpatialObject/itkSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkSpatialObject.h index 5309ebc074..eea0cb9398 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.67 $ + Date: $Date: 2009-04-07 14:34:16 $ + Version: $Revision: 1.68 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -65,7 +65,6 @@ namespace itk template <unsigned int TDimension> class SpatialObjectTreeNode; - template< unsigned int TDimension = 3> class SpatialObject :public DataObject diff --git a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectFactory.h b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectFactory.h index e9cb3c7849..f077d47410 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectFactory.h +++ b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectFactory.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectFactory.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:57 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-07 14:34:17 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -29,7 +29,7 @@ namespace itk */ template <class T> -class SpatialObjectFactory : public SpatialObjectFactoryBase +class ITK_EXPORT SpatialObjectFactory : public SpatialObjectFactoryBase { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectFactoryBase.h b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectFactoryBase.h index ff9fe3a788..72fb2849c2 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectFactoryBase.h +++ b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectFactoryBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectFactoryBase.h,v $ Language: C++ - Date: $Date: 2007-01-28 19:24:57 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-04-07 14:34:17 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -28,7 +28,7 @@ namespace itk * \brief Create instances of SpatialObjects */ -class SpatialObjectFactoryBase : public ObjectFactoryBase +class ITK_EXPORT SpatialObjectFactoryBase : public ObjectFactoryBase { public: /** Standard class typedefs. */ diff --git a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectPoint.h b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectPoint.h index 3c4cc7d4a3..ae4cea1e6d 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectPoint.h +++ b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectPoint.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:27 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-04-07 14:34:17 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,7 +34,7 @@ namespace itk */ template < unsigned int TPointDimension = 3 > -class SpatialObjectPoint +class ITK_EXPORT SpatialObjectPoint { public: diff --git a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectTreeContainer.h b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectTreeContainer.h index 6a13083bec..f21b11d84c 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectTreeContainer.h +++ b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectTreeContainer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectTreeContainer.h,v $ Language: C++ - Date: $Date: 2008-06-22 19:20:58 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-07 14:34:17 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -43,7 +43,7 @@ template< unsigned int TDimension> class SpatialObject; * \ingroup DataRepresentation */ template <unsigned int TDimension> -class SpatialObjectTreeContainer : +class ITK_EXPORT SpatialObjectTreeContainer : public TreeContainer<itk::SpatialObject<TDimension>*> { diff --git a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectTreeNode.h b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectTreeNode.h index 5cf462e69b..c8e0bb10b9 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSpatialObjectTreeNode.h +++ b/Utilities/ITK/Code/SpatialObject/itkSpatialObjectTreeNode.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSpatialObjectTreeNode.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:29 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-07 14:34:17 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,7 @@ template <unsigned int TDimension> class SpatialObject; * \brief TODO */ template <unsigned int TDimension> -class SpatialObjectTreeNode : public TreeNode< SpatialObject<TDimension> * > +class ITK_EXPORT SpatialObjectTreeNode : public TreeNode< SpatialObject<TDimension> * > { public: @@ -78,6 +78,14 @@ protected: /** Constructor */ SpatialObjectTreeNode(); virtual ~SpatialObjectTreeNode(){}; + void PrintSelf(std::ostream &os, Indent indent) const + { + this->Superclass::PrintSelf(os, indent); + os << indent << "NodeToParentNodeTransform: " + << m_NodeToParentNodeTransform << std::endl; + os << indent << "NodeToWorldTransform: " + << m_NodeToWorldTransform << std::endl; + } TransformPointer m_NodeToParentNodeTransform; TransformPointer m_NodeToWorldTransform; diff --git a/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObject.h index 4b3bffc8d4..0c85999c85 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSurfaceSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:29 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-07 14:34:17 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,7 +36,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class SurfaceSpatialObject +class ITK_EXPORT SurfaceSpatialObject :public PointBasedSpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObject.txx b/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObject.txx index 61d2114ca7..2b32f1fa66 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObject.txx +++ b/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObject.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSurfaceSpatialObject.txx,v $ Language: C++ - Date: $Date: 2008-06-29 01:56:15 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-04-06 00:19:18 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -377,7 +377,7 @@ SurfaceSpatialObject< TDimension > v2[0]*(v3[1]-v1[1]) + v3[0]*(v1[1]-v2[1])); - absvec = -sqrt ((double) ((coa*coa) + (cob*cob) + (coc*coc))); + absvec = -vcl_sqrt ((double) ((coa*coa) + (cob*cob) + (coc*coc))); if( absvec == 0) diff --git a/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObjectPoint.h b/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObjectPoint.h index 6d7702f64f..79438b3df6 100644 --- a/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObjectPoint.h +++ b/Utilities/ITK/Code/SpatialObject/itkSurfaceSpatialObjectPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSurfaceSpatialObjectPoint.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:29 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-04-07 14:34:17 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,7 +35,7 @@ namespace itk */ template < unsigned int TPointDimension = 3 > -class SurfaceSpatialObjectPoint +class ITK_EXPORT SurfaceSpatialObjectPoint : public SpatialObjectPoint<TPointDimension> { diff --git a/Utilities/ITK/Code/SpatialObject/itkTubeSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkTubeSpatialObject.h index bc5bd004c9..67870c2d50 100644 --- a/Utilities/ITK/Code/SpatialObject/itkTubeSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkTubeSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTubeSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:29 $ - Version: $Revision: 1.46 $ + Date: $Date: 2009-04-07 14:34:17 $ + Version: $Revision: 1.47 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,7 +40,7 @@ namespace itk template < unsigned int TDimension = 3, typename TTubePointType = TubeSpatialObjectPoint<TDimension> > -class TubeSpatialObject +class ITK_EXPORT TubeSpatialObject :public PointBasedSpatialObject< TDimension > { diff --git a/Utilities/ITK/Code/SpatialObject/itkTubeSpatialObjectPoint.h b/Utilities/ITK/Code/SpatialObject/itkTubeSpatialObjectPoint.h index eefb084699..5f9ae8a671 100644 --- a/Utilities/ITK/Code/SpatialObject/itkTubeSpatialObjectPoint.h +++ b/Utilities/ITK/Code/SpatialObject/itkTubeSpatialObjectPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTubeSpatialObjectPoint.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:29 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-07 14:34:18 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,7 +35,7 @@ namespace itk */ template < unsigned int TPointDimension = 3 > -class TubeSpatialObjectPoint +class ITK_EXPORT TubeSpatialObjectPoint : public SpatialObjectPoint<TPointDimension> { diff --git a/Utilities/ITK/Code/SpatialObject/itkVesselTubeSpatialObject.h b/Utilities/ITK/Code/SpatialObject/itkVesselTubeSpatialObject.h index 56a9fef3e1..2248e0a697 100644 --- a/Utilities/ITK/Code/SpatialObject/itkVesselTubeSpatialObject.h +++ b/Utilities/ITK/Code/SpatialObject/itkVesselTubeSpatialObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVesselTubeSpatialObject.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:30 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-04-07 14:34:18 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,7 +38,7 @@ namespace itk */ template < unsigned int TDimension = 3 > -class VesselTubeSpatialObject +class ITK_EXPORT VesselTubeSpatialObject :public TubeSpatialObject< TDimension, VesselTubeSpatialObjectPoint< TDimension > > { diff --git a/Utilities/ITK/Code/SpatialObject/itkVesselTubeSpatialObjectPoint.h b/Utilities/ITK/Code/SpatialObject/itkVesselTubeSpatialObjectPoint.h index c8da92822a..8749ef1fad 100644 --- a/Utilities/ITK/Code/SpatialObject/itkVesselTubeSpatialObjectPoint.h +++ b/Utilities/ITK/Code/SpatialObject/itkVesselTubeSpatialObjectPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVesselTubeSpatialObjectPoint.h,v $ Language: C++ - Date: $Date: 2009-01-28 20:10:30 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-04-07 14:34:18 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -35,7 +35,7 @@ namespace itk */ template < unsigned int TPointDimension = 3 > -class VesselTubeSpatialObjectPoint +class ITK_EXPORT VesselTubeSpatialObjectPoint : public TubeSpatialObjectPoint<TPointDimension> { diff --git a/Utilities/ITK/ITKConfig.cmake.in b/Utilities/ITK/ITKConfig.cmake.in index f3c7e9fba7..f9ec848779 100644 --- a/Utilities/ITK/ITKConfig.cmake.in +++ b/Utilities/ITK/ITKConfig.cmake.in @@ -59,6 +59,7 @@ SET(ITK_USE_SYSTEM_GDCM "@ITK_USE_SYSTEM_GDCM@") SET(ITK_USE_LIBXML2 "@ITK_USE_LIBXML2@") SET(ITK_USE_SYSTEM_LIBXML2 "@ITK_USE_SYSTEM_LIBXML2@") SET(ITK_USE_REVIEW "@ITK_USE_REVIEW@") +SET(ITK_USE_REVIEW_STATISTICS "@ITK_USE_REVIEW_STATISTICS@") SET(ITK_USE_TRANSFORM_IO_FACTORIES "@ITK_USE_TRANSFORM_IO_FACTORIES@") SET(ITK_USE_OPTIMIZED_REGISTRATION_METHODS "@ITK_USE_OPTIMIZED_REGISTRATION_METHODS@") SET(ITK_USE_ORIENTED_IMAGE_DIRECTION "@ITK_USE_ORIENTED_IMAGE_DIRECTION@") @@ -67,3 +68,4 @@ SET(ITK_USE_ORIENTED_IMAGE_DIRECTION "@ITK_USE_ORIENTED_IMAGE_DIRECTION@") # same for gdcm SET(ITK_VXL_DIR "@ITK_VXL_DIR@") SET(ITK_GDCM_DIR "@ITK_GDCM_DIR@") + diff --git a/Utilities/ITK/Utilities/CMakeLists.txt b/Utilities/ITK/Utilities/CMakeLists.txt index 61204f5210..60e62ebebb 100644 --- a/Utilities/ITK/Utilities/CMakeLists.txt +++ b/Utilities/ITK/Utilities/CMakeLists.txt @@ -123,6 +123,10 @@ IF(NOT ITK_USE_SYSTEM_VXL) ADD_SUBDIRECTORY(vxl) ENDIF(NOT ITK_USE_SYSTEM_VXL) +#------------------------------------------------------------------------------ +# This directory depends on VXL V3p +ADD_SUBDIRECTORY(netlib) + #------------------------------------------------------------------------------ # Build testing as needed IF (BUILD_TESTING) diff --git a/Utilities/ITK/Utilities/DICOMParser/DICOMAppHelper.h b/Utilities/ITK/Utilities/DICOMParser/DICOMAppHelper.h index 272eb347d0..024924e25c 100644 --- a/Utilities/ITK/Utilities/DICOMParser/DICOMAppHelper.h +++ b/Utilities/ITK/Utilities/DICOMParser/DICOMAppHelper.h @@ -3,8 +3,8 @@ Program: DICOMParser Module: $RCSfile: DICOMAppHelper.h,v $ Language: C++ - Date: $Date: 2008-05-25 12:03:31 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-04-05 10:56:56 $ + Version: $Revision: 1.32 $ Copyright (c) 2003 Matt Turek All rights reserved. @@ -25,7 +25,7 @@ #endif #include <vector> -#include <string> +#include <string.h> #include <cstring> #include "DICOMConfig.h" diff --git a/Utilities/ITK/Utilities/DICOMParser/DICOMBuffer.cxx b/Utilities/ITK/Utilities/DICOMParser/DICOMBuffer.cxx index ed0f9fb968..0587f4e788 100644 --- a/Utilities/ITK/Utilities/DICOMParser/DICOMBuffer.cxx +++ b/Utilities/ITK/Utilities/DICOMParser/DICOMBuffer.cxx @@ -3,8 +3,8 @@ Program: DICOMParser Module: $RCSfile: DICOMBuffer.cxx,v $ Language: C++ - Date: $Date: 2004-03-21 21:40:03 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-05 10:56:58 $ + Version: $Revision: 1.3 $ Copyright (c) 2003 Matt Turek All rights reserved. @@ -26,7 +26,7 @@ #include <fstream> #include <iomanip> #include <stdio.h> -#include <string> +#include <string.h> #include "DICOMConfig.h" #include "DICOMBuffer.h" diff --git a/Utilities/ITK/Utilities/DICOMParser/DICOMParser.cxx b/Utilities/ITK/Utilities/DICOMParser/DICOMParser.cxx index 8e7e78572e..51197878e4 100644 --- a/Utilities/ITK/Utilities/DICOMParser/DICOMParser.cxx +++ b/Utilities/ITK/Utilities/DICOMParser/DICOMParser.cxx @@ -3,8 +3,8 @@ Program: DICOMParser Module: $RCSfile: DICOMParser.cxx,v $ Language: C++ - Date: $Date: 2008-06-19 22:31:45 $ - Version: $Revision: 1.39 $ + Date: $Date: 2009-04-05 10:56:58 $ + Version: $Revision: 1.40 $ Copyright (c) 2003 Matt Turek All rights reserved. @@ -36,7 +36,7 @@ #include <sys/types.h> #endif -#include <string> +#include <string.h> #include <map> #include "DICOMConfig.h" diff --git a/Utilities/ITK/Utilities/DICOMParser/DICOMSource.cxx b/Utilities/ITK/Utilities/DICOMParser/DICOMSource.cxx index 30b5fd6649..8ec58db029 100644 --- a/Utilities/ITK/Utilities/DICOMParser/DICOMSource.cxx +++ b/Utilities/ITK/Utilities/DICOMParser/DICOMSource.cxx @@ -3,8 +3,8 @@ Program: DICOMParser Module: $RCSfile: DICOMSource.cxx,v $ Language: C++ - Date: $Date: 2004-03-21 21:40:03 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-04-05 10:56:58 $ + Version: $Revision: 1.3 $ Copyright (c) 2003 Matt Turek All rights reserved. @@ -26,7 +26,7 @@ #include <fstream> #include <iomanip> #include <stdio.h> -#include <string> +#include <string.h> #include "DICOMConfig.h" #include "DICOMSource.h" diff --git a/Utilities/ITK/Utilities/KWStyle/ITKFiles.txt.in b/Utilities/ITK/Utilities/KWStyle/ITKFiles.txt.in index fd9cc402a9..a8d513efbf 100644 --- a/Utilities/ITK/Utilities/KWStyle/ITKFiles.txt.in +++ b/Utilities/ITK/Utilities/KWStyle/ITKFiles.txt.in @@ -1,12 +1,12 @@ -@ITK_SOURCE_DIR@/Code/Common/itk[A-Ma-m]*.h -@ITK_SOURCE_DIR@/Code/Common/itk[A-Ma-m]*.txx -@ITK_SOURCE_DIR@/Code/Common/itk[A-Ma-m]*.cxx +@ITK_SOURCE_DIR@/Code/Common/itk*.h +@ITK_SOURCE_DIR@/Code/Common/itk*.txx +@ITK_SOURCE_DIR@/Code/Common/itk*.cxx @ITK_SOURCE_DIR@/Code/BasicFilters/itk*.h @ITK_SOURCE_DIR@/Code/BasicFilters/itk*.txx @ITK_SOURCE_DIR@/Code/BasicFilters/itk*.cxx -@ITK_SOURCE_DIR@/Code/Algorithms/itk[A-La-l]*.h -@ITK_SOURCE_DIR@/Code/Algorithms/itk[A-La-l]*.txx -@ITK_SOURCE_DIR@/Code/Algorithms/itk[A-La-l]*.cxx +@ITK_SOURCE_DIR@/Code/Algorithms/itk*.h +@ITK_SOURCE_DIR@/Code/Algorithms/itk*.txx +@ITK_SOURCE_DIR@/Code/Algorithms/itk*.cxx @ITK_SOURCE_DIR@/Code/IO/itk*.h @ITK_SOURCE_DIR@/Code/IO/itk*.txx @ITK_SOURCE_DIR@/Code/IO/itk*.cxx @@ -19,6 +19,9 @@ @ITK_SOURCE_DIR@/Code/Numerics/NeuralNetworks/itk*.h @ITK_SOURCE_DIR@/Code/Numerics/NeuralNetworks/itk*.txx @ITK_SOURCE_DIR@/Code/Numerics/NeuralNetworks/itk*.cxx +@ITK_SOURCE_DIR@/Code/Numerics/Statistics/itk*.h +@ITK_SOURCE_DIR@/Code/Numerics/Statistics/itk*.txx +@ITK_SOURCE_DIR@/Code/Numerics/Statistics/itk*.cxx @ITK_SOURCE_DIR@/Code/Algorithms/itk*.h @ITK_SOURCE_DIR@/Code/Algorithms/itk*.txx @ITK_SOURCE_DIR@/Code/Algorithms/itk*.cxx diff --git a/Utilities/ITK/Utilities/KWStyle/ITKOverwrite.txt b/Utilities/ITK/Utilities/KWStyle/ITKOverwrite.txt index bfa16cdae2..4a636ac489 100644 --- a/Utilities/ITK/Utilities/KWStyle/ITKOverwrite.txt +++ b/Utilities/ITK/Utilities/KWStyle/ITKOverwrite.txt @@ -28,6 +28,7 @@ itkQuadEdgeMeshMacro.h Indent Disable itkExceptionObject.h Indent Disable itkBinaryThresholdImageFilter.h Indent Disable VNLIterativeSparseSolverTraits.h Namespace Disable +itkMeasurementVectorTraits.h InternalVariables Disable itk.*\Test.*\.cxx Namespace Disable itk.*\Test.*\.h Namespace Disable itkBilateralImageFilter.txx Namespace Disable @@ -91,3 +92,14 @@ itkNumericTraitsTensorPixel.h InternalVariables Disable itkNumericTraitsVectorPixel.h InternalVariables Disable itkNumericTraits.cxx Typedefs Disable itkObjectFactoryBase.cxx Namespace Disable +itkSecondaryNodeList.h InternalVariables Disable +itkSimplexMeshGeometry.h InternalVariables Disable +itkSmartPointerForwardReferenceProcessObject.cxx Namespace Disable +itkValarrayImageContainer.h DeclarationOrder Disable +itkVectorContainer.h DeclarationOrder Disable +itkVectorContainer.h Typedefs Disable +itkXMLFileOutputWindow.cxx Indent Disable +itkKdTreeGenerator.h InternalVariables Disable +itkNormalVariateGenerator.h InternalVariables Disable +itkStatisticsTypesTest.cxx Typedefs Disable +itkLabelStatisticsImageFilter.h Indent Disable diff --git a/Utilities/ITK/Utilities/KWStyle/ITKReviewFiles.txt.in b/Utilities/ITK/Utilities/KWStyle/ITKReviewFiles.txt.in index e6c74c85ec..15d7fb5b26 100644 --- a/Utilities/ITK/Utilities/KWStyle/ITKReviewFiles.txt.in +++ b/Utilities/ITK/Utilities/KWStyle/ITKReviewFiles.txt.in @@ -1,6 +1,12 @@ @ITK_SOURCE_DIR@/Code/Review/itk*.h @ITK_SOURCE_DIR@/Code/Review/itk*.txx @ITK_SOURCE_DIR@/Code/Review/itk*.cxx +@ITK_SOURCE_DIR@/Code/Review/Statistics/itk*.h +@ITK_SOURCE_DIR@/Code/Review/Statistics/itk*.txx +@ITK_SOURCE_DIR@/Code/Review/Statistics/itk*.cxx @ITK_SOURCE_DIR@/Testing/Code/Review/*.h @ITK_SOURCE_DIR@/Testing/Code/Review/*.txx @ITK_SOURCE_DIR@/Testing/Code/Review/*.cxx +@ITK_SOURCE_DIR@/Testing/Code/Review/Statistics/*.h +@ITK_SOURCE_DIR@/Testing/Code/Review/Statistics/*.txx +@ITK_SOURCE_DIR@/Testing/Code/Review/Statistics/*.cxx diff --git a/Utilities/ITK/Utilities/KWStyle/KWStyle.cmake b/Utilities/ITK/Utilities/KWStyle/KWStyle.cmake index 540aa4b3a4..159174807c 100644 --- a/Utilities/ITK/Utilities/KWStyle/KWStyle.cmake +++ b/Utilities/ITK/Utilities/KWStyle/KWStyle.cmake @@ -6,8 +6,8 @@ SET(KWSTYLE_REQ_MAJOR 1) SET(KWSTYLE_REQ_MINOR 0) SET(KWSTYLE_REQ_PATCH 1) -#OPTION(KWSTYLE_USE_VIM_FORMAT "Set KWStyle to generate errors with a VIM-compatible format." OFF) -#OPTION(KWSTYLE_USE_MSVC_FORMAT "Set KWStyle to generate errors with a VisualStudio-compatible format." OFF) +OPTION(KWSTYLE_USE_VIM_FORMAT "Set KWStyle to generate errors with a VIM-compatible format." OFF) +OPTION(KWSTYLE_USE_MSVC_FORMAT "Set KWStyle to generate errors with a VisualStudio-compatible format." OFF) FIND_PROGRAM(KWSTYLE_EXECUTABLE NAMES KWStyle diff --git a/Utilities/ITK/Utilities/MetaIO/.svnrev b/Utilities/ITK/Utilities/MetaIO/.svnrev index 17863f9c51..84efa7e06a 100644 --- a/Utilities/ITK/Utilities/MetaIO/.svnrev +++ b/Utilities/ITK/Utilities/MetaIO/.svnrev @@ -1 +1 @@ -782 \ No newline at end of file +801 \ No newline at end of file diff --git a/Utilities/ITK/Utilities/MetaIO/metaImage.cxx b/Utilities/ITK/Utilities/MetaIO/metaImage.cxx index a1baa91a1c..c99c318db4 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaImage.cxx +++ b/Utilities/ITK/Utilities/MetaIO/metaImage.cxx @@ -3,8 +3,8 @@ Program: MetaIO Module: $RCSfile: metaImage.cxx,v $ Language: C++ - Date: $Date: 2009-02-17 18:44:03 $ - Version: $Revision: 1.114 $ + Date: $Date: 2009-03-06 03:24:05 $ + Version: $Revision: 1.115 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -2994,6 +2994,7 @@ bool MetaImage::ReadROIStream(int * _indexMin, int * _indexMax, { m_ReadStream->close(); } + delete readStreamTemp; return false; } diff --git a/Utilities/ITK/Utilities/gdcm/CMake/FindUUID.cmake b/Utilities/ITK/Utilities/gdcm/CMake/FindUUID.cmake index 82837f4ebc..ba975b012d 100644 --- a/Utilities/ITK/Utilities/gdcm/CMake/FindUUID.cmake +++ b/Utilities/ITK/Utilities/gdcm/CMake/FindUUID.cmake @@ -12,8 +12,20 @@ FIND_PATH(UUID_INCLUDE_DIR uuid/uuid.h /usr/include ) +# On MacOSX we have: +# $ nm -g /usr/lib/libSystem.dylib | grep uuid_generate +# 000b3aeb T _uuid_generate +# 0003e67e T _uuid_generate_random +# 000b37a1 T _uuid_generate_time +IF(APPLE) + SET(UUID_LIBRARY_VAR System) +ELSE(APPLE) + # Linux type: + SET(UUID_LIBRARY_VAR uuid) +ENDIF(APPLE) + FIND_LIBRARY(UUID_LIBRARY - NAMES uuid + NAMES ${UUID_LIBRARY_VAR} PATHS /lib /usr/lib /usr/local/lib ) diff --git a/Utilities/ITK/Utilities/gdcm/CMakeLists.txt b/Utilities/ITK/Utilities/gdcm/CMakeLists.txt index 1db2ce3ad1..8e0668ffa3 100644 --- a/Utilities/ITK/Utilities/gdcm/CMakeLists.txt +++ b/Utilities/ITK/Utilities/gdcm/CMakeLists.txt @@ -12,6 +12,10 @@ SET(CMAKE_MODULE_PATH ${GDCM_SOURCE_DIR}/CMake) FIND_PACKAGE(UUID) IF(UUID_FOUND) SET(GDCM_SYSTEM_UUID_FOUND 1) +ELSE(UUID_FOUND) + IF(NOT WIN32) + MESSAGE("Could not find the UUID dev library files on your system (uuid/uuid.h missing). Using the default internal implementation (it is known to be weak)") + ENDIF(NOT WIN32) ENDIF(UUID_FOUND) #----------------------------------------------------------------------------- diff --git a/Utilities/ITK/Utilities/gdcm/src/gdcmDocument.cxx b/Utilities/ITK/Utilities/gdcm/src/gdcmDocument.cxx index ba3b10ef50..2f1c9d2cbc 100644 --- a/Utilities/ITK/Utilities/gdcm/src/gdcmDocument.cxx +++ b/Utilities/ITK/Utilities/gdcm/src/gdcmDocument.cxx @@ -3,8 +3,8 @@ Program: gdcm Module: $RCSfile: gdcmDocument.cxx,v $ Language: C++ - Date: $Date: 2008-05-14 12:25:32 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-04-05 10:56:58 $ + Version: $Revision: 1.32 $ Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or @@ -33,6 +33,7 @@ #include <fstream> #include <ctype.h> // for isdigit #include <stdlib.h> // for atoi +#include <stdio.h> // for sscanf #if defined(__BORLANDC__) #include <mem.h> // for memset @@ -1136,16 +1137,38 @@ void Document::ParseDES(DocEntrySet *set, long offset, if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr { std::string strLgrGroup = newValEntry->GetValue(); - int lgrGroup; + unsigned int lgrGroup; if ( strLgrGroup != GDCM_UNFOUND) { - lgrGroup = atoi(strLgrGroup.c_str()); - Fp->seekg(lgrGroup, std::ios::cur); - //used = false; // never used - RemoveEntry( newDocEntry ); // Remove and delete - // bcc 5.5 is right "assigned a value that's never used" - // newDocEntry = 0; - continue; + //lgrGroup = atoi(strLgrGroup.c_str()); + if( sscanf( strLgrGroup.c_str(), "%ud", &lgrGroup) == 1 ) + { + gdcmDebugMacro( "Skipping: " << lgrGroup << " bytes" ); + long startpos = Fp->tellg(); + Fp->seekg(lgrGroup, std::ios::cur); + // Let's detect some easy case: when value is larger than file size: + Fp->peek(); + if( Fp->good() ) + { + //used = false; // never used + RemoveEntry( newDocEntry ); // Remove and delete + // bcc 5.5 is right "assigned a value that's never used" + // newDocEntry = 0; + continue; + } + else + { + // something went wrong, back track... + // http://www.itk.org/pipermail/insight-users/2009-March/029715.html + // (130d,0000) ?? (UL) 1099164365\1276292990\3804772504\555532589 + Fp->clear(); + Fp->seekg(startpos, std::ios::beg); + } + } + else + { + gdcmErrorMacro( "Could not skip using group length for tag:" ); + } } } } diff --git a/Utilities/ITK/Utilities/gdcm/src/gdcmFile.cxx b/Utilities/ITK/Utilities/gdcm/src/gdcmFile.cxx index 799e02e4b6..2b3b43d63b 100644 --- a/Utilities/ITK/Utilities/gdcm/src/gdcmFile.cxx +++ b/Utilities/ITK/Utilities/gdcm/src/gdcmFile.cxx @@ -3,8 +3,8 @@ Program: gdcm Module: $RCSfile: gdcmFile.cxx,v $ Language: C++ - Date: $Date: 2008-12-11 15:03:30 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-04-29 21:40:53 $ + Version: $Revision: 1.28 $ Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or @@ -525,6 +525,22 @@ bool File::GetSpacing(float &xspacing, float &yspacing, float &zspacing) } return true; } + else if( sopclassuid_used == "RT Dose Storage" ) + { + // (3004,000c) DS [0.0\-2.5\-5.0\-7.5\-10.0\-12.5... # 132,23 GridFrameOffsetVector + DocEntry *p3 = GetDocEntry(0x3004,0x000c); + if( !p3 ) return false; + ContentEntry *entry2 = dynamic_cast<ContentEntry *>(p3); + std::string gridframeoffset = entry2->GetValue(); + float z1, z2; + if ( sscanf( gridframeoffset.c_str(), "%f\\%f", &z1, &z2) != 2 ) + { + zspacing = 1.; + return false; + } + zspacing = z2 - z1; // can be negative ... + return true; + } return false; } diff --git a/Utilities/ITK/Utilities/gdcm/src/gdcmFileHelper.cxx b/Utilities/ITK/Utilities/gdcm/src/gdcmFileHelper.cxx index 8a3b865b64..b40452799c 100644 --- a/Utilities/ITK/Utilities/gdcm/src/gdcmFileHelper.cxx +++ b/Utilities/ITK/Utilities/gdcm/src/gdcmFileHelper.cxx @@ -4,8 +4,8 @@ Module: $RCSfile: gdcmFileHelper.cxx,v $ Language: C++ - Date: $Date: 2008-12-19 11:27:17 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-03-27 19:14:02 $ + Version: $Revision: 1.30 $ Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or @@ -1636,7 +1636,7 @@ void FileHelper::CheckMandatoryElements() os2 << *it; } } - imagetype = os.str(); + imagetype = os2.str(); } } } diff --git a/Utilities/ITK/Utilities/gdcm/src/gdcmGlobal.cxx b/Utilities/ITK/Utilities/gdcm/src/gdcmGlobal.cxx index 54e770156e..a1e5a7c784 100644 --- a/Utilities/ITK/Utilities/gdcm/src/gdcmGlobal.cxx +++ b/Utilities/ITK/Utilities/gdcm/src/gdcmGlobal.cxx @@ -3,8 +3,8 @@ Program: gdcm Module: $RCSfile: gdcmGlobal.cxx,v $ Language: C++ - Date: $Date: 2006-07-10 20:08:21 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-04-24 03:48:46 $ + Version: $Revision: 1.9 $ Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or @@ -25,6 +25,9 @@ #include "gdcmDictSet.h" #include "gdcmDicomDirElement.h" +#include <stdlib.h> // srand +#include <time.h> // time + namespace gdcm { //----------------------------------------------------------------------------- @@ -72,6 +75,7 @@ Global::Global() TranSyn = new TS(); GroupName = new DictGroupName(); ddElem = new DicomDirElement(); + srand( time(0) ); // rand() is used in the internal implementation of CreateUniqueUID } /** diff --git a/Utilities/ITK/Utilities/gdcm/src/gdcmJpeg2000.cxx b/Utilities/ITK/Utilities/gdcm/src/gdcmJpeg2000.cxx index 57c78cea83..a847253d0d 100644 --- a/Utilities/ITK/Utilities/gdcm/src/gdcmJpeg2000.cxx +++ b/Utilities/ITK/Utilities/gdcm/src/gdcmJpeg2000.cxx @@ -3,8 +3,8 @@ Program: gdcm Module: $RCSfile: gdcmJpeg2000.cxx,v $ Language: C++ - Date: $Date: 2008-05-28 11:26:40 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-04-02 08:47:04 $ + Version: $Revision: 1.18 $ Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or @@ -94,6 +94,19 @@ bool gdcm_read_JPEG2000_file (void* raw, char *inputdata, size_t inputlength) unsigned char *src = (unsigned char*)inputdata; int file_length = static_cast< int >( inputlength ); + // WARNING: OpenJPEG is very picky when there is a trailing 00 at the end of the JPC + // so we need to make sure to remove it: + // See for example: DX_J2K_0Padding.dcm + // and D_CLUNIE_CT1_J2KR.dcm + // Marker 0xffd9 EOI End of Image (JPEG 2000 EOC End of codestream) + // gdcmData/D_CLUNIE_CT1_J2KR.dcm contains a trailing 0xFF which apparently is ok... + while( file_length > 0 && src[file_length-1] != 0xd9 ) + { + file_length--; + } + // what if 0xd9 is never found ? + assert( file_length > 0 && src[file_length-1] == 0xd9 ); + /* configure the event callbacks (not required) */ memset(&event_mgr, 0, sizeof(opj_event_mgr_t)); event_mgr.error_handler = error_callback; @@ -102,21 +115,43 @@ bool gdcm_read_JPEG2000_file (void* raw, char *inputdata, size_t inputlength) /* set decoding parameters to default values */ opj_set_default_decoder_parameters(¶meters); - + // default blindly copied parameters.cp_layer=0; parameters.cp_reduce=0; // parameters.decod_format=-1; // parameters.cod_format=-1; - /* JPEG-2000 codestream */ - parameters.decod_format = J2K_CFMT; - assert(parameters.decod_format == J2K_CFMT); + const char jp2magic[] = "\x00\x00\x00\x0C\x6A\x50\x20\x20\x0D\x0A\x87\x0A"; + if( memcmp( src, jp2magic, sizeof(jp2magic) ) == 0 ) + { + /* JPEG-2000 compressed image data */ + // gdcmData/ELSCINT1_JP2vsJ2K.dcm + gdcmWarningMacro( "J2K start like JPEG-2000 compressed image data instead of codestream" ); + parameters.decod_format = JP2_CFMT; + assert(parameters.decod_format == JP2_CFMT); + } + else + { + /* JPEG-2000 codestream */ + parameters.decod_format = J2K_CFMT; + assert(parameters.decod_format == J2K_CFMT); + } parameters.cod_format = PGX_DFMT; assert(parameters.cod_format == PGX_DFMT); /* get a decoder handle */ - dinfo = opj_create_decompress(CODEC_J2K); + switch(parameters.decod_format ) + { + case J2K_CFMT: + dinfo = opj_create_decompress(CODEC_J2K); + break; + case JP2_CFMT: + dinfo = opj_create_decompress(CODEC_JP2); + break; + default: + return false; + } /* catch events using our callbacks and give a local context */ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, NULL); @@ -132,7 +167,7 @@ bool gdcm_read_JPEG2000_file (void* raw, char *inputdata, size_t inputlength) if(!image) { opj_destroy_decompress(dinfo); opj_cio_close(cio); - return 1; + return false; } /* close the byte stream */ @@ -315,7 +350,7 @@ opj_image_t* rawtoimage(char *inputbuffer, opj_cparameters_t *parameters, */ bool gdcm_write_JPEG2000_file (std::ostream *fp, char *inputdata, size_t inputlength, int image_width, int image_height, int numZ, int sample_pixel, int bitsallocated, - int sign, int quality) + int sign, int quality, size_t &nbbytes) { //// input_buffer is ONE image //// fragment_size is the size of this image (fragment) @@ -414,6 +449,8 @@ bool gdcm_write_JPEG2000_file (std::ostream *fp, char *inputdata, size_t inputle debug.close(); #endif fp->write((char*)(cio->buffer), codestream_length); + nbbytes = codestream_length; + //gdcmErrorMacro( "codestream_length: " << codestream_length ); // FIXME: remote debug of sunos //fclose(f); /* close and free the byte stream */ diff --git a/Utilities/ITK/Utilities/gdcm/src/gdcmPixelReadConvert.cxx b/Utilities/ITK/Utilities/gdcm/src/gdcmPixelReadConvert.cxx index cc42d771e7..6cbeab1c8e 100644 --- a/Utilities/ITK/Utilities/gdcm/src/gdcmPixelReadConvert.cxx +++ b/Utilities/ITK/Utilities/gdcm/src/gdcmPixelReadConvert.cxx @@ -3,8 +3,8 @@ Program: gdcm Module: $RCSfile: gdcmPixelReadConvert.cxx,v $ Language: C++ - Date: $Date: 2008-12-01 10:49:28 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-03-24 21:56:26 $ + Version: $Revision: 1.14 $ Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or @@ -491,7 +491,7 @@ bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp ) { if( (unsigned int)ZSize != JPEGInfo->GetFragmentCount() ) { - gdcmErrorMacro( "Sorry GDCM does not handle this type of fragments" ); + gdcmErrorMacro( "Sorry GDCM does not handle this type of fragments: " << ZSize << " vs " << JPEGInfo->GetFragmentCount() ); return false; } // Hopefully every dicom fragment is *exactly* the j2k stream diff --git a/Utilities/ITK/Utilities/gdcm/src/gdcmPixelWriteConvert.cxx b/Utilities/ITK/Utilities/gdcm/src/gdcmPixelWriteConvert.cxx index 5db936810e..7a473fc4b9 100644 --- a/Utilities/ITK/Utilities/gdcm/src/gdcmPixelWriteConvert.cxx +++ b/Utilities/ITK/Utilities/gdcm/src/gdcmPixelWriteConvert.cxx @@ -3,8 +3,8 @@ Program: gdcm Module: $RCSfile: gdcmPixelWriteConvert.cxx,v $ Language: C++ - Date: $Date: 2008-05-14 12:25:32 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-04-30 08:27:02 $ + Version: $Revision: 1.15 $ Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or @@ -28,6 +28,20 @@ #include <stdlib.h> #define WITHOFFSETTABLE 1 +/* + * Note: WITHOFFSETTABLE rely on a proper implementation of std::stringstream. + * It requires that you can seekp the stream but do not truncate it. In + * kwsys/stringstream implementation based out of strstream this requirement + * is not respected. This typically happen on old SunOS compiler. + * + * stringstream strstr; + * strstr.write( (char*)array, narray ); + * strstr.seekp( narray / 2 ); // set position of put pointer in mid string + * assert(strstr.str().size() == narray ); + * + * However there is a special flag '-stlport4' which seems to provide a better + * support for std::stringstream, this flag is the default now on ITK dashboard. + */ namespace gdcm { @@ -128,7 +142,7 @@ typedef std::vector<JpegPair> JpegVector; bool gdcm_write_JPEG2000_file (std::ostream *of, char *inputdata, size_t inputlength, int image_width, int image_height, int numZ, int sample_pixel, int bitsallocated, - int sign, int quality); + int sign, int quality, size_t &); void WriteDICOMItems(std::ostream *fp, JpegVector &v) @@ -239,7 +253,7 @@ void PixelWriteConvert::SetCompressJPEG2000UserData(uint8_t *data, size_t size, Compressed = true; //char * userData = reinterpret_cast<char*>(UserData); - itksys_ios::ostringstream *of = new itksys_ios::ostringstream(); + itksys_ios::stringstream *of = new itksys_ios::stringstream(); // ostringstream: debug / sunos int xsize = image->GetXSize(); int ysize = image->GetYSize(); int zsize = image->GetZSize(); @@ -264,15 +278,23 @@ void PixelWriteConvert::SetCompressJPEG2000UserData(uint8_t *data, size_t size, { WriteDICOMItems(of, JpegFragmentSize); size_t beg = of->tellp(); + size_t nbbytes = 0; gdcm_write_JPEG2000_file(of, (char*)pImageData,size, image->GetXSize(), image->GetYSize(), image->GetZSize(), image->GetSamplesPerPixel(), - image->GetBitsAllocated(), sign, 100); + image->GetBitsAllocated(), sign, 100, nbbytes); //userData, UserDataSize); // CreateOneFrame(of, pImageData, fragment_size, xsize, ysize, zsize, // samplesPerPixel, quality, JpegFragmentSize); //assert( !(fragment_size % 2) ); // Update the JpegVector with offset size_t end = of->tellp(); + if( (end - beg) != nbbytes ) + { + gdcmErrorMacro( "Go fix your compiler implementation of stringstream." ); + UserData = 0; + UserDataSize = 0; + return; + } //static int i = 0; JpegPair &jp = JpegFragmentSize[i]; jp.second = (uint32_t)(end-beg); @@ -283,7 +305,6 @@ void PixelWriteConvert::SetCompressJPEG2000UserData(uint8_t *data, size_t size, } assert( !(jp.second % 2) ); //std::cerr << "DIFF: " << i <<" -> " << jp.second << std::endl; - //++i; pImageData += fragment_size; } CloseJpeg(of, JpegFragmentSize); @@ -293,6 +314,7 @@ void PixelWriteConvert::SetCompressJPEG2000UserData(uint8_t *data, size_t size, size_t of_size = of->str().size(); + gdcmErrorMacro( "Of_size: " << of_size ); // FIXME: remote debug of sunos UserData = new uint8_t[of_size]; memcpy(UserData, of->str().c_str(), of_size); UserDataSize = of_size; diff --git a/Utilities/ITK/Utilities/gdcm/src/gdcmUtil.cxx b/Utilities/ITK/Utilities/gdcm/src/gdcmUtil.cxx index 449d21f1d7..f6aacd7a37 100644 --- a/Utilities/ITK/Utilities/gdcm/src/gdcmUtil.cxx +++ b/Utilities/ITK/Utilities/gdcm/src/gdcmUtil.cxx @@ -3,8 +3,8 @@ Program: gdcm Module: $RCSfile: gdcmUtil.cxx,v $ Language: C++ - Date: $Date: 2008-05-19 07:14:39 $ - Version: $Revision: 1.44 $ + Date: $Date: 2009-05-23 11:28:54 $ + Version: $Revision: 1.46 $ Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or @@ -23,6 +23,7 @@ #include <stdarg.h> // for va_list // For GetCurrentDate, GetCurrentTime +#include <math.h> // pow #include <time.h> #include <sys/types.h> #include <sys/stat.h> @@ -92,7 +93,11 @@ #include <thread.h> #endif -#if _WIN32 +#if defined(__CYGWIN__) +#undef GDCM_SYSTEM_UUID_FOUND +#endif + +#if defined(_WIN32) #define HAVE_UUIDCREATE #else #ifdef GDCM_SYSTEM_UUID_FOUND @@ -981,11 +986,19 @@ std::string Util::CreateUniqueUID(const std::string &root) } append += Util::GetCurrentDateTime(); - //Also add a mini random number just in case: - char tmp[10]; - int r = (int) (100.0*rand()/RAND_MAX); + // Also add a mini random number since machine are now so fast that within the same + // millisecond you could generate the same UID... + // Using all remaining bytes should avoid issues most of the time. + int diff = 64 - (prefix + append).size() - 1; + if( diff <= 0 ) + { + gdcmErrorMacro( "Size of UID is too long." ); + } + const double mult = pow(10., diff); + char tmp[64]; + int r = (int) (mult*rand()/(RAND_MAX+1.0)); // output will be in [0, mult - 1] // Don't use Util::Format to accelerate the execution - sprintf(tmp,"%02d", r); + sprintf(tmp,".%d", r); append += tmp; // If append is too long we need to rehash it diff --git a/Utilities/ITK/Utilities/itkjpeg/mangle_jpeg8bits.h b/Utilities/ITK/Utilities/itkjpeg/mangle_jpeg8bits.h index 226aa54b90..bb09e6596f 100644 --- a/Utilities/ITK/Utilities/itkjpeg/mangle_jpeg8bits.h +++ b/Utilities/ITK/Utilities/itkjpeg/mangle_jpeg8bits.h @@ -12,6 +12,7 @@ The following command was used to obtain the symbol list: nm libitkitk_jpeg8.a | grep " [R|T] " | colrm 1 11 | sort */ +#define itk_secret_symbol_mangled_jpeg8 #define jcopy_block_row itk_jpeg8_jcopy_block_row diff --git a/Utilities/ITK/Utilities/kwsys/Base64.h.in b/Utilities/ITK/Utilities/kwsys/Base64.h.in index 66329a253b..3300a3996e 100644 --- a/Utilities/ITK/Utilities/kwsys/Base64.h.in +++ b/Utilities/ITK/Utilities/kwsys/Base64.h.in @@ -24,13 +24,15 @@ # define kwsys_ns(x) @KWSYS_NAMESPACE@##x # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif -#define kwsysBase64 kwsys_ns(Base64) -#define kwsysBase64_Decode kwsys_ns(Base64_Decode) -#define kwsysBase64_Decode3 kwsys_ns(Base64_Decode3) -#define kwsysBase64_Encode kwsys_ns(Base64_Encode) -#define kwsysBase64_Encode1 kwsys_ns(Base64_Encode1) -#define kwsysBase64_Encode2 kwsys_ns(Base64_Encode2) -#define kwsysBase64_Encode3 kwsys_ns(Base64_Encode3) +#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# define kwsysBase64 kwsys_ns(Base64) +# define kwsysBase64_Decode kwsys_ns(Base64_Decode) +# define kwsysBase64_Decode3 kwsys_ns(Base64_Decode3) +# define kwsysBase64_Encode kwsys_ns(Base64_Encode) +# define kwsysBase64_Encode1 kwsys_ns(Base64_Encode1) +# define kwsysBase64_Encode2 kwsys_ns(Base64_Encode2) +# define kwsysBase64_Encode3 kwsys_ns(Base64_Encode3) +#endif #if defined(__cplusplus) extern "C" @@ -106,13 +108,15 @@ kwsysEXPORT unsigned long kwsysBase64_Decode(const unsigned char *input, #if !defined(KWSYS_NAMESPACE) # undef kwsys_ns # undef kwsysEXPORT -# undef kwsysBase64 -# undef kwsysBase64_Decode -# undef kwsysBase64_Decode3 -# undef kwsysBase64_Encode -# undef kwsysBase64_Encode1 -# undef kwsysBase64_Encode2 -# undef kwsysBase64_Encode3 +# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# undef kwsysBase64 +# undef kwsysBase64_Decode +# undef kwsysBase64_Decode3 +# undef kwsysBase64_Encode +# undef kwsysBase64_Encode1 +# undef kwsysBase64_Encode2 +# undef kwsysBase64_Encode3 +# endif #endif #endif diff --git a/Utilities/ITK/Utilities/kwsys/CommandLineArguments.cxx b/Utilities/ITK/Utilities/kwsys/CommandLineArguments.cxx index fecec7e2c6..8d35b0993a 100644 --- a/Utilities/ITK/Utilities/kwsys/CommandLineArguments.cxx +++ b/Utilities/ITK/Utilities/kwsys/CommandLineArguments.cxx @@ -521,7 +521,7 @@ unsigned int CommandLineArguments::GetLastArgument() void CommandLineArguments::GenerateHelp() { kwsys_ios::ostringstream str; - + // Collapse all arguments into the map of vectors of all arguments that do // the same thing. CommandLineArguments::Internal::CallbacksMap::iterator it; @@ -660,7 +660,7 @@ void CommandLineArguments::GenerateHelp() skip = cc; } } - str.write(ptr, skip); + str.write(ptr, static_cast<kwsys_ios::streamsize>(skip)); str << kwsys_ios::endl; ptr += skip; len -= skip; @@ -701,7 +701,7 @@ void CommandLineArguments::PopulateVariable( int* variable, const kwsys_stl::string& value) { char* res = 0; - *variable = strtol(value.c_str(), &res, 10); + *variable = static_cast<int>(strtol(value.c_str(), &res, 10)); //if ( res && *res ) // { // Can handle non-int @@ -759,7 +759,7 @@ void CommandLineArguments::PopulateVariable( kwsys_stl::vector<int>* variable, const kwsys_stl::string& value) { char* res = 0; - variable->push_back(strtol(value.c_str(), &res, 10)); + variable->push_back(static_cast<int>(strtol(value.c_str(), &res, 10))); //if ( res && *res ) // { // Can handle non-int diff --git a/Utilities/ITK/Utilities/kwsys/Configure.h.in b/Utilities/ITK/Utilities/kwsys/Configure.h.in index 0fdc6441ef..9f34eac3aa 100644 --- a/Utilities/ITK/Utilities/kwsys/Configure.h.in +++ b/Utilities/ITK/Utilities/kwsys/Configure.h.in @@ -22,6 +22,9 @@ # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif +/* Whether kwsys namespace is "kwsys". */ +#define @KWSYS_NAMESPACE@_NAME_IS_KWSYS @KWSYS_NAME_IS_KWSYS@ + /* If we are building a kwsys .c or .cxx file, suppress the Microsoft deprecation warnings. */ #if defined(KWSYS_NAMESPACE) diff --git a/Utilities/ITK/Utilities/kwsys/Configure.hxx.in b/Utilities/ITK/Utilities/kwsys/Configure.hxx.in index cb7817fa6a..fc77b35a57 100644 --- a/Utilities/ITK/Utilities/kwsys/Configure.hxx.in +++ b/Utilities/ITK/Utilities/kwsys/Configure.hxx.in @@ -17,9 +17,6 @@ /* Include C configuration. */ #include <@KWSYS_NAMESPACE@/Configure.h> -/* Whether kwsys namespace is "kwsys". */ -#define @KWSYS_NAMESPACE@_NAME_IS_KWSYS @KWSYS_NAME_IS_KWSYS@ - /* Whether ANSI C++ stream headers are to be used. */ #define @KWSYS_NAMESPACE@_IOS_USE_ANSI @KWSYS_IOS_USE_ANSI@ diff --git a/Utilities/ITK/Utilities/kwsys/FundamentalType.h.in b/Utilities/ITK/Utilities/kwsys/FundamentalType.h.in index 648270f88a..5d057343e6 100644 --- a/Utilities/ITK/Utilities/kwsys/FundamentalType.h.in +++ b/Utilities/ITK/Utilities/kwsys/FundamentalType.h.in @@ -24,15 +24,18 @@ # define kwsys_ns(x) @KWSYS_NAMESPACE@##x # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif -#define kwsysFundamentalType kwsys_ns(FundamentalType) -#define kwsysFundamentalType_Int8 kwsys_ns(FundamentalType_Int8) -#define kwsysFundamentalType_UInt8 kwsys_ns(FundamentalType_UInt8) -#define kwsysFundamentalType_Int16 kwsys_ns(FundamentalType_Int16) -#define kwsysFundamentalType_UInt16 kwsys_ns(FundamentalType_UInt16) -#define kwsysFundamentalType_Int32 kwsys_ns(FundamentalType_Int32) -#define kwsysFundamentalType_UInt32 kwsys_ns(FundamentalType_UInt32) -#define kwsysFundamentalType_Int64 kwsys_ns(FundamentalType_Int64) -#define kwsysFundamentalType_UInt64 kwsys_ns(FundamentalType_UInt64) + +#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# define kwsysFundamentalType kwsys_ns(FundamentalType) +# define kwsysFundamentalType_Int8 kwsys_ns(FundamentalType_Int8) +# define kwsysFundamentalType_UInt8 kwsys_ns(FundamentalType_UInt8) +# define kwsysFundamentalType_Int16 kwsys_ns(FundamentalType_Int16) +# define kwsysFundamentalType_UInt16 kwsys_ns(FundamentalType_UInt16) +# define kwsysFundamentalType_Int32 kwsys_ns(FundamentalType_Int32) +# define kwsysFundamentalType_UInt32 kwsys_ns(FundamentalType_UInt32) +# define kwsysFundamentalType_Int64 kwsys_ns(FundamentalType_Int64) +# define kwsysFundamentalType_UInt64 kwsys_ns(FundamentalType_UInt64) +#endif /* The size of fundamental types. Types that do not exist have size 0. */ #define @KWSYS_NAMESPACE@_SIZEOF_CHAR @KWSYS_SIZEOF_CHAR@ @@ -114,15 +117,17 @@ typedef unsigned __int64 kwsysFundamentalType_UInt64; #if !defined(KWSYS_NAMESPACE) # undef kwsys_ns # undef kwsysEXPORT -# undef kwsysFundamentalType -# undef kwsysFundamentalType_Int8 -# undef kwsysFundamentalType_UInt8 -# undef kwsysFundamentalType_Int16 -# undef kwsysFundamentalType_UInt16 -# undef kwsysFundamentalType_Int32 -# undef kwsysFundamentalType_UInt32 -# undef kwsysFundamentalType_Int64 -# undef kwsysFundamentalType_UInt64 +# if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# undef kwsysFundamentalType +# undef kwsysFundamentalType_Int8 +# undef kwsysFundamentalType_UInt8 +# undef kwsysFundamentalType_Int16 +# undef kwsysFundamentalType_UInt16 +# undef kwsysFundamentalType_Int32 +# undef kwsysFundamentalType_UInt32 +# undef kwsysFundamentalType_Int64 +# undef kwsysFundamentalType_UInt64 +# endif #endif /* If building a C or C++ file in kwsys itself, give the source file diff --git a/Utilities/ITK/Utilities/kwsys/Glob.cxx b/Utilities/ITK/Utilities/kwsys/Glob.cxx index bc9a902eb2..4c17d63549 100644 --- a/Utilities/ITK/Utilities/kwsys/Glob.cxx +++ b/Utilities/ITK/Utilities/kwsys/Glob.cxx @@ -380,13 +380,13 @@ bool Glob::FindFiles(const kwsys_stl::string& inexpr) } kwsys_stl::string fexpr = expr; - int skip = 0; - int last_slash = 0; + kwsys_stl::string::size_type skip = 0; + kwsys_stl::string::size_type last_slash = 0; for ( cc = 0; cc < expr.size(); cc ++ ) { if ( cc > 0 && expr[cc] == '/' && expr[cc-1] != '\\' ) { - last_slash = static_cast<int>(cc); + last_slash = cc; } if ( cc > 0 && (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') && diff --git a/Utilities/ITK/Utilities/kwsys/MD5.h.in b/Utilities/ITK/Utilities/kwsys/MD5.h.in index 148f220da6..ae46d21fc3 100644 --- a/Utilities/ITK/Utilities/kwsys/MD5.h.in +++ b/Utilities/ITK/Utilities/kwsys/MD5.h.in @@ -24,15 +24,17 @@ # define kwsys_ns(x) @KWSYS_NAMESPACE@##x # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif -#define kwsysMD5 kwsys_ns(MD5) -#define kwsysMD5_s kwsys_ns(MD5_s) -#define kwsysMD5_New kwsys_ns(MD5_New) -#define kwsysMD5_Delete kwsys_ns(MD5_Delete) -#define kwsysMD5_Initialize kwsys_ns(MD5_Initialize) -#define kwsysMD5_Append kwsys_ns(MD5_Append) -#define kwsysMD5_Finalize kwsys_ns(MD5_Finalize) -#define kwsysMD5_FinalizeHex kwsys_ns(MD5_FinalizeHex) -#define kwsysMD5_DigestToHex kwsys_ns(MD5_DigestToHex) +#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# define kwsysMD5 kwsys_ns(MD5) +# define kwsysMD5_s kwsys_ns(MD5_s) +# define kwsysMD5_New kwsys_ns(MD5_New) +# define kwsysMD5_Delete kwsys_ns(MD5_Delete) +# define kwsysMD5_Initialize kwsys_ns(MD5_Initialize) +# define kwsysMD5_Append kwsys_ns(MD5_Append) +# define kwsysMD5_Finalize kwsys_ns(MD5_Finalize) +# define kwsysMD5_FinalizeHex kwsys_ns(MD5_FinalizeHex) +# define kwsysMD5_DigestToHex kwsys_ns(MD5_DigestToHex) +#endif #if defined(__cplusplus) extern "C" @@ -91,15 +93,17 @@ kwsysEXPORT void kwsysMD5_DigestToHex(unsigned char const digest[16], #if !defined(KWSYS_NAMESPACE) # undef kwsys_ns # undef kwsysEXPORT -# undef kwsysMD5 -# undef kwsysMD5_s -# undef kwsysMD5_New -# undef kwsysMD5_Delete -# undef kwsysMD5_Initialize -# undef kwsysMD5_Append -# undef kwsysMD5_Finalize -# undef kwsysMD5_FinalizeHex -# undef kwsysMD5_DigestToHex +# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# undef kwsysMD5 +# undef kwsysMD5_s +# undef kwsysMD5_New +# undef kwsysMD5_Delete +# undef kwsysMD5_Initialize +# undef kwsysMD5_Append +# undef kwsysMD5_Finalize +# undef kwsysMD5_FinalizeHex +# undef kwsysMD5_DigestToHex +# endif #endif #endif diff --git a/Utilities/ITK/Utilities/kwsys/Process.h.in b/Utilities/ITK/Utilities/kwsys/Process.h.in index 74dc2b8d39..1c76c5a155 100644 --- a/Utilities/ITK/Utilities/kwsys/Process.h.in +++ b/Utilities/ITK/Utilities/kwsys/Process.h.in @@ -24,57 +24,59 @@ # define kwsys_ns(x) @KWSYS_NAMESPACE@##x # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif -#define kwsysProcess kwsys_ns(Process) -#define kwsysProcess_s kwsys_ns(Process_s) -#define kwsysProcess_New kwsys_ns(Process_New) -#define kwsysProcess_Delete kwsys_ns(Process_Delete) -#define kwsysProcess_SetCommand kwsys_ns(Process_SetCommand) -#define kwsysProcess_AddCommand kwsys_ns(Process_AddCommand) -#define kwsysProcess_SetTimeout kwsys_ns(Process_SetTimeout) -#define kwsysProcess_SetWorkingDirectory kwsys_ns(Process_SetWorkingDirectory) -#define kwsysProcess_SetPipeFile kwsys_ns(Process_SetPipeFile) -#define kwsysProcess_SetPipeNative kwsys_ns(Process_SetPipeNative) -#define kwsysProcess_SetPipeShared kwsys_ns(Process_SetPipeShared) -#define kwsysProcess_Option_Detach kwsys_ns(Process_Option_Detach) -#define kwsysProcess_Option_HideWindow kwsys_ns(Process_Option_HideWindow) -#define kwsysProcess_Option_Verbatim kwsys_ns(Process_Option_Verbatim) -#define kwsysProcess_GetOption kwsys_ns(Process_GetOption) -#define kwsysProcess_SetOption kwsys_ns(Process_SetOption) -#define kwsysProcess_Option_e kwsys_ns(Process_Option_e) -#define kwsysProcess_State_Starting kwsys_ns(Process_State_Starting) -#define kwsysProcess_State_Error kwsys_ns(Process_State_Error) -#define kwsysProcess_State_Exception kwsys_ns(Process_State_Exception) -#define kwsysProcess_State_Executing kwsys_ns(Process_State_Executing) -#define kwsysProcess_State_Exited kwsys_ns(Process_State_Exited) -#define kwsysProcess_State_Expired kwsys_ns(Process_State_Expired) -#define kwsysProcess_State_Killed kwsys_ns(Process_State_Killed) -#define kwsysProcess_State_Disowned kwsys_ns(Process_State_Disowned) -#define kwsysProcess_GetState kwsys_ns(Process_GetState) -#define kwsysProcess_State_e kwsys_ns(Process_State_e) -#define kwsysProcess_Exception_None kwsys_ns(Process_Exception_None) -#define kwsysProcess_Exception_Fault kwsys_ns(Process_Exception_Fault) -#define kwsysProcess_Exception_Illegal kwsys_ns(Process_Exception_Illegal) -#define kwsysProcess_Exception_Interrupt kwsys_ns(Process_Exception_Interrupt) -#define kwsysProcess_Exception_Numerical kwsys_ns(Process_Exception_Numerical) -#define kwsysProcess_Exception_Other kwsys_ns(Process_Exception_Other) -#define kwsysProcess_GetExitException kwsys_ns(Process_GetExitException) -#define kwsysProcess_Exception_e kwsys_ns(Process_Exception_e) -#define kwsysProcess_GetExitCode kwsys_ns(Process_GetExitCode) -#define kwsysProcess_GetExitValue kwsys_ns(Process_GetExitValue) -#define kwsysProcess_GetErrorString kwsys_ns(Process_GetErrorString) -#define kwsysProcess_GetExceptionString kwsys_ns(Process_GetExceptionString) -#define kwsysProcess_Execute kwsys_ns(Process_Execute) -#define kwsysProcess_Disown kwsys_ns(Process_Disown) -#define kwsysProcess_WaitForData kwsys_ns(Process_WaitForData) -#define kwsysProcess_Pipes_e kwsys_ns(Process_Pipes_e) -#define kwsysProcess_Pipe_None kwsys_ns(Process_Pipe_None) -#define kwsysProcess_Pipe_STDIN kwsys_ns(Process_Pipe_STDIN) -#define kwsysProcess_Pipe_STDOUT kwsys_ns(Process_Pipe_STDOUT) -#define kwsysProcess_Pipe_STDERR kwsys_ns(Process_Pipe_STDERR) -#define kwsysProcess_Pipe_Timeout kwsys_ns(Process_Pipe_Timeout) -#define kwsysProcess_Pipe_Handle kwsys_ns(Process_Pipe_Handle) -#define kwsysProcess_WaitForExit kwsys_ns(Process_WaitForExit) -#define kwsysProcess_Kill kwsys_ns(Process_Kill) +#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# define kwsysProcess kwsys_ns(Process) +# define kwsysProcess_s kwsys_ns(Process_s) +# define kwsysProcess_New kwsys_ns(Process_New) +# define kwsysProcess_Delete kwsys_ns(Process_Delete) +# define kwsysProcess_SetCommand kwsys_ns(Process_SetCommand) +# define kwsysProcess_AddCommand kwsys_ns(Process_AddCommand) +# define kwsysProcess_SetTimeout kwsys_ns(Process_SetTimeout) +# define kwsysProcess_SetWorkingDirectory kwsys_ns(Process_SetWorkingDirectory) +# define kwsysProcess_SetPipeFile kwsys_ns(Process_SetPipeFile) +# define kwsysProcess_SetPipeNative kwsys_ns(Process_SetPipeNative) +# define kwsysProcess_SetPipeShared kwsys_ns(Process_SetPipeShared) +# define kwsysProcess_Option_Detach kwsys_ns(Process_Option_Detach) +# define kwsysProcess_Option_HideWindow kwsys_ns(Process_Option_HideWindow) +# define kwsysProcess_Option_Verbatim kwsys_ns(Process_Option_Verbatim) +# define kwsysProcess_GetOption kwsys_ns(Process_GetOption) +# define kwsysProcess_SetOption kwsys_ns(Process_SetOption) +# define kwsysProcess_Option_e kwsys_ns(Process_Option_e) +# define kwsysProcess_State_Starting kwsys_ns(Process_State_Starting) +# define kwsysProcess_State_Error kwsys_ns(Process_State_Error) +# define kwsysProcess_State_Exception kwsys_ns(Process_State_Exception) +# define kwsysProcess_State_Executing kwsys_ns(Process_State_Executing) +# define kwsysProcess_State_Exited kwsys_ns(Process_State_Exited) +# define kwsysProcess_State_Expired kwsys_ns(Process_State_Expired) +# define kwsysProcess_State_Killed kwsys_ns(Process_State_Killed) +# define kwsysProcess_State_Disowned kwsys_ns(Process_State_Disowned) +# define kwsysProcess_GetState kwsys_ns(Process_GetState) +# define kwsysProcess_State_e kwsys_ns(Process_State_e) +# define kwsysProcess_Exception_None kwsys_ns(Process_Exception_None) +# define kwsysProcess_Exception_Fault kwsys_ns(Process_Exception_Fault) +# define kwsysProcess_Exception_Illegal kwsys_ns(Process_Exception_Illegal) +# define kwsysProcess_Exception_Interrupt kwsys_ns(Process_Exception_Interrupt) +# define kwsysProcess_Exception_Numerical kwsys_ns(Process_Exception_Numerical) +# define kwsysProcess_Exception_Other kwsys_ns(Process_Exception_Other) +# define kwsysProcess_GetExitException kwsys_ns(Process_GetExitException) +# define kwsysProcess_Exception_e kwsys_ns(Process_Exception_e) +# define kwsysProcess_GetExitCode kwsys_ns(Process_GetExitCode) +# define kwsysProcess_GetExitValue kwsys_ns(Process_GetExitValue) +# define kwsysProcess_GetErrorString kwsys_ns(Process_GetErrorString) +# define kwsysProcess_GetExceptionString kwsys_ns(Process_GetExceptionString) +# define kwsysProcess_Execute kwsys_ns(Process_Execute) +# define kwsysProcess_Disown kwsys_ns(Process_Disown) +# define kwsysProcess_WaitForData kwsys_ns(Process_WaitForData) +# define kwsysProcess_Pipes_e kwsys_ns(Process_Pipes_e) +# define kwsysProcess_Pipe_None kwsys_ns(Process_Pipe_None) +# define kwsysProcess_Pipe_STDIN kwsys_ns(Process_Pipe_STDIN) +# define kwsysProcess_Pipe_STDOUT kwsys_ns(Process_Pipe_STDOUT) +# define kwsysProcess_Pipe_STDERR kwsys_ns(Process_Pipe_STDERR) +# define kwsysProcess_Pipe_Timeout kwsys_ns(Process_Pipe_Timeout) +# define kwsysProcess_Pipe_Handle kwsys_ns(Process_Pipe_Handle) +# define kwsysProcess_WaitForExit kwsys_ns(Process_WaitForExit) +# define kwsysProcess_Kill kwsys_ns(Process_Kill) +#endif #if defined(__cplusplus) extern "C" @@ -370,57 +372,59 @@ kwsysEXPORT void kwsysProcess_Kill(kwsysProcess* cp); #if !defined(KWSYS_NAMESPACE) # undef kwsys_ns # undef kwsysEXPORT -# undef kwsysProcess -# undef kwsysProcess_s -# undef kwsysProcess_New -# undef kwsysProcess_Delete -# undef kwsysProcess_SetCommand -# undef kwsysProcess_AddCommand -# undef kwsysProcess_SetTimeout -# undef kwsysProcess_SetWorkingDirectory -# undef kwsysProcess_SetPipeFile -# undef kwsysProcess_SetPipeNative -# undef kwsysProcess_SetPipeShared -# undef kwsysProcess_Option_Detach -# undef kwsysProcess_Option_HideWindow -# undef kwsysProcess_Option_Verbatim -# undef kwsysProcess_GetOption -# undef kwsysProcess_SetOption -# undef kwsysProcess_Option_e -# undef kwsysProcess_State_Starting -# undef kwsysProcess_State_Error -# undef kwsysProcess_State_Exception -# undef kwsysProcess_State_Executing -# undef kwsysProcess_State_Exited -# undef kwsysProcess_State_Expired -# undef kwsysProcess_State_Killed -# undef kwsysProcess_State_Disowned -# undef kwsysProcess_GetState -# undef kwsysProcess_State_e -# undef kwsysProcess_Exception_None -# undef kwsysProcess_Exception_Fault -# undef kwsysProcess_Exception_Illegal -# undef kwsysProcess_Exception_Interrupt -# undef kwsysProcess_Exception_Numerical -# undef kwsysProcess_Exception_Other -# undef kwsysProcess_GetExitException -# undef kwsysProcess_Exception_e -# undef kwsysProcess_GetExitCode -# undef kwsysProcess_GetExitValue -# undef kwsysProcess_GetErrorString -# undef kwsysProcess_GetExceptionString -# undef kwsysProcess_Execute -# undef kwsysProcess_Disown -# undef kwsysProcess_WaitForData -# undef kwsysProcess_Pipes_e -# undef kwsysProcess_Pipe_None -# undef kwsysProcess_Pipe_STDIN -# undef kwsysProcess_Pipe_STDOUT -# undef kwsysProcess_Pipe_STDERR -# undef kwsysProcess_Pipe_Timeout -# undef kwsysProcess_Pipe_Handle -# undef kwsysProcess_WaitForExit -# undef kwsysProcess_Kill +# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# undef kwsysProcess +# undef kwsysProcess_s +# undef kwsysProcess_New +# undef kwsysProcess_Delete +# undef kwsysProcess_SetCommand +# undef kwsysProcess_AddCommand +# undef kwsysProcess_SetTimeout +# undef kwsysProcess_SetWorkingDirectory +# undef kwsysProcess_SetPipeFile +# undef kwsysProcess_SetPipeNative +# undef kwsysProcess_SetPipeShared +# undef kwsysProcess_Option_Detach +# undef kwsysProcess_Option_HideWindow +# undef kwsysProcess_Option_Verbatim +# undef kwsysProcess_GetOption +# undef kwsysProcess_SetOption +# undef kwsysProcess_Option_e +# undef kwsysProcess_State_Starting +# undef kwsysProcess_State_Error +# undef kwsysProcess_State_Exception +# undef kwsysProcess_State_Executing +# undef kwsysProcess_State_Exited +# undef kwsysProcess_State_Expired +# undef kwsysProcess_State_Killed +# undef kwsysProcess_State_Disowned +# undef kwsysProcess_GetState +# undef kwsysProcess_State_e +# undef kwsysProcess_Exception_None +# undef kwsysProcess_Exception_Fault +# undef kwsysProcess_Exception_Illegal +# undef kwsysProcess_Exception_Interrupt +# undef kwsysProcess_Exception_Numerical +# undef kwsysProcess_Exception_Other +# undef kwsysProcess_GetExitException +# undef kwsysProcess_Exception_e +# undef kwsysProcess_GetExitCode +# undef kwsysProcess_GetExitValue +# undef kwsysProcess_GetErrorString +# undef kwsysProcess_GetExceptionString +# undef kwsysProcess_Execute +# undef kwsysProcess_Disown +# undef kwsysProcess_WaitForData +# undef kwsysProcess_Pipes_e +# undef kwsysProcess_Pipe_None +# undef kwsysProcess_Pipe_STDIN +# undef kwsysProcess_Pipe_STDOUT +# undef kwsysProcess_Pipe_STDERR +# undef kwsysProcess_Pipe_Timeout +# undef kwsysProcess_Pipe_Handle +# undef kwsysProcess_WaitForExit +# undef kwsysProcess_Kill +# endif #endif #endif diff --git a/Utilities/ITK/Utilities/kwsys/ProcessUNIX.c b/Utilities/ITK/Utilities/kwsys/ProcessUNIX.c index fb31464935..938683820e 100644 --- a/Utilities/ITK/Utilities/kwsys/ProcessUNIX.c +++ b/Utilities/ITK/Utilities/kwsys/ProcessUNIX.c @@ -390,7 +390,8 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command) /* Allocate a new array for command pointers. */ newNumberOfCommands = cp->NumberOfCommands + 1; - if(!(newCommands = (char***)malloc(sizeof(char**) * newNumberOfCommands))) + if(!(newCommands = + (char***)malloc(sizeof(char**) *(size_t)(newNumberOfCommands)))) { /* Out of memory. */ return 0; @@ -427,7 +428,8 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command) kwsysProcess_ptrdiff_t i = 0; while(*c++); n = c - command - 1; - newCommands[cp->NumberOfCommands] = (char**)malloc((n+1)*sizeof(char*)); + newCommands[cp->NumberOfCommands] = + (char**)malloc((size_t)(n+1)*sizeof(char*)); if(!newCommands[cp->NumberOfCommands]) { /* Out of memory. */ @@ -1049,7 +1051,7 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length, { /* Report this data. */ *data = cp->PipeBuffer; - *length = n; + *length = (int)(n); switch(i) { case KWSYSPE_PIPE_STDOUT: @@ -1399,23 +1401,24 @@ static int kwsysProcessInitialize(kwsysProcess* cp) { free(cp->ForkPIDs); } - cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*cp->NumberOfCommands); + cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*(size_t)(cp->NumberOfCommands)); if(!cp->ForkPIDs) { return 0; } - memset(cp->ForkPIDs, 0, sizeof(pid_t)*cp->NumberOfCommands); + memset(cp->ForkPIDs, 0, sizeof(pid_t)*(size_t)(cp->NumberOfCommands)); if(cp->CommandExitCodes) { free(cp->CommandExitCodes); } - cp->CommandExitCodes = (int*)malloc(sizeof(int)*cp->NumberOfCommands); + cp->CommandExitCodes = (int*)malloc(sizeof(int)* + (size_t)(cp->NumberOfCommands)); if(!cp->CommandExitCodes) { return 0; } - memset(cp->CommandExitCodes, 0, sizeof(int)*cp->NumberOfCommands); + memset(cp->CommandExitCodes, 0, sizeof(int)*(size_t)(cp->NumberOfCommands)); /* Allocate memory to save the real working directory. */ if ( cp->WorkingDirectory ) @@ -1951,7 +1954,7 @@ static kwsysProcessTime kwsysProcessTimeGetCurrent(void) /*--------------------------------------------------------------------------*/ static double kwsysProcessTimeToDouble(kwsysProcessTime t) { - return (double)t.tv_sec + t.tv_usec*0.000001; + return (double)t.tv_sec + (double)(t.tv_usec)*0.000001; } /*--------------------------------------------------------------------------*/ @@ -1959,7 +1962,7 @@ static kwsysProcessTime kwsysProcessTimeFromDouble(double d) { kwsysProcessTime t; t.tv_sec = (long)d; - t.tv_usec = (long)((d-t.tv_sec)*1000000); + t.tv_usec = (long)((d-(double)(t.tv_sec))*1000000); return t; } @@ -2134,10 +2137,12 @@ static void kwsysProcessChildErrorExit(int errorPipe) { /* Construct the error message. */ char buffer[KWSYSPE_PIPE_BUFFER_SIZE]; + kwsysProcess_ssize_t result; strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE); /* Report the error to the parent through the special pipe. */ - write(errorPipe, buffer, strlen(buffer)); + result=write(errorPipe, buffer, strlen(buffer)); + (void)result; /* Terminate without cleanup. */ _exit(1); @@ -2265,6 +2270,9 @@ static pid_t kwsysProcessFork(kwsysProcess* cp, if(cp->OptionDetach) { /* Create an intermediate process. */ +#ifdef __VMS +#define fork vfork +#endif pid_t middle_pid = fork(); if(middle_pid < 0) { @@ -2379,7 +2387,7 @@ static void kwsysProcessKill(pid_t process_id) FILE* f = fopen(fname, "r"); if(f) { - int nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f); + size_t nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f); buffer[nread] = '\0'; if(nread > 0) { @@ -2513,14 +2521,14 @@ static int kwsysProcessesAdd(kwsysProcess* cp) /* Try allocating the new block of memory. */ if((newProcesses.Processes = ((kwsysProcess**) - malloc(newProcesses.Size* + malloc((size_t)(newProcesses.Size)* sizeof(kwsysProcess*))))) { /* Copy the old pipe set to the new memory. */ if(oldProcesses.Count > 0) { memcpy(newProcesses.Processes, oldProcesses.Processes, - (oldProcesses.Count * sizeof(kwsysProcess*))); + ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*))); } } else @@ -2638,8 +2646,10 @@ static void kwsysProcessesSignalHandler(int signum /* Set the pipe in a signalled state. */ char buf = 1; kwsysProcess* cp = kwsysProcesses.Processes[i]; - read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1); - write(cp->SignalPipe, &buf, 1); + kwsysProcess_ssize_t status= + read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1); + status=write(cp->SignalPipe, &buf, 1); + } } @@ -2672,7 +2682,7 @@ static int kwsysProcessAppendByte(char* local, { return 0; } - memcpy(newBuffer, *begin, length*sizeof(char)); + memcpy(newBuffer, *begin, (size_t)(length)*sizeof(char)); if(*begin != local) { free(*begin); @@ -2705,12 +2715,12 @@ static int kwsysProcessAppendArgument(char** local, if((*end - *begin) >= *size) { kwsysProcess_ptrdiff_t length = *end - *begin; - char** newPointers = (char**)malloc(*size*2*sizeof(char*)); + char** newPointers = (char**)malloc((size_t)(*size)*2*sizeof(char*)); if(!newPointers) { return 0; } - memcpy(newPointers, *begin, length*sizeof(char*)); + memcpy(newPointers, *begin, (size_t)(length)*sizeof(char*)); if(*begin != local) { free(*begin); @@ -2878,14 +2888,14 @@ static char** kwsysProcessParseVerbatimCommand(const char* command) if(!failed) { kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin; - newCommand = (char**)malloc((n+1)*sizeof(char*)); + newCommand = (char**)malloc((size_t)(n+1)*sizeof(char*)); } if(newCommand) { /* Copy the arguments into the new command buffer. */ kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin; - memcpy(newCommand, pointer_begin, sizeof(char*)*n); + memcpy(newCommand, pointer_begin, sizeof(char*)*(size_t)(n)); newCommand[n] = 0; } else diff --git a/Utilities/ITK/Utilities/kwsys/RegularExpression.cxx b/Utilities/ITK/Utilities/kwsys/RegularExpression.cxx index 45fd5429dc..abec755cdf 100644 --- a/Utilities/ITK/Utilities/kwsys/RegularExpression.cxx +++ b/Utilities/ITK/Utilities/kwsys/RegularExpression.cxx @@ -269,7 +269,7 @@ const unsigned char MAGIC = 0234; * Utility definitions. */ -#define UCHARAT(p) ((const unsigned char*)(p))[0] +#define UCHARAT(p) (reinterpret_cast<const unsigned char*>(p))[0] #define FAIL(m) { regerror(m); return(0); } @@ -316,7 +316,7 @@ static char* regatom (int*); static char* regnode (char); static const char* regnext (register const char*); static char* regnext (register char*); -static void regc (unsigned char); +static void regc (char); static void reginsert (char, char*); static void regtail (char*, const char*); static void regoptail (char*, const char*); @@ -348,7 +348,7 @@ static int strcspn (); bool RegularExpression::compile (const char* exp) { register const char* scan; register const char* longest; - register unsigned long len; + register size_t len; int flags; if (exp == 0) { @@ -362,7 +362,7 @@ bool RegularExpression::compile (const char* exp) { regnpar = 1; regsize = 0L; regcode = ®dummy; - regc(MAGIC); + regc(static_cast<char>(MAGIC)); if(!reg(0, &flags)) { printf ("RegularExpression::compile(): Error in compile.\n"); @@ -394,7 +394,7 @@ bool RegularExpression::compile (const char* exp) { regparse = exp; regnpar = 1; regcode = this->program; - regc(MAGIC); + regc(static_cast<char>(MAGIC)); reg(0, &flags); // Dig out information for optimizations. @@ -426,7 +426,7 @@ bool RegularExpression::compile (const char* exp) { for (; scan != 0; scan = regnext(scan)) if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) { longest = OPERAND(scan); - len = int(strlen(OPERAND(scan))); + len = strlen(OPERAND(scan)); } this->regmust = longest; this->regmlen = len; @@ -675,7 +675,7 @@ static char* regatom (int *flagp) { return 0; } for (; rxpclass <= rxpclassend; rxpclass++) - regc(static_cast<unsigned char>(rxpclass)); + regc(static_cast<char>(rxpclass)); regparse++; } } @@ -778,7 +778,7 @@ static char* regnode (char op) { /* - regc - emit (if appropriate) a byte of code */ -static void regc (unsigned char b) { +static void regc (char b) { if (regcode != ®dummy) *regcode++ = b; else @@ -1018,14 +1018,14 @@ static int regmatch (const char* prog) { reginput++; break; case EXACTLY:{ - register int len; + register size_t len; register const char* opnd; opnd = OPERAND(scan); // Inline the first character, for speed. if (*opnd != *reginput) return (0); - len = int(strlen(opnd)); + len = strlen(opnd); if (len > 1 && strncmp(opnd, reginput, len) != 0) return (0); reginput += len; @@ -1234,7 +1234,6 @@ static const char* regnext (register const char* p) { return (p + offset); } - static char* regnext (register char* p) { register int offset; diff --git a/Utilities/ITK/Utilities/kwsys/RegularExpression.hxx.in b/Utilities/ITK/Utilities/kwsys/RegularExpression.hxx.in index 8459e078e7..2aa8a9aeed 100644 --- a/Utilities/ITK/Utilities/kwsys/RegularExpression.hxx.in +++ b/Utilities/ITK/Utilities/kwsys/RegularExpression.hxx.in @@ -281,7 +281,7 @@ private: char regstart; // Internal use only char reganch; // Internal use only const char* regmust; // Internal use only - unsigned long regmlen; // Internal use only + kwsys_stl::string::size_type regmlen; // Internal use only char* program; int progsize; const char* searchstring; @@ -323,7 +323,8 @@ inline RegularExpression::~RegularExpression () */ inline kwsys_stl::string::size_type RegularExpression::start () const { - return(this->startp[0] - searchstring); + return static_cast<kwsys_stl::string::size_type>( + this->startp[0] - searchstring); } @@ -332,7 +333,8 @@ inline kwsys_stl::string::size_type RegularExpression::start () const */ inline kwsys_stl::string::size_type RegularExpression::end () const { - return(this->endp[0] - searchstring); + return static_cast<kwsys_stl::string::size_type>( + this->endp[0] - searchstring); } /** @@ -367,7 +369,8 @@ inline void RegularExpression::set_invalid () */ inline kwsys_stl::string::size_type RegularExpression::start(int n) const { - return this->startp[n] - searchstring; + return static_cast<kwsys_stl::string::size_type>( + this->startp[n] - searchstring); } @@ -376,7 +379,8 @@ inline kwsys_stl::string::size_type RegularExpression::start(int n) const */ inline kwsys_stl::string::size_type RegularExpression::end(int n) const { - return this->endp[n] - searchstring; + return static_cast<kwsys_stl::string::size_type>( + this->endp[n] - searchstring); } /** @@ -390,7 +394,9 @@ inline kwsys_stl::string RegularExpression::match(int n) const } else { - return kwsys_stl::string(this->startp[n], this->endp[n] - this->startp[n]); + return kwsys_stl::string(this->startp[n], + static_cast<kwsys_stl::string::size_type>( + this->endp[n] - this->startp[n])); } } diff --git a/Utilities/ITK/Utilities/kwsys/String.h.in b/Utilities/ITK/Utilities/kwsys/String.h.in index 49a067b126..4bb9782d07 100644 --- a/Utilities/ITK/Utilities/kwsys/String.h.in +++ b/Utilities/ITK/Utilities/kwsys/String.h.in @@ -26,8 +26,10 @@ # define kwsys_ns(x) @KWSYS_NAMESPACE@##x # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif -#define kwsysString_strcasecmp kwsys_ns(String_strcasecmp) -#define kwsysString_strncasecmp kwsys_ns(String_strncasecmp) +#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# define kwsysString_strcasecmp kwsys_ns(String_strcasecmp) +# define kwsysString_strncasecmp kwsys_ns(String_strncasecmp) +#endif #if defined(__cplusplus) extern "C" @@ -58,8 +60,10 @@ kwsysEXPORT int kwsysString_strncasecmp(const char* lhs, const char* rhs, #if !defined(KWSYS_NAMESPACE) # undef kwsys_ns # undef kwsysEXPORT -# undef kwsysString_strcasecmp -# undef kwsysString_strncasecmp +# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# undef kwsysString_strcasecmp +# undef kwsysString_strncasecmp +# endif #endif #endif diff --git a/Utilities/ITK/Utilities/kwsys/System.h.in b/Utilities/ITK/Utilities/kwsys/System.h.in index c8bae4cb25..d890a3c923 100644 --- a/Utilities/ITK/Utilities/kwsys/System.h.in +++ b/Utilities/ITK/Utilities/kwsys/System.h.in @@ -24,18 +24,29 @@ # define kwsys_ns(x) @KWSYS_NAMESPACE@##x # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif -#define kwsysSystem_Shell_GetArgumentForWindows kwsys_ns(System_Shell_GetArgumentForWindows) -#define kwsysSystem_Shell_GetArgumentForUnix kwsys_ns(System_Shell_GetArgumentForUnix) -#define kwsysSystem_Shell_GetArgumentSizeForWindows kwsys_ns(System_Shell_GetArgumentSizeForWindows) -#define kwsysSystem_Shell_GetArgumentSizeForUnix kwsys_ns(System_Shell_GetArgumentSizeForUnix) -#define kwsysSystem_Shell_Flag_e kwsys_ns(System_Shell_Flag_e) -#define kwsysSystem_Shell_Flag_Make kwsys_ns(System_Shell_Flag_Make) -#define kwsysSystem_Shell_Flag_VSIDE kwsys_ns(System_Shell_Flag_VSIDE) -#define kwsysSystem_Shell_Flag_EchoWindows kwsys_ns(System_Shell_Flag_EchoWindows) -#define kwsysSystem_Shell_Flag_WatcomWMake kwsys_ns(System_Shell_Flag_WatcomWMake) -#define kwsysSystem_Shell_Flag_MinGWMake kwsys_ns(System_Shell_Flag_MinGWMake) -#define kwsysSystem_Shell_Flag_NMake kwsys_ns(System_Shell_Flag_NMake) -#define kwsysSystem_Shell_Flag_AllowMakeVariables kwsys_ns(System_Shell_Flag_AllowMakeVariables) +#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# define kwsysSystem_Shell_GetArgumentForWindows kwsys_ns(System_Shell_GetArgumentForWindows) +# define kwsysSystem_Shell_GetArgumentForUnix kwsys_ns(System_Shell_GetArgumentForUnix) +# define kwsysSystem_Shell_GetArgumentSizeForWindows kwsys_ns(System_Shell_GetArgumentSizeForWindows) +# define kwsysSystem_Shell_GetArgumentSizeForUnix kwsys_ns(System_Shell_GetArgumentSizeForUnix) +# define kwsysSystem_Shell_Flag_e kwsys_ns(System_Shell_Flag_e) +# define kwsysSystem_Shell_Flag_Make kwsys_ns(System_Shell_Flag_Make) +# define kwsysSystem_Shell_Flag_VSIDE kwsys_ns(System_Shell_Flag_VSIDE) +# define kwsysSystem_Shell_Flag_EchoWindows kwsys_ns(System_Shell_Flag_EchoWindows) +# define kwsysSystem_Shell_Flag_WatcomWMake kwsys_ns(System_Shell_Flag_WatcomWMake) +# define kwsysSystem_Shell_Flag_MinGWMake kwsys_ns(System_Shell_Flag_MinGWMake) +# define kwsysSystem_Shell_Flag_NMake kwsys_ns(System_Shell_Flag_NMake) +# define kwsysSystem_Shell_Flag_AllowMakeVariables kwsys_ns(System_Shell_Flag_AllowMakeVariables) +#endif + +#ifdef __VMS +#define @KWSYS_NAMESPACE@System_Shell_GetArgumentForUnix \ + @KWSYS_NAMESPACE@System_Shell_UnixGA +#define @KWSYS_NAMESPACE@System_Shell_GetArgumentSizeForUnix \ + @KWSYS_NAMESPACE@System_Shell_UnixGAS +#define @KWSYS_NAMESPACE@System_Shell_GetArgumentForWindows \ + @KWSYS_NAMESPACE@System_Shell_WindowsGA +#endif #if defined(__cplusplus) extern "C" @@ -111,18 +122,20 @@ enum kwsysSystem_Shell_Flag_e #if !defined(KWSYS_NAMESPACE) # undef kwsys_ns # undef kwsysEXPORT -# undef kwsysSystem_Shell_GetArgumentForWindows -# undef kwsysSystem_Shell_GetArgumentForUnix -# undef kwsysSystem_Shell_GetArgumentSizeForWindows -# undef kwsysSystem_Shell_GetArgumentSizeForUnix -# undef kwsysSystem_Shell_Flag_e -# undef kwsysSystem_Shell_Flag_Make -# undef kwsysSystem_Shell_Flag_VSIDE -# undef kwsysSystem_Shell_Flag_EchoWindows -# undef kwsysSystem_Shell_Flag_WatcomWMake -# undef kwsysSystem_Shell_Flag_MinGWMake -# undef kwsysSystem_Shell_Flag_NMake -# undef kwsysSystem_Shell_Flag_AllowMakeVariables +# if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# undef kwsysSystem_Shell_GetArgumentForWindows +# undef kwsysSystem_Shell_GetArgumentForUnix +# undef kwsysSystem_Shell_GetArgumentSizeForWindows +# undef kwsysSystem_Shell_GetArgumentSizeForUnix +# undef kwsysSystem_Shell_Flag_e +# undef kwsysSystem_Shell_Flag_Make +# undef kwsysSystem_Shell_Flag_VSIDE +# undef kwsysSystem_Shell_Flag_EchoWindows +# undef kwsysSystem_Shell_Flag_WatcomWMake +# undef kwsysSystem_Shell_Flag_MinGWMake +# undef kwsysSystem_Shell_Flag_NMake +# undef kwsysSystem_Shell_Flag_AllowMakeVariables +# endif #endif #endif diff --git a/Utilities/ITK/Utilities/kwsys/SystemInformation.cxx b/Utilities/ITK/Utilities/kwsys/SystemInformation.cxx old mode 100755 new mode 100644 index 2f1a7c9561..191250674d --- a/Utilities/ITK/Utilities/kwsys/SystemInformation.cxx +++ b/Utilities/ITK/Utilities/kwsys/SystemInformation.cxx @@ -3,8 +3,8 @@ Program: BatchMake Module: $RCSfile: SystemInformation.cxx,v $ Language: C++ - Date: $Date: 2009-02-12 15:08:15 $ - Version: $Revision: 1.38 $ + Date: $Date: 2009-05-20 13:50:20 $ + Version: $Revision: 1.45 $ Copyright (c) 2005 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -49,6 +49,14 @@ # include <windows.h> #endif +#ifdef __APPLE__ +#include <sys/sysctl.h> +#include <mach/vm_statistics.h> +#include <mach/host_info.h> +#include <mach/mach.h> +#include <mach/mach_types.h> +#endif + #ifdef __linux # include <sys/procfs.h> # include <sys/types.h> @@ -104,7 +112,7 @@ public: const char * GetExtendedProcessorName(); const char * GetProcessorSerialNumber(); int GetProcessorCacheSize(); - int GetLogicalProcessorsPerPhysical(); + unsigned int GetLogicalProcessorsPerPhysical(); float GetProcessorClockFrequency(); int GetProcessorAPICID(); int GetProcessorCacheXSize(long int); @@ -166,7 +174,7 @@ public: bool HasMMXPlus; bool HasSSEMMX; bool SupportsHyperthreading; - int LogicalProcessorsPerPhysical; + unsigned int LogicalProcessorsPerPhysical; int APIC_ID; CPUPowerManagement PowerManagement; } CPUExtendedFeatures; @@ -195,7 +203,7 @@ public: enum Manufacturer { - AMD, Intel, NSC, UMC, Cyrix, NexGen, IDT, Rise, Transmeta, Sun, UnknownManufacturer + AMD, Intel, NSC, UMC, Cyrix, NexGen, IDT, Rise, Transmeta, Sun, IBM, Motorola, UnknownManufacturer }; protected: @@ -317,7 +325,7 @@ int SystemInformation::GetProcessorCacheSize() { return this->Implementation->GetProcessorCacheSize(); } -int SystemInformation::GetLogicalProcessorsPerPhysical() +unsigned int SystemInformation::GetLogicalProcessorsPerPhysical() { return this->Implementation->GetLogicalProcessorsPerPhysical(); } @@ -629,6 +637,10 @@ const char * SystemInformationImplementation::GetVendorID() return "Transmeta"; case Sun: return "Sun Microelectronics"; + case IBM: + return "IBM"; + case Motorola: + return "Motorola"; default: return "Unknown Manufacturer"; } @@ -680,7 +692,7 @@ const char * SystemInformationImplementation::GetProcessorSerialNumber() } /** Return the logical processors per physical */ -int SystemInformationImplementation::GetLogicalProcessorsPerPhysical() +unsigned int SystemInformationImplementation::GetLogicalProcessorsPerPhysical() { return this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical; } @@ -968,7 +980,9 @@ void SystemInformationImplementation::FindManufacturer() else if (strcmp (this->ChipID.Vendor, "GenuineTMx86") == 0) this->ChipManufacturer = Transmeta; // Transmeta else if (strcmp (this->ChipID.Vendor, "TransmetaCPU") == 0) this->ChipManufacturer = Transmeta; // Transmeta else if (strcmp (this->ChipID.Vendor, "Geode By NSC") == 0) this->ChipManufacturer = NSC; // National Semiconductor - else if (strcmp (this->ChipID.Vendor, "Sun") == 0) this->ChipManufacturer = Sun; // Sun Microelectronics + else if (strcmp (this->ChipID.Vendor, "Sun") == 0) this->ChipManufacturer = Sun; // Sun Microelectronics + else if (strcmp (this->ChipID.Vendor, "IBM") == 0) this->ChipManufacturer = IBM; // IBM Microelectronics + else if (strcmp (this->ChipID.Vendor, "Motorola") == 0) this->ChipManufacturer = Motorola; // Motorola Microelectronics else this->ChipManufacturer = UnknownManufacturer; // Unknown manufacturer } @@ -1563,7 +1577,7 @@ bool SystemInformationImplementation::RetrieveExtendedCPUFeatures() } // Check to see if what we are about to do is supported... - if (!RetrieveCPUExtendedLevelSupport (0x80000001)) + if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000001))) { return false; } @@ -1698,7 +1712,7 @@ bool SystemInformationImplementation::RetrieveProcessorSerialNumber() bool SystemInformationImplementation::RetrieveCPUPowerManagement() { // Check to see if what we are about to do is supported... - if (!RetrieveCPUExtendedLevelSupport (0x80000007)) + if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000007))) { this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID = false; this->Features.ExtendedFeatures.PowerManagement.HasVoltageID = false; @@ -1755,9 +1769,12 @@ bool SystemInformationImplementation::RetrieveCPUPowerManagement() bool SystemInformationImplementation::RetrieveExtendedCPUIdentity() { // Check to see if what we are about to do is supported... - if (!RetrieveCPUExtendedLevelSupport(0x80000002)) return false; - if (!RetrieveCPUExtendedLevelSupport(0x80000003)) return false; - if (!RetrieveCPUExtendedLevelSupport(0x80000004)) return false; + if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000002))) + return false; + if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000003))) + return false; + if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000004))) + return false; #if USE_ASM_INSTRUCTIONS int ProcessorNameStartPos = 0; @@ -1910,6 +1927,7 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() case 8: sprintf (this->ChipID.ProcessorName,"Pentium III (0.18 micron) With 256 KB On-Die L2 Cache "); break; case 0xa: sprintf (this->ChipID.ProcessorName,"Pentium III (0.18 micron) With 1 Or 2 MB On-Die L2 Cache "); break; case 0xb: sprintf (this->ChipID.ProcessorName,"Pentium III (0.13 micron) With 256 Or 512 KB On-Die L2 Cache "); break; + case 23: sprintf (this->ChipID.ProcessorName, "Intel(R) Core(TM)2 Duo CPU T9500 @ 2.60GHz"); break; default: sprintf (this->ChipID.ProcessorName,"Unknown P6 family"); return false; } break; @@ -2169,7 +2187,7 @@ int SystemInformationImplementation::RetreiveInformationFromCpuInfoFile() size_t fileSize = 0; while(!feof(fd)) { - buffer += static_cast<unsigned char>(fgetc(fd)); + buffer += static_cast<char>(fgetc(fd)); fileSize++; } fclose( fd ); @@ -2204,7 +2222,8 @@ int SystemInformationImplementation::RetreiveInformationFromCpuInfoFile() kwsys_stl::string cores = this->ExtractValueFromCpuInfoFile(buffer,"cpu cores"); int numberOfCoresPerCPU=atoi(cores.c_str()); - this->NumberOfPhysicalCPU=numberOfCoresPerCPU*(maxId+1); + this->NumberOfPhysicalCPU=static_cast<unsigned int>( + numberOfCoresPerCPU*(maxId+1)); #else // __CYGWIN__ // does not have "physical id" entries, neither "cpu cores" @@ -2222,7 +2241,7 @@ int SystemInformationImplementation::RetreiveInformationFromCpuInfoFile() } // LogicalProcessorsPerPhysical>1 => hyperthreading. this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical= - this->NumberOfLogicalCPU/this->NumberOfPhysicalCPU; + this->NumberOfLogicalCPU/this->NumberOfPhysicalCPU; // CPU speed (checking only the first proc kwsys_stl::string CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"cpu MHz"); @@ -2284,7 +2303,7 @@ int SystemInformationImplementation::QueryMemory() unsigned long av=0; unsigned long ap=0; - char buffer[1024]; // for skipping unused lines + char buffer[1024]; // for reading lines int linuxMajor = 0; int linuxMinor = 0; @@ -2327,34 +2346,39 @@ int SystemInformationImplementation::QueryMemory() // new /proc/meminfo format since kernel 2.6.x // Rigorously, this test should check from the developping version 2.5.x // that introduced the new format... - - long freeMem; - long buffersMem; - long cachedMem; - - fscanf(fd,"MemTotal:%ld kB\n", &this->TotalPhysicalMemory); - fscanf(fd,"MemFree:%ld kB\n", &freeMem); - fscanf(fd,"Buffers:%ld kB\n", &buffersMem); - fscanf(fd,"Cached:%ld kB\n", &cachedMem); - - this->TotalPhysicalMemory /= 1024; - this->AvailablePhysicalMemory = freeMem+cachedMem+buffersMem; - this->AvailablePhysicalMemory /= 1024; - - // Skip SwapCached, Active, Inactive, HighTotal, HighFree, LowTotal - // and LowFree. - int i=0; - while(i<7) + + enum { mMemTotal, mMemFree, mBuffers, mCached, mSwapTotal, mSwapFree }; + const char* format[6] = + { "MemTotal:%lu kB", "MemFree:%lu kB", "Buffers:%lu kB", + "Cached:%lu kB", "SwapTotal:%lu kB", "SwapFree:%lu kB" }; + bool have[6] = { false, false, false, false, false, false }; + unsigned long value[6]; + int count = 0; + while(fgets(buffer, sizeof(buffer), fd)) { - fgets(buffer, sizeof(buffer), fd); // skip a line - ++i; + for(int i=0; i < 6; ++i) + { + if(!have[i] && sscanf(buffer, format[i], &value[i]) == 1) + { + have[i] = true; + ++count; + } + } + } + if(count == 6) + { + this->TotalPhysicalMemory = value[mMemTotal] / 1024; + this->AvailablePhysicalMemory = + (value[mMemFree] + value[mBuffers] + value[mCached]) / 1024; + this->TotalVirtualMemory = value[mSwapTotal] / 1024; + this->AvailableVirtualMemory = value[mSwapFree] / 1024; + } + else + { + kwsys_ios::cout << "Problem parsing /proc/meminfo" << kwsys_ios::endl; + fclose(fd); + return 0; } - - fscanf(fd,"SwapTotal:%ld kB\n", &this->TotalVirtualMemory); - fscanf(fd,"SwapFree:%ld kB\n", &this->AvailableVirtualMemory); - - this->TotalVirtualMemory /= 1024; - this->AvailableVirtualMemory /= 1024; } else { @@ -2363,16 +2387,30 @@ int SystemInformationImplementation::QueryMemory() unsigned long temp; unsigned long cachedMem; unsigned long buffersMem; - fgets(buffer, sizeof(buffer), fd); // Skip "total: used:..." - - fscanf(fd, "Mem: %lu %lu %lu %lu %lu %lu\n", - &tp, &temp, &ap, &temp, &buffersMem, &cachedMem); - fscanf(fd, "Swap: %lu %lu %lu\n", &tv, &temp, &av); - - this->TotalVirtualMemory = tv>>10>>10; - this->TotalPhysicalMemory = tp>>10>>10; - this->AvailableVirtualMemory = av>>10>>10; - this->AvailablePhysicalMemory = (ap+buffersMem+cachedMem)>>10>>10; + char *r=fgets(buffer, sizeof(buffer), fd); // Skip "total: used:..." + int status=0; + if(r==buffer) + { + status+=fscanf(fd, "Mem: %lu %lu %lu %lu %lu %lu\n", + &tp, &temp, &ap, &temp, &buffersMem, &cachedMem); + } + if(status==6) + { + status+=fscanf(fd, "Swap: %lu %lu %lu\n", &tv, &temp, &av); + } + if(status==9) + { + this->TotalVirtualMemory = tv>>10>>10; + this->TotalPhysicalMemory = tp>>10>>10; + this->AvailableVirtualMemory = av>>10>>10; + this->AvailablePhysicalMemory = (ap+buffersMem+cachedMem)>>10>>10; + } + else + { + kwsys_ios::cout << "Problem parsing /proc/meminfo" << kwsys_ios::endl; + fclose(fd); + return 0; + } } fclose( fd ); return 1; @@ -2520,6 +2558,20 @@ unsigned char SystemInformationImplementation::LogicalCPUPerPhysicalCPU(void) mov Regebx, ebx } #endif + +#ifdef __APPLE__ + size_t len = 4; + int cores_per_package = 0; + int err = sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package, &len, NULL, 0); + if (err != 0) + { + return 1; // That name was not found, default to 1 + } + else + { + return static_cast<unsigned char>(cores_per_package); + } +#endif return static_cast<unsigned char> ((Regebx & NUM_LOGICAL_BITS) >> 16); } @@ -2713,50 +2765,115 @@ unsigned int SystemInformationImplementation::GetNumberOfPhysicalCPU() return this->NumberOfPhysicalCPU; } -/** For Mac we Parse the sysctl -a output */ +/** For Mac use sysctlbyname calls to find system info */ bool SystemInformationImplementation::ParseSysCtl() { - // Extract the arguments from the command line - kwsys_stl::vector<const char*> args; - args.push_back("sysctl"); - args.push_back("-a"); - args.push_back(0); +#if defined(__APPLE__) + int err = 0; + uint64_t value = 0; + size_t len = sizeof(value); + sysctlbyname("hw.memsize", &value, &len, NULL, 0); + this->TotalPhysicalMemory = value/1048576; - this->SysCtlBuffer = this->RunProcess(args); - // Parse values for Mac - this->TotalPhysicalMemory = atoi(this->ExtractValueFromSysCtl("hw.memsize:").c_str())/(1024*1024); - this->TotalVirtualMemory = 0; this->AvailablePhysicalMemory = 0; - this->AvailableVirtualMemory = 0; + vm_statistics_data_t vmstat; + mach_msg_type_number_t count = HOST_VM_INFO_COUNT; + if ( host_statistics(mach_host_self(), HOST_VM_INFO, + (host_info_t) &vmstat, &count) == KERN_SUCCESS ) + { + err = sysctlbyname("hw.pagesize", &value, &len, NULL, 0); + int64_t available_memory = vmstat.free_count * value; + this->AvailablePhysicalMemory = available_memory / 1048576; + } - this->NumberOfPhysicalCPU = atoi(this->ExtractValueFromSysCtl("hw.physicalcpu:").c_str()); - this->NumberOfLogicalCPU = atoi(this->ExtractValueFromSysCtl("hw.logicalcpu:").c_str()); - - if(this->NumberOfPhysicalCPU!=0) +#ifdef VM_SWAPUSAGE + // Virtual memory. + int mib[2] = { CTL_VM, VM_SWAPUSAGE }; + size_t miblen = sizeof(mib) / sizeof(mib[0]); + struct xsw_usage swap; + len = sizeof(struct xsw_usage); + err = sysctl(mib, miblen, &swap, &len, NULL, 0); + if (err == 0) { - this->NumberOfLogicalCPU /= this->NumberOfPhysicalCPU; + this->AvailableVirtualMemory = swap.xsu_avail/1048576; + this->TotalVirtualMemory = swap.xsu_total/1048576; } +#else + this->AvailableVirtualMemory = 0; + this->TotalVirtualMemory = 0; +#endif + +// CPU Info + len = sizeof(this->NumberOfPhysicalCPU); + sysctlbyname("hw.physicalcpu", &this->NumberOfPhysicalCPU, &len, NULL, 0); + sysctlbyname("hw.logicalcpu", &this->NumberOfLogicalCPU, &len, NULL, 0); + this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical = + this->LogicalCPUPerPhysicalCPU(); + + len = sizeof(value); + sysctlbyname("hw.cpufrequency", &value, &len, NULL, 0); + this->CPUSpeedInMHz = value / 1048576; - this->CPUSpeedInMHz = static_cast<float>(atoi(this->ExtractValueFromSysCtl("hw.cpufrequency:").c_str())); - this->CPUSpeedInMHz /= 1000000; // Chip family - this->ChipID.Family = atoi(this->ExtractValueFromSysCtl("machdep.cpu.family:").c_str()); - - // Chip Vendor - strcpy(this->ChipID.Vendor,this->ExtractValueFromSysCtl("machdep.cpu.vendor:").c_str()); - this->FindManufacturer(); - - // Chip Model - this->ChipID.Model = atoi(this->ExtractValueFromSysCtl("machdep.cpu.model:").c_str()); - this->RetrieveClassicalCPUIdentity(); + len = sizeof(this->ChipID.Family); + //Seems only the intel chips will have this name so if this fails it is + //probably a PPC machine + err = sysctlbyname("machdep.cpu.family", + &this->ChipID.Family, &len, NULL, 0); + if (err != 0) // Go back to names we know but are less descriptive + { + this->ChipID.Family = 0; + char retBuf[32]; + ::memset(retBuf, 0, 32); + len = 32; + err = sysctlbyname("hw.machine", &retBuf, &len, NULL, 0); + kwsys_stl::string machineBuf(retBuf); + if (machineBuf.find_first_of("Power") != kwsys_stl::string::npos) + { + strcpy(this->ChipID.Vendor, "IBM"); + len = 4; + err = sysctlbyname("hw.cputype", &this->ChipID.Family, &len, NULL, 0); + err = sysctlbyname("hw.cpusubtype", &this->ChipID.Model, &len, NULL, 0); + this->FindManufacturer(); + } + } + else // Should be an Intel Chip. + { + len = sizeof(this->ChipID.Family); + err = + sysctlbyname("machdep.cpu.family", &this->ChipID.Family, &len, NULL, 0); + + char retBuf[128]; + ::memset(retBuf, 0, 128); + len = 128; + err = sysctlbyname("machdep.cpu.vendor", retBuf, &len, NULL, 0); + // Chip Vendor + strcpy(this->ChipID.Vendor,retBuf); + this->FindManufacturer(); + + len=CHIPNAME_STRING_LENGTH; + err = + sysctlbyname("machdep.cpu.brand_string", + this->ChipID.ProcessorName, &len, NULL, 0); + // Chip Model + len = sizeof(value); + err = sysctlbyname("machdep.cpu.model", &value, &len, NULL, 0); + this->ChipID.Model = value; + } // Cache size - this->Features.L1CacheSize = atoi(this->ExtractValueFromSysCtl("hw.l1icachesize:").c_str()); - this->Features.L2CacheSize = atoi(this->ExtractValueFromSysCtl("hw.l2cachesize:").c_str()); - + len = sizeof(value); + err = sysctlbyname("hw.l1icachesize", &value, &len, NULL, 0); + this->Features.L1CacheSize = value; + err = sysctlbyname("hw.l2cachesize", &value, &len, NULL, 0); + this->Features.L2CacheSize = value; + return true; +#else + return false; +#endif } /** Extract a value from sysctl command */ @@ -2908,7 +3025,8 @@ kwsys_stl::string SystemInformationImplementation::ParseValueFromKStat(const cha bool SystemInformationImplementation::QuerySolarisInfo() { // Parse values - this->NumberOfPhysicalCPU = atoi(this->ParseValueFromKStat("-n syste_misc -s ncpus").c_str()); + this->NumberOfPhysicalCPU = static_cast<unsigned int>( + atoi(this->ParseValueFromKStat("-n syste_misc -s ncpus").c_str())); this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU; if(this->NumberOfPhysicalCPU!=0) diff --git a/Utilities/ITK/Utilities/kwsys/SystemInformation.hxx.in b/Utilities/ITK/Utilities/kwsys/SystemInformation.hxx.in old mode 100755 new mode 100644 index 282fadae67..b56a01f0e2 --- a/Utilities/ITK/Utilities/kwsys/SystemInformation.hxx.in +++ b/Utilities/ITK/Utilities/kwsys/SystemInformation.hxx.in @@ -3,8 +3,8 @@ Program: KWSys - Kitware System Library Module: $RCSfile: SystemInformation.hxx.in,v $ Language: C++ - Date: $Date: 2008-03-11 21:37:17 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-03-20 02:48:05 $ + Version: $Revision: 1.9 $ Copyright (c) 2005 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,7 +47,7 @@ public: const char * GetExtendedProcessorName(); const char * GetProcessorSerialNumber(); int GetProcessorCacheSize(); - int GetLogicalProcessorsPerPhysical(); + unsigned int GetLogicalProcessorsPerPhysical(); float GetProcessorClockFrequency(); int GetProcessorAPICID(); int GetProcessorCacheXSize(long int); diff --git a/Utilities/ITK/Utilities/kwsys/SystemTools.cxx b/Utilities/ITK/Utilities/kwsys/SystemTools.cxx index 27b47e7a0b..0135df63af 100644 --- a/Utilities/ITK/Utilities/kwsys/SystemTools.cxx +++ b/Utilities/ITK/Utilities/kwsys/SystemTools.cxx @@ -53,12 +53,14 @@ #ifndef _WIN32 #include <utime.h> #include <limits.h> -#include <sys/param.h> #include <sys/wait.h> #include <sys/ioctl.h> #include <unistd.h> #include <pwd.h> +#ifndef __VMS +#include <sys/param.h> #include <termios.h> +#endif #include <signal.h> /* sigprocmask */ #endif @@ -311,11 +313,11 @@ SystemTools::GetTime(void) struct timeval t; #ifdef GETTIMEOFDAY_NO_TZ if (gettimeofday(&t) == 0) - return static_cast<double>(t.tv_sec) + t.tv_usec*0.000001; #else /* !GETTIMEOFDAY_NO_TZ */ if (gettimeofday(&t, static_cast<struct timezone *>(NULL)) == 0) - return static_cast<double>(t.tv_sec) + t.tv_usec*0.000001; #endif /* !GETTIMEOFDAY_NO_TZ */ + return static_cast<double>(t.tv_sec) + + static_cast<double>(t.tv_usec)*0.000001; } #endif /* !HAVE_GETTIMEOFDAY */ { @@ -1660,7 +1662,7 @@ bool SystemTools::CopyFileIfDifferent(const char* source, #define KWSYS_ST_BUFFER 4096 bool SystemTools::FilesDiffer(const char* source, - const char* destination) + const char* destination) { struct stat statSource; if (stat(source, &statSource) != 0) @@ -1715,10 +1717,11 @@ bool SystemTools::FilesDiffer(const char* source, { return true; } - + // If this block differs the file differs. if(memcmp(static_cast<const void*>(source_buf), - static_cast<const void*>(dest_buf), nnext) != 0) + static_cast<const void*>(dest_buf), + static_cast<size_t>(nnext)) != 0) { return true; } @@ -1999,7 +2002,7 @@ bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt) return false; } - int month = (ptr - month_names) / 3; + int month = static_cast<int>((ptr - month_names) / 3); int day = atoi(buffer + 4); int year = atoi(buffer + 7); @@ -2050,7 +2053,7 @@ bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt) return false; } - int month = (ptr - month_names) / 3; + int month = static_cast<int>((ptr - month_names) / 3); int day = atoi(buffer + 8); int hour = atoi(buffer + 11); int min = atoi(buffer + 14); @@ -2100,6 +2103,19 @@ bool SystemTools::RemoveFile(const char* source) bool SystemTools::RemoveADirectory(const char* source) { + // Add write permission to the directory so we can modify its + // content to remove files and directories from it. + mode_t mode; + if(SystemTools::GetPermissions(source, mode)) + { +#if defined(_WIN32) && !defined(__CYGWIN__) + mode |= S_IWRITE; +#else + mode |= S_IWUSR; +#endif + SystemTools::SetPermissions(source, mode); + } + Directory dir; dir.Load(source); size_t fileNum; @@ -2495,7 +2511,7 @@ bool SystemTools::FileIsDirectory(const char* name) { // Remove any trailing slash from the name. char buffer[KWSYS_SYSTEMTOOLS_MAXPATH]; - int last = static_cast<int>(strlen(name))-1; + size_t last = strlen(name)-1; if(last > 0 && (name[last] == '/' || name[last] == '\\') && strcmp(name, "/") !=0) { @@ -3130,7 +3146,7 @@ const char* SystemTools::SplitPathRootComponent(const char* p, // "~u" : root = "~u/", return "" // "~u/" : root = "~u/", return "" // "~u/x" : root = "~u/", return "x" - int n = 1; + size_t n = 1; while(c[n] && c[n] != '/') { ++n; @@ -3221,7 +3237,9 @@ void SystemTools::SplitPath(const char* p, if(*last == '/' || *last == '\\') { // End of a component. Save it. - components.push_back(kwsys_stl::string(first, last-first)); + components.push_back( + kwsys_stl::string(first,static_cast<kwsys_stl::string::size_type>( + last-first))); first = last+1; } } @@ -3229,7 +3247,9 @@ void SystemTools::SplitPath(const char* p, // Save the last component unless there were no components. if(last != c) { - components.push_back(kwsys_stl::string(first, last-first)); + components.push_back( + kwsys_stl::string(first,static_cast<kwsys_stl::string::size_type>( + last-first))); } } @@ -3970,29 +3990,15 @@ bool SystemTools::SetPermissions(const char* file, mode_t mode) kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir) { - if ( !fileOrDir || !*fileOrDir ) - { - return ""; - } - kwsys_stl::string res = fileOrDir; - SystemTools::ConvertToUnixSlashes(res); - kwsys_stl::string::size_type cc = res.size()-1; - if ( res[cc] == '/' ) - { - cc --; - } - for ( ; cc > 0; cc -- ) - { - if ( res[cc] == '/' ) - { - break; - } - } - return res.substr(0, cc); + return SystemTools::GetFilenamePath(fileOrDir); } bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir) { + if(!*cDir) + { + return false; + } kwsys_stl::string subdir = cSubdir; kwsys_stl::string dir = cDir; SystemTools::ConvertToUnixSlashes(dir); @@ -4009,29 +4015,6 @@ bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir) return false; } -kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname, - const char* directory, const char* toplevel) -{ - kwsys_stl::string file = fname; - SystemTools::ConvertToUnixSlashes(file); - kwsys_stl::string dir = directory; - SystemTools::ConvertToUnixSlashes(dir); - while ( !dir.empty() ) - { - kwsys_stl::string path = dir + "/" + file; - if ( SystemTools::FileExists(path.c_str()) ) - { - return path; - } - if ( dir.size() < strlen(toplevel) ) - { - break; - } - dir = SystemTools::GetParentDirectory(dir.c_str()); - } - return ""; -} - void SystemTools::Delay(unsigned int msec) { #ifdef _WIN32 diff --git a/Utilities/ITK/Utilities/kwsys/SystemTools.hxx.in b/Utilities/ITK/Utilities/kwsys/SystemTools.hxx.in index c64ddd5ac1..6527c21fb6 100644 --- a/Utilities/ITK/Utilities/kwsys/SystemTools.hxx.in +++ b/Utilities/ITK/Utilities/kwsys/SystemTools.hxx.in @@ -659,14 +659,6 @@ public: const char *dir, kwsys_stl::string& filename_found, int try_filename_dirs = 0); - - /** - * Check if the given file exists in one of the parent directory of the - * given file or directory and if it does, return the name of the file. - * Toplevel specifies the top-most directory to where it will look. - */ - static kwsys_stl::string FileExistsInParentDirectories(const char* fname, - const char* directory, const char* toplevel); /** compute the relative path from local to remote. local must be a directory. remote can be a file or a directory. diff --git a/Utilities/ITK/Utilities/kwsys/Terminal.c b/Utilities/ITK/Utilities/kwsys/Terminal.c index 77ea47f58c..421962c226 100644 --- a/Utilities/ITK/Utilities/kwsys/Terminal.c +++ b/Utilities/ITK/Utilities/kwsys/Terminal.c @@ -158,6 +158,7 @@ static const char* kwsysTerminalVT100Names[] = "mlterm", "putty", "rxvt", + "rxvt-256color", "rxvt-cygwin", "rxvt-cygwin-native", "rxvt-unicode", diff --git a/Utilities/ITK/Utilities/kwsys/Terminal.h.in b/Utilities/ITK/Utilities/kwsys/Terminal.h.in index a0b5a38c31..3b0f9247db 100644 --- a/Utilities/ITK/Utilities/kwsys/Terminal.h.in +++ b/Utilities/ITK/Utilities/kwsys/Terminal.h.in @@ -26,32 +26,34 @@ # define kwsys_ns(x) @KWSYS_NAMESPACE@##x # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif -#define kwsysTerminal_cfprintf kwsys_ns(Terminal_cfprintf) -#define kwsysTerminal_Color_e kwsys_ns(Terminal_Color_e) -#define kwsysTerminal_Color_Normal kwsys_ns(Terminal_Color_Normal) -#define kwsysTerminal_Color_ForegroundBlack kwsys_ns(Terminal_Color_ForegroundBlack) -#define kwsysTerminal_Color_ForegroundRed kwsys_ns(Terminal_Color_ForegroundRed) -#define kwsysTerminal_Color_ForegroundGreen kwsys_ns(Terminal_Color_ForegroundGreen) -#define kwsysTerminal_Color_ForegroundYellow kwsys_ns(Terminal_Color_ForegroundYellow) -#define kwsysTerminal_Color_ForegroundBlue kwsys_ns(Terminal_Color_ForegroundBlue) -#define kwsysTerminal_Color_ForegroundMagenta kwsys_ns(Terminal_Color_ForegroundMagenta) -#define kwsysTerminal_Color_ForegroundCyan kwsys_ns(Terminal_Color_ForegroundCyan) -#define kwsysTerminal_Color_ForegroundWhite kwsys_ns(Terminal_Color_ForegroundWhite) -#define kwsysTerminal_Color_ForegroundMask kwsys_ns(Terminal_Color_ForegroundMask) -#define kwsysTerminal_Color_BackgroundBlack kwsys_ns(Terminal_Color_BackgroundBlack) -#define kwsysTerminal_Color_BackgroundRed kwsys_ns(Terminal_Color_BackgroundRed) -#define kwsysTerminal_Color_BackgroundGreen kwsys_ns(Terminal_Color_BackgroundGreen) -#define kwsysTerminal_Color_BackgroundYellow kwsys_ns(Terminal_Color_BackgroundYellow) -#define kwsysTerminal_Color_BackgroundBlue kwsys_ns(Terminal_Color_BackgroundBlue) -#define kwsysTerminal_Color_BackgroundMagenta kwsys_ns(Terminal_Color_BackgroundMagenta) -#define kwsysTerminal_Color_BackgroundCyan kwsys_ns(Terminal_Color_BackgroundCyan) -#define kwsysTerminal_Color_BackgroundWhite kwsys_ns(Terminal_Color_BackgroundWhite) -#define kwsysTerminal_Color_BackgroundMask kwsys_ns(Terminal_Color_BackgroundMask) -#define kwsysTerminal_Color_ForegroundBold kwsys_ns(Terminal_Color_ForegroundBold) -#define kwsysTerminal_Color_BackgroundBold kwsys_ns(Terminal_Color_BackgroundBold) -#define kwsysTerminal_Color_AssumeTTY kwsys_ns(Terminal_Color_AssumeTTY) -#define kwsysTerminal_Color_AssumeVT100 kwsys_ns(Terminal_Color_AssumeVT100) -#define kwsysTerminal_Color_AttributeMask kwsys_ns(Terminal_Color_AttributeMask) +#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# define kwsysTerminal_cfprintf kwsys_ns(Terminal_cfprintf) +# define kwsysTerminal_Color_e kwsys_ns(Terminal_Color_e) +# define kwsysTerminal_Color_Normal kwsys_ns(Terminal_Color_Normal) +# define kwsysTerminal_Color_ForegroundBlack kwsys_ns(Terminal_Color_ForegroundBlack) +# define kwsysTerminal_Color_ForegroundRed kwsys_ns(Terminal_Color_ForegroundRed) +# define kwsysTerminal_Color_ForegroundGreen kwsys_ns(Terminal_Color_ForegroundGreen) +# define kwsysTerminal_Color_ForegroundYellow kwsys_ns(Terminal_Color_ForegroundYellow) +# define kwsysTerminal_Color_ForegroundBlue kwsys_ns(Terminal_Color_ForegroundBlue) +# define kwsysTerminal_Color_ForegroundMagenta kwsys_ns(Terminal_Color_ForegroundMagenta) +# define kwsysTerminal_Color_ForegroundCyan kwsys_ns(Terminal_Color_ForegroundCyan) +# define kwsysTerminal_Color_ForegroundWhite kwsys_ns(Terminal_Color_ForegroundWhite) +# define kwsysTerminal_Color_ForegroundMask kwsys_ns(Terminal_Color_ForegroundMask) +# define kwsysTerminal_Color_BackgroundBlack kwsys_ns(Terminal_Color_BackgroundBlack) +# define kwsysTerminal_Color_BackgroundRed kwsys_ns(Terminal_Color_BackgroundRed) +# define kwsysTerminal_Color_BackgroundGreen kwsys_ns(Terminal_Color_BackgroundGreen) +# define kwsysTerminal_Color_BackgroundYellow kwsys_ns(Terminal_Color_BackgroundYellow) +# define kwsysTerminal_Color_BackgroundBlue kwsys_ns(Terminal_Color_BackgroundBlue) +# define kwsysTerminal_Color_BackgroundMagenta kwsys_ns(Terminal_Color_BackgroundMagenta) +# define kwsysTerminal_Color_BackgroundCyan kwsys_ns(Terminal_Color_BackgroundCyan) +# define kwsysTerminal_Color_BackgroundWhite kwsys_ns(Terminal_Color_BackgroundWhite) +# define kwsysTerminal_Color_BackgroundMask kwsys_ns(Terminal_Color_BackgroundMask) +# define kwsysTerminal_Color_ForegroundBold kwsys_ns(Terminal_Color_ForegroundBold) +# define kwsysTerminal_Color_BackgroundBold kwsys_ns(Terminal_Color_BackgroundBold) +# define kwsysTerminal_Color_AssumeTTY kwsys_ns(Terminal_Color_AssumeTTY) +# define kwsysTerminal_Color_AssumeVT100 kwsys_ns(Terminal_Color_AssumeVT100) +# define kwsysTerminal_Color_AttributeMask kwsys_ns(Terminal_Color_AttributeMask) +#endif #if defined(__cplusplus) extern "C" @@ -126,32 +128,34 @@ enum kwsysTerminal_Color_e #if !defined(KWSYS_NAMESPACE) # undef kwsys_ns # undef kwsysEXPORT -# undef kwsysTerminal_cfprintf -# undef kwsysTerminal_Color_e -# undef kwsysTerminal_Color_Normal -# undef kwsysTerminal_Color_ForegroundBlack -# undef kwsysTerminal_Color_ForegroundRed -# undef kwsysTerminal_Color_ForegroundGreen -# undef kwsysTerminal_Color_ForegroundYellow -# undef kwsysTerminal_Color_ForegroundBlue -# undef kwsysTerminal_Color_ForegroundMagenta -# undef kwsysTerminal_Color_ForegroundCyan -# undef kwsysTerminal_Color_ForegroundWhite -# undef kwsysTerminal_Color_ForegroundMask -# undef kwsysTerminal_Color_BackgroundBlack -# undef kwsysTerminal_Color_BackgroundRed -# undef kwsysTerminal_Color_BackgroundGreen -# undef kwsysTerminal_Color_BackgroundYellow -# undef kwsysTerminal_Color_BackgroundBlue -# undef kwsysTerminal_Color_BackgroundMagenta -# undef kwsysTerminal_Color_BackgroundCyan -# undef kwsysTerminal_Color_BackgroundWhite -# undef kwsysTerminal_Color_BackgroundMask -# undef kwsysTerminal_Color_ForegroundBold -# undef kwsysTerminal_Color_BackgroundBold -# undef kwsysTerminal_Color_AssumeTTY -# undef kwsysTerminal_Color_AssumeVT100 -# undef kwsysTerminal_Color_AttributeMask +# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# undef kwsysTerminal_cfprintf +# undef kwsysTerminal_Color_e +# undef kwsysTerminal_Color_Normal +# undef kwsysTerminal_Color_ForegroundBlack +# undef kwsysTerminal_Color_ForegroundRed +# undef kwsysTerminal_Color_ForegroundGreen +# undef kwsysTerminal_Color_ForegroundYellow +# undef kwsysTerminal_Color_ForegroundBlue +# undef kwsysTerminal_Color_ForegroundMagenta +# undef kwsysTerminal_Color_ForegroundCyan +# undef kwsysTerminal_Color_ForegroundWhite +# undef kwsysTerminal_Color_ForegroundMask +# undef kwsysTerminal_Color_BackgroundBlack +# undef kwsysTerminal_Color_BackgroundRed +# undef kwsysTerminal_Color_BackgroundGreen +# undef kwsysTerminal_Color_BackgroundYellow +# undef kwsysTerminal_Color_BackgroundBlue +# undef kwsysTerminal_Color_BackgroundMagenta +# undef kwsysTerminal_Color_BackgroundCyan +# undef kwsysTerminal_Color_BackgroundWhite +# undef kwsysTerminal_Color_BackgroundMask +# undef kwsysTerminal_Color_ForegroundBold +# undef kwsysTerminal_Color_BackgroundBold +# undef kwsysTerminal_Color_AssumeTTY +# undef kwsysTerminal_Color_AssumeVT100 +# undef kwsysTerminal_Color_AttributeMask +# endif #endif #endif diff --git a/Utilities/ITK/Utilities/kwsys/kwsysDateStamp.cmake b/Utilities/ITK/Utilities/kwsys/kwsysDateStamp.cmake index 8d8284ef88..3d491de89f 100644 --- a/Utilities/ITK/Utilities/kwsys/kwsysDateStamp.cmake +++ b/Utilities/ITK/Utilities/kwsys/kwsysDateStamp.cmake @@ -4,7 +4,7 @@ SET(KWSYS_DATE_STAMP_YEAR 2009) # KWSys version date month component. Format is MM. -SET(KWSYS_DATE_STAMP_MONTH 02) +SET(KWSYS_DATE_STAMP_MONTH 05) # KWSys version date day component. Format is DD. -SET(KWSYS_DATE_STAMP_DAY 28) +SET(KWSYS_DATE_STAMP_DAY 27) diff --git a/Utilities/ITK/Utilities/kwsys/kwsysPrivate.h b/Utilities/ITK/Utilities/kwsys/kwsysPrivate.h index 1b614c9bec..d6b2d47e78 100644 --- a/Utilities/ITK/Utilities/kwsys/kwsysPrivate.h +++ b/Utilities/ITK/Utilities/kwsys/kwsysPrivate.h @@ -22,7 +22,7 @@ Define KWSYS_HEADER macro to help the c and cxx files include kwsys headers from the configured namespace directory. The macro can be used like this: - + #include KWSYS_HEADER(Directory.hxx) #include KWSYS_HEADER(std/vector) */ @@ -39,5 +39,7 @@ #define KWSYS_NAMESPACE_STRING1(x) #x #else -# error "kwsysPrivate.h included multiple times." +# ifndef __VMS /* Avoid strange false positive on VMS compiler. */ +# error "kwsysPrivate.h included multiple times." +# endif #endif diff --git a/Utilities/ITK/Utilities/kwsys/testIOS.cxx b/Utilities/ITK/Utilities/kwsys/testIOS.cxx index e4e0a2d309..5b65d20b5a 100644 --- a/Utilities/ITK/Utilities/kwsys/testIOS.cxx +++ b/Utilities/ITK/Utilities/kwsys/testIOS.cxx @@ -12,15 +12,39 @@ # include "kwsys_ios_iostream.h.in" #endif +#include <string.h> /* strlen */ + int testIOS(int, char*[]) { kwsys_ios::ostringstream ostr; - ostr << "hello"; - if(ostr.str() != "hello") + const char hello[] = "hello"; + ostr << hello; + if(ostr.str() != hello) { kwsys_ios::cerr << "failed to write hello to ostr" << kwsys_ios::endl; return 1; } + const char world[] = "world"; + kwsys_ios::ostringstream ostr2; + ostr2.write( hello, strlen(hello) ); /* I could do sizeof */ + ostr2.put( '\0' ); + ostr2.write( world, strlen(world) ); + if(ostr2.str().size() != strlen(hello) + 1 + strlen(world) ) + { + kwsys_ios::cerr << "failed to write hello to ostr2" << kwsys_ios::endl; + return 1; + } + static const unsigned char array[] = { 0xff,0x4f,0xff,0x51,0x00,0x29,0x00,0x00,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x07,0x01,0x01,0xff,0x52,0x00,0x0c,0x00,0x00,0x00,0x01,0x00,0x05,0x04,0x04,0x00,0x01,0xff,0x5c,0x00,0x13,0x40,0x40,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0xff,0x64,0x00,0x2c,0x00,0x00,0x43,0x72,0x65,0x61,0x74,0x65,0x64,0x20,0x62,0x79,0x20,0x49,0x54,0x4b,0x2f,0x47,0x44,0x43,0x4d,0x2f,0x4f,0x70,0x65,0x6e,0x4a,0x50,0x45,0x47,0x20,0x76,0x65,0x72,0x73,0x69,0x6f,0x6e,0x20,0x31,0x2e,0x30,0xff,0x90,0x00,0x0a,0x00,0x00,0x00,0x00,0x06,0x2c,0x00,0x01,0xff,0x93,0xcf,0xb0,0x18,0x08,0x7f,0xc6,0x99,0xbf,0xff,0xc0,0xf8,0xc1,0xc1,0xf3,0x05,0x81,0xf2,0x83,0x0a,0xa5,0xff,0x10,0x90,0xbf,0x2f,0xff,0x04,0xa8,0x7f,0xc0,0xf8,0xc4,0xc1,0xf3,0x09,0x81,0xf3,0x0c,0x19,0x34 }; + const unsigned int narray = sizeof(array); // 180 + kwsys_ios::stringstream strstr; + strstr.write( (char*)array, narray ); + //strstr.seekp( narray / 2 ); // set position of put pointer in mid string + if(strstr.str().size() != narray ) + { + kwsys_ios::cerr << "failed to write array to strstr" << kwsys_ios::endl; + return 1; + } + kwsys_ios::istringstream istr(" 10 20 str "); kwsys_stl::string s; int x; diff --git a/Utilities/ITK/Utilities/kwsys/testSystemInformation.cxx b/Utilities/ITK/Utilities/kwsys/testSystemInformation.cxx old mode 100755 new mode 100644 index 921f596bc6..061458a4c7 --- a/Utilities/ITK/Utilities/kwsys/testSystemInformation.cxx +++ b/Utilities/ITK/Utilities/kwsys/testSystemInformation.cxx @@ -26,13 +26,21 @@ #define printMethod(inof, m) kwsys_ios::cout << #m << ": " \ << info.m() << "\n" + +#define printMethod2(inof, m, unit) kwsys_ios::cout << #m << ": " \ +<< info.m() << " " << unit << "\n" + int testSystemInformation(int, char*[]) { kwsys::SystemInformation info; - printMethod(info, GetVendorString); info.RunCPUCheck(); info.RunOSCheck(); info.RunMemoryCheck(); + printMethod(info, GetOSName); + printMethod(info, GetHostname); + printMethod(info, GetOSRelease); + printMethod(info, GetOSVersion); + printMethod(info, GetOSPlatform); printMethod(info, GetVendorString); printMethod(info, GetVendorID); printMethod(info, GetTypeID); @@ -40,24 +48,19 @@ int testSystemInformation(int, char*[]) printMethod(info, GetModelID); printMethod(info, GetExtendedProcessorName); printMethod(info, GetProcessorSerialNumber); - printMethod(info, GetProcessorCacheSize); + printMethod2(info, GetProcessorCacheSize, "KB"); printMethod(info, GetLogicalProcessorsPerPhysical); - printMethod(info, GetProcessorClockFrequency); - printMethod(info, GetProcessorAPICID); - printMethod(info, GetOSName); - printMethod(info, GetHostname); - printMethod(info, GetOSRelease); - printMethod(info, GetOSVersion); - printMethod(info, GetOSPlatform); + printMethod2(info, GetProcessorClockFrequency, "MHz"); printMethod(info, Is64Bits); printMethod(info, GetNumberOfLogicalCPU); printMethod(info, GetNumberOfPhysicalCPU); printMethod(info, DoesCPUSupportCPUID); - printMethod(info, GetTotalVirtualMemory); - printMethod(info, GetAvailableVirtualMemory); - printMethod(info, GetTotalPhysicalMemory); - printMethod(info, GetAvailablePhysicalMemory); - + printMethod(info, GetProcessorAPICID); + printMethod2(info, GetTotalVirtualMemory, "MB"); + printMethod2(info, GetAvailableVirtualMemory, "MB"); + printMethod2(info, GetTotalPhysicalMemory, "MB"); + printMethod2(info, GetAvailablePhysicalMemory, "MB"); + //int GetProcessorCacheXSize(long int); // bool DoesCPUSupportFeature(long int); return 0; diff --git a/Utilities/ITK/Utilities/netlib/CMakeLists.txt b/Utilities/ITK/Utilities/netlib/CMakeLists.txt new file mode 100644 index 0000000000..4a28bb3524 --- /dev/null +++ b/Utilities/ITK/Utilities/netlib/CMakeLists.txt @@ -0,0 +1 @@ +ADD_SUBDIRECTORY( slatec ) diff --git a/Utilities/ITK/Utilities/netlib/slatec/.NoDartCoverage b/Utilities/ITK/Utilities/netlib/slatec/.NoDartCoverage new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Utilities/ITK/Utilities/netlib/slatec/CMakeLists.txt b/Utilities/ITK/Utilities/netlib/slatec/CMakeLists.txt new file mode 100644 index 0000000000..16b62d7d0d --- /dev/null +++ b/Utilities/ITK/Utilities/netlib/slatec/CMakeLists.txt @@ -0,0 +1,40 @@ +ADD_LIBRARY( itkNetlibSlatec + # from SLATEC/FNLIB + d1mach.c + d9lgmc.c + d9gmit.c + d9lgic.c + d9lgit.c + dbetai.c + dcsevl.c + dgami.c + dgamit.c + dgamlm.c + dgamma.c + dgamr.c + dlbeta.c + dlgams.c + dlngam.c + dlnrel.c + initds.c + xermsg.c + d_int.c + d_mod.c + ) + +IF(ITK_USE_SYSTEM_VXL) + TARGET_LINK_LIBRARIES( itkNetlibSlatec netlib ) +ELSE(ITK_USE_SYSTEM_VXL) + TARGET_LINK_LIBRARIES( itkNetlibSlatec itkv3p_netlib ) +ENDIF(ITK_USE_SYSTEM_VXL) + +IF(NOT ITK_INSTALL_NO_LIBRARIES) + INSTALL(TARGETS itkNetlibSlatec + RUNTIME DESTINATION ${ITK_INSTALL_BIN_DIR_CM24} COMPONENT RuntimeLibraries + LIBRARY DESTINATION ${ITK_INSTALL_LIB_DIR_CM24} COMPONENT RuntimeLibraries + ARCHIVE DESTINATION ${ITK_INSTALL_LIB_DIR_CM24} COMPONENT Development) +ENDIF(NOT ITK_INSTALL_NO_LIBRARIES) + +IF (BORLAND) + SET (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w-8004 -w-8057") +ENDIF (BORLAND) diff --git a/Utilities/ITK/Utilities/netlib/slatec/README.txt b/Utilities/ITK/Utilities/netlib/slatec/README.txt new file mode 100644 index 0000000000..11757d5f51 --- /dev/null +++ b/Utilities/ITK/Utilities/netlib/slatec/README.txt @@ -0,0 +1,4 @@ +These routines may be obtained from the netlib site at + http://www.netlib.org/slatec/ + +They are used by the probability distributions in the Insight Toolkit diff --git a/Utilities/ITK/Code/Numerics/Statistics/d1mach.c b/Utilities/ITK/Utilities/netlib/slatec/d1mach.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d1mach.c rename to Utilities/ITK/Utilities/netlib/slatec/d1mach.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/d1mach.f b/Utilities/ITK/Utilities/netlib/slatec/d1mach.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d1mach.f rename to Utilities/ITK/Utilities/netlib/slatec/d1mach.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/d9gmit.c b/Utilities/ITK/Utilities/netlib/slatec/d9gmit.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d9gmit.c rename to Utilities/ITK/Utilities/netlib/slatec/d9gmit.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/d9gmit.f b/Utilities/ITK/Utilities/netlib/slatec/d9gmit.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d9gmit.f rename to Utilities/ITK/Utilities/netlib/slatec/d9gmit.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/d9lgic.c b/Utilities/ITK/Utilities/netlib/slatec/d9lgic.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d9lgic.c rename to Utilities/ITK/Utilities/netlib/slatec/d9lgic.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/d9lgic.f b/Utilities/ITK/Utilities/netlib/slatec/d9lgic.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d9lgic.f rename to Utilities/ITK/Utilities/netlib/slatec/d9lgic.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/d9lgit.c b/Utilities/ITK/Utilities/netlib/slatec/d9lgit.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d9lgit.c rename to Utilities/ITK/Utilities/netlib/slatec/d9lgit.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/d9lgit.f b/Utilities/ITK/Utilities/netlib/slatec/d9lgit.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d9lgit.f rename to Utilities/ITK/Utilities/netlib/slatec/d9lgit.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/d9lgmc.c b/Utilities/ITK/Utilities/netlib/slatec/d9lgmc.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d9lgmc.c rename to Utilities/ITK/Utilities/netlib/slatec/d9lgmc.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/d9lgmc.f b/Utilities/ITK/Utilities/netlib/slatec/d9lgmc.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d9lgmc.f rename to Utilities/ITK/Utilities/netlib/slatec/d9lgmc.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/d_int.c b/Utilities/ITK/Utilities/netlib/slatec/d_int.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d_int.c rename to Utilities/ITK/Utilities/netlib/slatec/d_int.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/d_mod.c b/Utilities/ITK/Utilities/netlib/slatec/d_mod.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/d_mod.c rename to Utilities/ITK/Utilities/netlib/slatec/d_mod.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dbetai.c b/Utilities/ITK/Utilities/netlib/slatec/dbetai.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dbetai.c rename to Utilities/ITK/Utilities/netlib/slatec/dbetai.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dbetai.f b/Utilities/ITK/Utilities/netlib/slatec/dbetai.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dbetai.f rename to Utilities/ITK/Utilities/netlib/slatec/dbetai.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dcsevl.c b/Utilities/ITK/Utilities/netlib/slatec/dcsevl.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dcsevl.c rename to Utilities/ITK/Utilities/netlib/slatec/dcsevl.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dcsevl.f b/Utilities/ITK/Utilities/netlib/slatec/dcsevl.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dcsevl.f rename to Utilities/ITK/Utilities/netlib/slatec/dcsevl.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgami.c b/Utilities/ITK/Utilities/netlib/slatec/dgami.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgami.c rename to Utilities/ITK/Utilities/netlib/slatec/dgami.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgami.f b/Utilities/ITK/Utilities/netlib/slatec/dgami.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgami.f rename to Utilities/ITK/Utilities/netlib/slatec/dgami.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgamit.c b/Utilities/ITK/Utilities/netlib/slatec/dgamit.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgamit.c rename to Utilities/ITK/Utilities/netlib/slatec/dgamit.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgamit.f b/Utilities/ITK/Utilities/netlib/slatec/dgamit.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgamit.f rename to Utilities/ITK/Utilities/netlib/slatec/dgamit.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgamlm.c b/Utilities/ITK/Utilities/netlib/slatec/dgamlm.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgamlm.c rename to Utilities/ITK/Utilities/netlib/slatec/dgamlm.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgamlm.f b/Utilities/ITK/Utilities/netlib/slatec/dgamlm.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgamlm.f rename to Utilities/ITK/Utilities/netlib/slatec/dgamlm.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgamma.c b/Utilities/ITK/Utilities/netlib/slatec/dgamma.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgamma.c rename to Utilities/ITK/Utilities/netlib/slatec/dgamma.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgamma.f b/Utilities/ITK/Utilities/netlib/slatec/dgamma.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgamma.f rename to Utilities/ITK/Utilities/netlib/slatec/dgamma.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgamr.c b/Utilities/ITK/Utilities/netlib/slatec/dgamr.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgamr.c rename to Utilities/ITK/Utilities/netlib/slatec/dgamr.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dgamr.f b/Utilities/ITK/Utilities/netlib/slatec/dgamr.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dgamr.f rename to Utilities/ITK/Utilities/netlib/slatec/dgamr.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dlbeta.c b/Utilities/ITK/Utilities/netlib/slatec/dlbeta.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dlbeta.c rename to Utilities/ITK/Utilities/netlib/slatec/dlbeta.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dlbeta.f b/Utilities/ITK/Utilities/netlib/slatec/dlbeta.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dlbeta.f rename to Utilities/ITK/Utilities/netlib/slatec/dlbeta.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dlgams.c b/Utilities/ITK/Utilities/netlib/slatec/dlgams.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dlgams.c rename to Utilities/ITK/Utilities/netlib/slatec/dlgams.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dlgams.f b/Utilities/ITK/Utilities/netlib/slatec/dlgams.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dlgams.f rename to Utilities/ITK/Utilities/netlib/slatec/dlgams.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dlngam.c b/Utilities/ITK/Utilities/netlib/slatec/dlngam.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dlngam.c rename to Utilities/ITK/Utilities/netlib/slatec/dlngam.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dlngam.f b/Utilities/ITK/Utilities/netlib/slatec/dlngam.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dlngam.f rename to Utilities/ITK/Utilities/netlib/slatec/dlngam.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/dlnrel.c b/Utilities/ITK/Utilities/netlib/slatec/dlnrel.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dlnrel.c rename to Utilities/ITK/Utilities/netlib/slatec/dlnrel.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/dlnrel.f b/Utilities/ITK/Utilities/netlib/slatec/dlnrel.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/dlnrel.f rename to Utilities/ITK/Utilities/netlib/slatec/dlnrel.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/initds.c b/Utilities/ITK/Utilities/netlib/slatec/initds.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/initds.c rename to Utilities/ITK/Utilities/netlib/slatec/initds.c diff --git a/Utilities/ITK/Code/Numerics/Statistics/initds.f b/Utilities/ITK/Utilities/netlib/slatec/initds.f similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/initds.f rename to Utilities/ITK/Utilities/netlib/slatec/initds.f diff --git a/Utilities/ITK/Code/Numerics/Statistics/xermsg.c b/Utilities/ITK/Utilities/netlib/slatec/xermsg.c similarity index 100% rename from Utilities/ITK/Code/Numerics/Statistics/xermsg.c rename to Utilities/ITK/Utilities/netlib/slatec/xermsg.c diff --git a/Utilities/ITK/Utilities/vxl/config/cmake/config/CMakeLists.txt b/Utilities/ITK/Utilities/vxl/config/cmake/config/CMakeLists.txt index af14d50a8d..6d382c3db8 100644 --- a/Utilities/ITK/Utilities/vxl/config/cmake/config/CMakeLists.txt +++ b/Utilities/ITK/Utilities/vxl/config/cmake/config/CMakeLists.txt @@ -186,6 +186,30 @@ PERFORM_CHECK_HEADER(ieeefp.h VXL_HAS_IEEEFP_H) PERFORM_CHECK_HEADER(iso646.h VCL_CXX_HAS_HEADER_ISO646_H) PERFORM_CHECK_HEADER(emmintrin.h VXL_HAS_EMMINTRIN_H) +# check for hardware support for sse2 with the current compiler flags +PERFORM_CMAKE_TEST_RUN(vxl_platform_tests.cxx VXL_HAS_SSE2_HARDWARE_SUPPORT) + +# if no support right now, see if the support exists if some flags +# are added. This can be used to give the user some useful info. +IF(NOT VXL_HAS_SSE2_HARDWARE_SUPPORT) + IF(CMAKE_COMPILER_IS_GNUCXX) + SET(VXL_SSE_TEST_FLAG_BACKUP ${CMAKE_REQUIRED_FLAGS}) + SET(CMAKE_REQUIRED_FLAGS " -msse2 ${VXL_SSE_TEST_FLAG_BACKUP} ") + PERFORM_CMAKE_TEST_RUN(vxl_platform_tests.cxx VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE) + SET( VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE_HELP + "The current compiler flags do not allow the SSE2 instructions to be used. " + "It looks like if you add the flag '-msse2' you will be able to use the " + "SSE2 instructions. If you chose to set VNL_CONFIG_ENABLE_SSE or " + "VNL_CONFIG_ENABLE_SSE2_ROUNDING to ON, cmake will put this flag for you. " + "You can also add this flag yourself. If you still see this message, after " + "the flag change, you may need to set VXL_UPDATE_CONFIGURATION to ON and " + "rerun cmake." + CACHE INTERNAL "help string for how to enable SSE2 support" ) + SET(CMAKE_REQUIRED_FLAGS ${VXL_SSE_TEST_FLAG_BACKUP}) + ENDIF(CMAKE_COMPILER_IS_GNUCXX) +ENDIF(NOT VXL_HAS_SSE2_HARDWARE_SUPPORT) + + # # Check for aligned dynamic memory allocation support, useful for sse # @@ -196,16 +220,6 @@ IF(VXL_HAS_EMMINTRIN_H) PERFORM_CMAKE_TEST(vxl_platform_tests.cxx VXL_HAS_ALIGNED_MALLOC) PERFORM_CMAKE_TEST(vxl_platform_tests.cxx VXL_HAS_MINGW_ALIGNED_MALLOC) PERFORM_CMAKE_TEST(vxl_platform_tests.cxx VXL_HAS_POSIX_MEMALIGN) - - # check for hardware support for sse2 - IF(CMAKE_COMPILER_IS_GNUCXX) - SET(VXL_SSE_TEST_FLAG_BACKUP ${CMAKE_REQUIRED_FLAGS}) - SET(CMAKE_REQUIRED_FLAGS " -msse2 ${VXL_SSE_TEST_FLAG_BACKUP} ") - PERFORM_CMAKE_TEST_RUN(vxl_platform_tests.cxx VXL_HAS_SSE2_HARDWARE_SUPPORT) - SET(CMAKE_REQUIRED_FLAGS ${VXL_SSE_TEST_FLAG_BACKUP}) - ELSE(CMAKE_COMPILER_IS_GNUCXX) - PERFORM_CMAKE_TEST_RUN(vxl_platform_tests.cxx VXL_HAS_SSE2_HARDWARE_SUPPORT) - ENDIF(CMAKE_COMPILER_IS_GNUCXX) ELSE(VXL_HAS_EMMINTRIN_H) SET( VXL_HAS_MM_MALLOC 0 ) SET( VXL_HAS_ALIGNED_MALLOC 0 ) diff --git a/Utilities/ITK/Utilities/vxl/config/cmake/config/vxl_platform_tests.cxx b/Utilities/ITK/Utilities/vxl/config/cmake/config/vxl_platform_tests.cxx index 3973cbd350..84df681287 100644 --- a/Utilities/ITK/Utilities/vxl/config/cmake/config/vxl_platform_tests.cxx +++ b/Utilities/ITK/Utilities/vxl/config/cmake/config/vxl_platform_tests.cxx @@ -1174,7 +1174,7 @@ int main() //------------------------------------- -#ifdef VXL_HAS_SSE2_HARDWARE_SUPPORT +#if defined(VXL_HAS_SSE2_HARDWARE_SUPPORT) || defined(VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE) #include <emmintrin.h> int main() { @@ -1182,12 +1182,12 @@ int main() double d_a[] = { 6.75, 3.42 }; double d_b[] = { 2.3, 9.2 }; double res[2] = {0.0}; - + __m128d z; z = _mm_mul_pd(_mm_loadu_pd(d_a),_mm_loadu_pd(d_b)); - + _mm_storeu_pd(res,z); - + return 0; } #endif diff --git a/Utilities/ITK/Utilities/vxl/core/testlib/testlib_main.cxx b/Utilities/ITK/Utilities/vxl/core/testlib/testlib_main.cxx index 670a6fedcd..6ee1897f5f 100644 --- a/Utilities/ITK/Utilities/vxl/core/testlib/testlib_main.cxx +++ b/Utilities/ITK/Utilities/vxl/core/testlib/testlib_main.cxx @@ -8,6 +8,8 @@ #include <vcl_exception.h> #endif +# include <stdlib.h> + #if defined(VCL_VC) || defined(VCL_BORLAND) # include <crtdbg.h> # include <windows.h> diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/CMakeLists.txt b/Utilities/ITK/Utilities/vxl/core/vnl/CMakeLists.txt index 8b8c6a5394..44bb93fbe8 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/CMakeLists.txt +++ b/Utilities/ITK/Utilities/vxl/core/vnl/CMakeLists.txt @@ -8,19 +8,40 @@ OPTION(VNL_CONFIG_LEGACY_METHODS OPTION(VNL_CONFIG_THREAD_SAFE "Whether thread-safe vnl implementations are used." ON) - + #IF( VXL_HAS_EMMINTRIN_H AND VXL_HAS_SSE2_HARDWARE_SUPPORT ) # OPTION(VNL_CONFIG_ENABLE_SSE2 # "Enable Streaming SIMD Extensions 2 optimisations (hardware dependant)." ON) #ELSE ( VXL_HAS_EMMINTRIN_H AND VXL_HAS_SSE2_HARDWARE_SUPPORT ) OPTION(VNL_CONFIG_ENABLE_SSE2 - "Enable Streaming SIMD Extensions 2 optimisations (hardware dependant)." OFF) + "Enable Streaming SIMD Extensions 2 optimisations (hardware dependant). Currently broken. For use by VNL developers only." OFF) #ENDIF( VXL_HAS_EMMINTRIN_H AND VXL_HAS_SSE2_HARDWARE_SUPPORT ) +OPTION(VNL_CONFIG_ENABLE_SSE2_ROUNDING + "Enable Streaming SIMD Extensions 2 implementation of rounding (hardware dependant)." + ${VXL_HAS_SSE2_HARDWARE_SUPPORT} ) +IF( VNL_CONFIG_ENABLE_SSE2_ROUNDING ) + IF( NOT VXL_HAS_SSE2_HARDWARE_SUPPORT ) + IF( VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE ) + MESSAGE( ${VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE_HELP} ) + # Reset the update configuration flag + SET( VXL_UPDATE_CONFIGURATION "ON" CACHE BOOL "Re-run the configuration tests?" FORCE ) + MESSAGE( SEND_ERROR "VXL_UPDATE_CONFIGURATION has been forced to ON. " + "Please rerun the cmake configure step" ) + ELSE( VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE ) + MESSAGE( SEND_ERROR "Cannot have VNL_CONFIG_ENABLE_SSE2_ROUNDING because" + " there is no SSE2 hardware support" ) + SET(VNL_CONFIG_ENABLE_SSE2_ROUNDING 0) + ENDIF( VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE ) + ENDIF( NOT VXL_HAS_SSE2_HARDWARE_SUPPORT ) +ENDIF( VNL_CONFIG_ENABLE_SSE2_ROUNDING ) + + MARK_AS_ADVANCED( VNL_CONFIG_CHECK_BOUNDS VNL_CONFIG_LEGACY_METHODS VNL_CONFIG_THREAD_SAFE + VNL_CONFIG_ENABLE_SSE2_ROUNDING VNL_CONFIG_ENABLE_SSE2 ) # Need to enforce 1/0 values for configuration. @@ -44,6 +65,11 @@ IF(VNL_CONFIG_ENABLE_SSE2) ELSE(VNL_CONFIG_ENABLE_SSE2) SET(VNL_CONFIG_ENABLE_SSE2 0) ENDIF(VNL_CONFIG_ENABLE_SSE2) +IF(VNL_CONFIG_ENABLE_SSE2_ROUNDING) + SET(VNL_CONFIG_ENABLE_SSE2_ROUNDING 1) +ELSE(VNL_CONFIG_ENABLE_SSE2_ROUNDING) + SET(VNL_CONFIG_ENABLE_SSE2_ROUNDING 0) +ENDIF(VNL_CONFIG_ENABLE_SSE2_ROUNDING) CONFIGURE_FILE(${vxl_SOURCE_DIR}/core/vnl/vnl_config.h.in ${vxl_BINARY_DIR}/core/vnl/vnl_config.h @ONLY IMMEDIATE) @@ -210,10 +236,6 @@ IF(CMAKE_COMPILER_IS_GNUCXX) SET_SOURCE_FILES_PROPERTIES(Templates/vnl_matrix_fixed+vnl_bignum.3.3-.cxx PROPERTIES COMPILE_FLAGS -O0) SET_SOURCE_FILES_PROPERTIES(Templates/vnl_vector+vnl_rational-.cxx PROPERTIES COMPILE_FLAGS -O0) SET_SOURCE_FILES_PROPERTIES(Templates/vnl_vector_fixed+vnl_rational.3-.cxx PROPERTIES COMPILE_FLAGS -O0) - # gcc must have -msse2 option to enable sse2 support - IF(VNL_CONFIG_ENABLE_SSE2) - ADD_DEFINITIONS( -msse2 ) - ENDIF(VNL_CONFIG_ENABLE_SSE2) ENDIF(CMAKE_COMPILER_IS_GNUCXX) ADD_LIBRARY(itkvnl ${vnl_sources}) diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_math.cxx b/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_math.cxx index 6da8eb70eb..96e727956c 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_math.cxx +++ b/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_math.cxx @@ -68,22 +68,135 @@ void test_math() testlib_test_assert_near("exp(d*i) ~= -1", vnl_math_abs(e_ipi+1.0), 0); vcl_cout << vcl_endl; - testlib_test_assert("rnd(-8.4999) == -8", vnl_math_rnd(-8.4999) == -8); - testlib_test_assert("rnd(-8.4999f) == -8", vnl_math_rnd(-8.4999f) == -8); - vcl_cout << "vnl_math_rnd(-8.50) == " << vnl_math_rnd(-8.50) << vcl_endl; - testlib_test_assert("rnd(-8.50) == -8/9", vnl_math_rnd(-8.50)/2 == -4); - testlib_test_assert("rnd(-8.50f) == -8/9", vnl_math_rnd(-8.50f)/2 == -4); - vcl_cout << "vnl_math_rnd(-8.5001) == " << vnl_math_rnd(-8.5001) << vcl_endl; - testlib_test_assert("rnd(-8.5001) == -9", vnl_math_rnd(-8.5001) == -9); - testlib_test_assert("rnd(-8.5001f) == -9", vnl_math_rnd(-8.5001f) == -9); - testlib_test_assert("rnd(8.4999) == 8", vnl_math_rnd(8.4999) == 8); - testlib_test_assert("rnd(8.4999f) == 8", vnl_math_rnd(8.4999f) == 8); - testlib_test_assert("rnd(8.50) == 8/9", vnl_math_rnd(8.50)/2 == 4); - vcl_cout << "vnl_math_rnd(8.50) == " << vnl_math_rnd(8.50) << vcl_endl; - testlib_test_assert("rnd(8.50f) == 8/9", vnl_math_rnd(8.50f)/2 == 4); - vcl_cout << "vnl_math_rnd(8.5001) == " << vnl_math_rnd(8.5001) << vcl_endl; - testlib_test_assert("rnd(8.5001) == 9", vnl_math_rnd(8.5001) == 9); - testlib_test_assert("rnd(8.5001f) == 9", vnl_math_rnd(8.5001f) == 9); + testlib_test_assert("rnd(-8.4999) == -8 ", vnl_math_rnd(-8.4999) == -8); + testlib_test_assert("rnd(-8.4999f) == -8 ", vnl_math_rnd(-8.4999f) == -8); + testlib_test_assert("rnd(-8.50) == -8/9", vnl_math_rnd(-8.50)/2 == -4); + testlib_test_assert("rnd(-8.50f) == -8/9", vnl_math_rnd(-8.50f)/2 == -4); + testlib_test_assert("rnd(-8.5001) == -9 ", vnl_math_rnd(-8.5001) == -9); + testlib_test_assert("rnd(-8.5001f) == -9 ", vnl_math_rnd(-8.5001f) == -9); + testlib_test_assert("rnd(8.4999) == 8 ", vnl_math_rnd(8.4999) == 8); + testlib_test_assert("rnd(8.4999f) == 8 ", vnl_math_rnd(8.4999f) == 8); + testlib_test_assert("rnd(8.50) == 8/9", vnl_math_rnd(8.50)/2 == 4); + testlib_test_assert("rnd(8.50f) == 8/9", vnl_math_rnd(8.50f)/2 == 4); + testlib_test_assert("rnd(8.5001) == 9 ", vnl_math_rnd(8.5001) == 9); + testlib_test_assert("rnd(8.5001f) == 9 ", vnl_math_rnd(8.5001f) == 9); + + testlib_test_assert("rnd(-9.4999) == -9 ", vnl_math_rnd(-9.4999) == -9); + testlib_test_assert("rnd(-9.4999f) == -9 ", vnl_math_rnd(-9.4999f) == -9); + testlib_test_assert("rnd(-9.50) == -9/10", (vnl_math_rnd(-9.50)+1)/2 == -4); + testlib_test_assert("rnd(-9.50f) == -9/10", (vnl_math_rnd(-9.50f)+1)/2 == -4); + testlib_test_assert("rnd(-9.5001) == -10 ", vnl_math_rnd(-9.5001) == -10); + testlib_test_assert("rnd(-9.5001f) == -10 ", vnl_math_rnd(-9.5001f) == -10); + testlib_test_assert("rnd(9.4999) == 9 ", vnl_math_rnd(9.4999) == 9); + testlib_test_assert("rnd(9.4999f) == 9 ", vnl_math_rnd(9.4999f) == 9); + testlib_test_assert("rnd(9.50) == 9/10", (vnl_math_rnd(9.50)-1)/2 == 4); + testlib_test_assert("rnd(9.50f) == 9/10", (vnl_math_rnd(9.50f)-1)/2 == 4); + testlib_test_assert("rnd(9.5001) == 10 ", vnl_math_rnd(9.5001) == 10); + testlib_test_assert("rnd(9.5001f) == 10 ", vnl_math_rnd(9.5001f) == 10); + + testlib_test_assert("rnd_halfinttoeven(-8.4999) == -8", vnl_math_rnd_halfinttoeven(-8.4999) == -8); + testlib_test_assert("rnd_halfinttoeven(-8.4999f) == -8", vnl_math_rnd_halfinttoeven(-8.4999f)== -8); + testlib_test_assert("rnd_halfinttoeven(-8.50) == -8", vnl_math_rnd_halfinttoeven(-8.50) == -8); + testlib_test_assert("rnd_halfinttoeven(-8.50f) == -8", vnl_math_rnd_halfinttoeven(-8.50f) == -8); + testlib_test_assert("rnd_halfinttoeven(-8.5001) == -9", vnl_math_rnd_halfinttoeven(-8.5001) == -9); + testlib_test_assert("rnd_halfinttoeven(-8.5001f) == -9", vnl_math_rnd_halfinttoeven(-8.5001f)== -9); + testlib_test_assert("rnd_halfinttoeven(8.4999) == 8", vnl_math_rnd_halfinttoeven(8.4999) == 8); + testlib_test_assert("rnd_halfinttoeven(8.4999f) == 8", vnl_math_rnd_halfinttoeven(8.4999f)== 8); + testlib_test_assert("rnd_halfinttoeven(8.50) == 9", vnl_math_rnd_halfinttoeven(8.50) == 8); + testlib_test_assert("rnd_halfinttoeven(8.50f) == 9", vnl_math_rnd_halfinttoeven(8.50f) == 8); + testlib_test_assert("rnd_halfinttoeven(8.5001) == 9", vnl_math_rnd_halfinttoeven(8.5001) == 9); + testlib_test_assert("rnd_halfinttoeven(8.5001f) == 9", vnl_math_rnd_halfinttoeven(8.5001f)== 9); + + testlib_test_assert("rnd_halfinttoeven(-9.4999) == -9 ", vnl_math_rnd_halfinttoeven(-9.4999) == -9); + testlib_test_assert("rnd_halfinttoeven(-9.4999f) == -9 ", vnl_math_rnd_halfinttoeven(-9.4999f)== -9); + testlib_test_assert("rnd_halfinttoeven(-9.50) == -9 ", vnl_math_rnd_halfinttoeven(-9.50) == -10); + testlib_test_assert("rnd_halfinttoeven(-9.50f) == -9 ", vnl_math_rnd_halfinttoeven(-9.50f) == -10); + testlib_test_assert("rnd_halfinttoeven(-9.5001) == -10", vnl_math_rnd_halfinttoeven(-9.5001) == -10); + testlib_test_assert("rnd_halfinttoeven(-9.5001f) == -10", vnl_math_rnd_halfinttoeven(-9.5001f)== -10); + testlib_test_assert("rnd_halfinttoeven(9.4999) == 9 ", vnl_math_rnd_halfinttoeven(9.4999) == 9); + testlib_test_assert("rnd_halfinttoeven(9.4999f) == 9 ", vnl_math_rnd_halfinttoeven(9.4999f)== 9); + testlib_test_assert("rnd_halfinttoeven(9.50) == 10", vnl_math_rnd_halfinttoeven(9.50) == 10); + testlib_test_assert("rnd_halfinttoeven(9.50f) == 10", vnl_math_rnd_halfinttoeven(9.50f) == 10); + testlib_test_assert("rnd_halfinttoeven(9.5001) == 10", vnl_math_rnd_halfinttoeven(9.5001) == 10); + testlib_test_assert("rnd_halfinttoeven(9.5001f) == 10", vnl_math_rnd_halfinttoeven(9.5001f)== 10); + + testlib_test_assert("rnd_halfintup(-8.4999) == -8", vnl_math_rnd_halfintup(-8.4999) == -8); + testlib_test_assert("rnd_halfintup(-8.4999f) == -8", vnl_math_rnd_halfintup(-8.4999f)== -8); + testlib_test_assert("rnd_halfintup(-8.50) == -8", vnl_math_rnd_halfintup(-8.50) == -8); + testlib_test_assert("rnd_halfintup(-8.50f) == -8", vnl_math_rnd_halfintup(-8.50f) == -8); + testlib_test_assert("rnd_halfintup(-8.5001) == -9", vnl_math_rnd_halfintup(-8.5001) == -9); + testlib_test_assert("rnd_halfintup(-8.5001f) == -9", vnl_math_rnd_halfintup(-8.5001f)== -9); + testlib_test_assert("rnd_halfintup(8.4999) == 8", vnl_math_rnd_halfintup(8.4999) == 8); + testlib_test_assert("rnd_halfintup(8.4999f) == 8", vnl_math_rnd_halfintup(8.4999f)== 8); + testlib_test_assert("rnd_halfintup(8.50) == 9", vnl_math_rnd_halfintup(8.50) == 9); + testlib_test_assert("rnd_halfintup(8.50f) == 9", vnl_math_rnd_halfintup(8.50f) == 9); + testlib_test_assert("rnd_halfintup(8.5001) == 9", vnl_math_rnd_halfintup(8.5001) == 9); + testlib_test_assert("rnd_halfintup(8.5001f) == 9", vnl_math_rnd_halfintup(8.5001f)== 9); + + testlib_test_assert("rnd_halfintup(-9.4999) == -9 ", vnl_math_rnd_halfintup(-9.4999) == -9); + testlib_test_assert("rnd_halfintup(-9.4999f) == -9 ", vnl_math_rnd_halfintup(-9.4999f)== -9); + testlib_test_assert("rnd_halfintup(-9.50) == -9 ", vnl_math_rnd_halfintup(-9.50) == -9); + testlib_test_assert("rnd_halfintup(-9.50f) == -9 ", vnl_math_rnd_halfintup(-9.50f) == -9); + testlib_test_assert("rnd_halfintup(-9.5001) == -10", vnl_math_rnd_halfintup(-9.5001) == -10); + testlib_test_assert("rnd_halfintup(-9.5001f) == -10", vnl_math_rnd_halfintup(-9.5001f)== -10); + testlib_test_assert("rnd_halfintup(9.4999) == 9 ", vnl_math_rnd_halfintup(9.4999) == 9); + testlib_test_assert("rnd_halfintup(9.4999f) == 9 ", vnl_math_rnd_halfintup(9.4999f)== 9); + testlib_test_assert("rnd_halfintup(9.50) == 10", vnl_math_rnd_halfintup(9.50) == 10); + testlib_test_assert("rnd_halfintup(9.50f) == 10", vnl_math_rnd_halfintup(9.50f) == 10); + testlib_test_assert("rnd_halfintup(9.5001) == 10", vnl_math_rnd_halfintup(9.5001) == 10); + testlib_test_assert("rnd_halfintup(9.5001f) == 10", vnl_math_rnd_halfintup(9.5001f)== 10); + + testlib_test_assert("floor(8.0) == 8", vnl_math_floor(8.0) == 8); + testlib_test_assert("floor(8.0f) == 8", vnl_math_floor(8.0f) == 8); + testlib_test_assert("floor(8.9999) == 8", vnl_math_floor(8.9999) == 8); + testlib_test_assert("floor(8.9999f) == 8", vnl_math_floor(8.9999f) == 8); + testlib_test_assert("floor(8.0001) == 8", vnl_math_floor(8.0001) == 8); + testlib_test_assert("floor(8.0001f) == 8", vnl_math_floor(8.0001f) == 8); + testlib_test_assert("floor(-8.0) == -8", vnl_math_floor(-8.0) == -8); + testlib_test_assert("floor(-8.0f) == -8", vnl_math_floor(-8.0f) == -8); + testlib_test_assert("floor(-8.9999) == -9", vnl_math_floor(-8.9999) == -9); + testlib_test_assert("floor(-8.9999f) == -9", vnl_math_floor(-8.9999f) == -9); + testlib_test_assert("floor(-8.0001) == -9", vnl_math_floor(-8.0001) == -9); + testlib_test_assert("floor(-8.0001f) == -9", vnl_math_floor(-8.0001f) == -9); + + testlib_test_assert("floor(9.0) == 9", vnl_math_floor(9.0) == 9); + testlib_test_assert("floor(9.0f) == 9", vnl_math_floor(9.0f) == 9); + testlib_test_assert("floor(9.9999) == 9", vnl_math_floor(9.9999) == 9); + testlib_test_assert("floor(9.9999f) == 9", vnl_math_floor(9.9999f) == 9); + testlib_test_assert("floor(9.0001) == 9", vnl_math_floor(9.0001) == 9); + testlib_test_assert("floor(9.0001f) == 9", vnl_math_floor(9.0001f) == 9); + testlib_test_assert("floor(-9.0) == -9", vnl_math_floor(-9.0) == -9); + testlib_test_assert("floor(-9.0f) == -9", vnl_math_floor(-9.0f) == -9); + testlib_test_assert("floor(-9.9999) == -10", vnl_math_floor(-9.9999) == -10); + testlib_test_assert("floor(-9.9999f) == -10", vnl_math_floor(-9.9999f) == -10); + testlib_test_assert("floor(-9.0001) == -10", vnl_math_floor(-9.0001) == -10); + testlib_test_assert("floor(-9.0001f) == -10", vnl_math_floor(-9.0001f) == -10); + + testlib_test_assert("ceil(8.0) == 8", vnl_math_ceil(8.0) == 8); + testlib_test_assert("ceil(8.0f) == 8", vnl_math_ceil(8.0f) == 8); + testlib_test_assert("ceil(8.9999) == 9", vnl_math_ceil(8.9999) == 9); + testlib_test_assert("ceil(8.9999f) == 9", vnl_math_ceil(8.9999f) == 9); + testlib_test_assert("ceil(8.0001) == 9", vnl_math_ceil(8.0001) == 9); + testlib_test_assert("ceil(8.0001f) == 9", vnl_math_ceil(8.0001f) == 9); + testlib_test_assert("ceil(-8.0) == -8", vnl_math_ceil(-8.0) == -8); + testlib_test_assert("ceil(-8.0f) == -8", vnl_math_ceil(-8.0f) == -8); + testlib_test_assert("ceil(-8.9999) == -8", vnl_math_ceil(-8.9999) == -8); + testlib_test_assert("ceil(-8.9999f) == -8", vnl_math_ceil(-8.9999f) == -8); + testlib_test_assert("ceil(-8.0001) == -8", vnl_math_ceil(-8.0001) == -8); + testlib_test_assert("ceil(-8.0001f) == -8", vnl_math_ceil(-8.0001f) == -8); + + testlib_test_assert("ceil(9.0) == 9", vnl_math_ceil(9.0) == 9); + testlib_test_assert("ceil(9.0f) == 9", vnl_math_ceil(9.0f) == 9); + testlib_test_assert("ceil(9.9999) == 10", vnl_math_ceil(9.9999) == 10); + testlib_test_assert("ceil(9.9999f) == 10", vnl_math_ceil(9.9999f) == 10); + testlib_test_assert("ceil(9.0001) == 10", vnl_math_ceil(9.0001) == 10); + testlib_test_assert("ceil(9.0001f) == 10", vnl_math_ceil(9.0001f) == 10); + testlib_test_assert("ceil(-9.0) == -9", vnl_math_ceil(-9.0) == -9); + testlib_test_assert("ceil(-9.0f) == -9", vnl_math_ceil(-9.0f) == -9); + testlib_test_assert("ceil(-9.9999) == -9", vnl_math_ceil(-9.9999) == -9); + testlib_test_assert("ceil(-9.9999f) == -9", vnl_math_ceil(-9.9999f) == -9); + testlib_test_assert("ceil(-9.0001) == -9", vnl_math_ceil(-9.0001) == -9); + testlib_test_assert("ceil(-9.0001f) == -9", vnl_math_ceil(-9.0001f) == -9); testlib_test_assert(" isfinite(f) ", vnl_math_isfinite(f)); testlib_test_assert(" isfinite(d) ", vnl_math_isfinite(d)); @@ -133,7 +246,7 @@ void test_math() for (int i=1; i*sizeof(unsigned char)<sizeof(p); ++i) \ vcl_cout<<vcl_setfill('0')<<vcl_setw(sizeof(unsigned char))<<(reinterpret_cast<unsigned char*>(&p))[i]; \ vcl_cout<<vcl_dec - +#if 0 vcl_cout << "pinf_f = " << pinf_f << " = " << print_hex(pinf_f) << vcl_endl << "ninf_f = " << ninf_f << " = " << print_hex(ninf_f) << vcl_endl << "pinf_d = " << pinf_d << " = " << print_hex(pinf_d) << vcl_endl @@ -144,6 +257,8 @@ void test_math() << "qnan_d = " << qnan_d << " = " << print_hex(qnan_d) << vcl_endl << "qnan_q = " << qnan_q << " = " << print_hex(qnan_q) << vcl_endl << vcl_endl; +#endif + #undef print_hex #ifndef __alpha__ // on alpha, infinity() == max() @@ -180,8 +295,8 @@ void test_math() testlib_test_assert("!isnan(pinf_q) ", !vnl_math_isnan(pinf_q)); testlib_test_assert("!isnan(ninf_q) ", !vnl_math_isnan(ninf_q)); testlib_test_assert("!isfinite(qnan_q)", !vnl_math_isfinite(qnan_q)); - testlib_test_assert("!isinf(qnan_q) ", !vnl_math_isinf(qnan_q)); #if 0 // even more nonstandard ... + testlib_test_assert("!isinf(qnan_q) ", !vnl_math_isinf(qnan_q)); testlib_test_assert(" isnan(qnan_q) ", vnl_math_isnan(qnan_q)); #endif // 0 #endif // __ICC diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_matlab.cxx b/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_matlab.cxx index 8f36c1b53e..e5314dd134 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_matlab.cxx +++ b/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_matlab.cxx @@ -16,9 +16,47 @@ #include <vnl/vnl_matlab_print.h> #include <vnl/vnl_matlab_write.h> #include <vnl/vnl_matlab_read.h> - +#include <vnl/vnl_matlab_header.h> #include <testlib/testlib_test.h> +#if VXL_LITTLE_ENDIAN // #ifdef i386 +# define NONnative_BYTE_ORDER vnl_matlab_header::vnl_BIG_ENDIAN +#else +# define NONnative_BYTE_ORDER vnl_matlab_header::vnl_LITTLE_ENDIAN +#endif + +// +// this duplicates code from vnl_matlab_write, but it's the only way to +// get a byte-swapped file, short of reading in a native file and swapping it +// and writing it back out, and that isn't any easier. +void matlab_write_swapped(vcl_ostream &f, + float *array, + unsigned size, + char const *name) +{ + vnl_matlab_header hdr; + hdr.type = NONnative_BYTE_ORDER + + vnl_matlab_header::vnl_COLUMN_WISE + + vnl_matlab_header::vnl_SINGLE_PRECISION; + hdr.rows = (long)size; + hdr.cols = 1; + hdr.imag = 0; // not complex + hdr.namlen = (unsigned long)vcl_strlen(name)+1L; + byteswap::swap32(&hdr.type); + byteswap::swap32(&hdr.rows); + byteswap::swap32(&hdr.cols); + byteswap::swap32(&hdr.imag); + byteswap::swap32(&hdr.namlen); + f.write((char const *)&hdr, sizeof(hdr)); + f.write((char const *)name, vcl_strlen(name)+1); + for(unsigned i = 0; i < size; ++i) + { + float dummy = array[i]; + byteswap::swap32(&dummy); + f.write((char const *)&dummy,sizeof(dummy)); + } +} + static void fsm_assert_(int lineno, bool pass, char const *expr) { vcl_cout << __FILE__ " : " << lineno << vcl_endl; @@ -55,8 +93,10 @@ static void test_matlab() // vnl_matlab_write, vnl_matlab_read { - vcl_string tmp_nam = vul_temp_filename(); + vcl_string tmp_nam = vul_temp_filename(), + tmp_nam2 = vul_temp_filename(); char const *file = tmp_nam!="" ? tmp_nam.c_str() : "smoo.mat"; + char const *file2 = tmp_nam2!="" ? tmp_nam2.c_str() : "smoo2.mat"; { vcl_ofstream f(file); #ifdef LEAVE_IMAGES_BEHIND @@ -64,10 +104,13 @@ static void test_matlab() #endif vnl_matlab_write(f, v.begin(), v.size(), "v"); vnl_matlab_write(f, (double const * const *)M.data_array(), M.rows(), M.cols(), (char const *)"M"); + // + // write swapped matlab file + vcl_ofstream f2(file2); + matlab_write_swapped(f2, v.begin(), v.size(), "v"); } { vcl_ifstream f(file); - vnl_matlab_readhdr vh(f); fsm_assert( vh?true:false ); fsm_assert( vh.is_single()); @@ -79,6 +122,18 @@ static void test_matlab() fsm_assert( vh.read_data(v_.begin())); fsm_assert(v_ == v); + vcl_ifstream f2(file2); + vnl_matlab_readhdr vh2(f2); + fsm_assert( vh2?true:false ); + fsm_assert( vh2.is_single()); + fsm_assert( vh2.rows() == (int)v.size()); + fsm_assert( vh2.cols() == 1); + fsm_assert(!vh2.is_complex()); + fsm_assert(vcl_strcmp(vh2.name(), "v")==0); + vnl_vector<float> v_2(v.size()); + fsm_assert( vh2.read_data(v_2.begin())); + fsm_assert(v_2 == v); + vnl_matlab_readhdr Mh(f); fsm_assert( Mh?true:false ); fsm_assert(!Mh.is_single()); diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_config.h.in b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_config.h.in index 22745b37bb..13f2c93d75 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_config.h.in +++ b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_config.h.in @@ -19,4 +19,7 @@ //: Set to 0 if you don't have SSE2 support on your target platform #define VNL_CONFIG_ENABLE_SSE2 @VNL_CONFIG_ENABLE_SSE2@ +//: Set to 0 if you don't want to use SSE2 instructions to implement rounding, floor, and ceil functions. +#define VNL_CONFIG_ENABLE_SSE2_ROUNDING @VNL_CONFIG_ENABLE_SSE2_ROUNDING@ + #endif diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.h b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.h index b9b723c73a..87cb41744c 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.h +++ b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.h @@ -5,39 +5,69 @@ #pragma interface #endif //: -// \file -// \brief Namespace with standard math functions +// \file +// \brief Namespace with standard math functions // -// The vnl_math namespace provides a standard set of the simple mathematical -// functions (min, max, sqr, sgn, rnd, abs), and some predefined constants -// such as pi and e, which are not defined by the ANSI C++ standard. +// The vnl_math namespace provides a standard set of the simple mathematical +// functions (min, max, sqr, sgn, rnd, abs), and some predefined constants +// such as pi and e, which are not defined by the ANSI C++ standard. // -// There are complex versions defined in vnl_complex.h +// There are complex versions defined in vnl_complex.h // -// That's right, M_PI is nonstandard! +// That's right, M_PI is nonstandard! // -// Aside from e, pi and their associates the class also defines eps, -// the IEEE double machine precision. This is the smallest number -// eps such that 1+eps != 1. +// Aside from e, pi and their associates the class also defines eps, +// the IEEE double machine precision. This is the smallest number +// eps such that 1+eps != 1. // -// The operations are overloaded for int, float and double arguments, -// which in combination with inlining can make them more efficient than -// their counterparts in the standard C library. +// The operations are overloaded for int, float and double arguments, +// which in combination with inlining can make them more efficient than +// their counterparts in the standard C library. // -// \author Andrew W. Fitzgibbon, Oxford RRG -// \date July 13, 1996 +// \author Andrew W. Fitzgibbon, Oxford RRG +// \date July 13, 1996 // // \verbatim // Modifications -// 210598 AWF Removed conditional VCL_IMPLEMENT_STATIC_CONSTS, sometimes gcc needs them. -// LSB (Modifications) 23/1/01 Documentation tidied -// Peter Vanroose - 7 Sept. 2002 - maxdouble etc. replaced by vnl_numeric_traits<T>::maxval +// 21 May 1998 AWF Removed conditional VCL_IMPLEMENT_STATIC_CONSTS, sometimes gcc needs them. +// LSB (Modifications) 23 Jan 2001 Documentation tidied +// Peter Vanroose - 7 Sep 2002 - maxdouble etc. replaced by vnl_numeric_traits<T>::maxval // Amitha Perera - 13 Sep 2002 - make constant initialization standards compliant. // \endverbatim #include <vcl_cmath.h> #include "dll.h" -#include <vxl_config.h> // for VXL_C_MATH_HAS_LROUND +#include <vxl_config.h> +#include <vnl/vnl_config.h> // for VNL_CONFIG_ENABLE_SSE2_ROUNDING +#ifdef VNL_CHECK_FPU_ROUNDING_MODE +# include <vcl_cassert.h> +#endif + +// Figure out when the fast implementation can be used +#if VNL_CONFIG_ENABLE_SSE2_ROUNDING && (!defined(__GCCXML__)) +# if !VXL_HAS_EMMINTRIN_H +# error "Required file emmintrin.h for SSE2 not found" +# else +# include <emmintrin.h> // sse 2 intrinsics +# define USE_SSE2_IMPL 1 +# endif +#else +# define USE_SSE2_IMPL 0 +#endif +// Turn on fast impl when using GCC with the following exception: +// GCCXML, PPC, PPC64 +#if defined(__GNUC__) && (!defined(__GCCXML__)) && (!defined(__ppc__)) && (!defined(__ppc64__)) +# define GCC_USE_FAST_IMPL 1 +#else +# define GCC_USE_FAST_IMPL 0 +#endif +// Turn on fast impl when using msvc on 32 bits windows +#if defined(VCL_VC) && (!defined(__GCCXML__)) && !defined(_WIN64) +# define VC_USE_FAST_IMPL 1 +#else +# define VC_USE_FAST_IMPL 0 +#endif + //: Type-accessible infinities for use in templates. template <class T> T vnl_huge_val(T); @@ -53,19 +83,20 @@ class vnl_math { public: //: pi, e and all that - static VNL_DLL_DATA const double e VCL_STATIC_CONST_INIT_FLOAT_DECL(2.7182818284590452354); - static VNL_DLL_DATA const double log2e VCL_STATIC_CONST_INIT_FLOAT_DECL(1.4426950408889634074); - static VNL_DLL_DATA const double log10e VCL_STATIC_CONST_INIT_FLOAT_DECL(0.43429448190325182765); - static VNL_DLL_DATA const double ln2 VCL_STATIC_CONST_INIT_FLOAT_DECL(0.69314718055994530942); - static VNL_DLL_DATA const double ln10 VCL_STATIC_CONST_INIT_FLOAT_DECL(2.30258509299404568402); - static VNL_DLL_DATA const double pi VCL_STATIC_CONST_INIT_FLOAT_DECL(3.14159265358979323846); - static VNL_DLL_DATA const double pi_over_2 VCL_STATIC_CONST_INIT_FLOAT_DECL(1.57079632679489661923); - static VNL_DLL_DATA const double pi_over_4 VCL_STATIC_CONST_INIT_FLOAT_DECL(0.78539816339744830962); - static VNL_DLL_DATA const double one_over_pi VCL_STATIC_CONST_INIT_FLOAT_DECL(0.31830988618379067154); - static VNL_DLL_DATA const double two_over_pi VCL_STATIC_CONST_INIT_FLOAT_DECL(0.63661977236758134308); - static VNL_DLL_DATA const double two_over_sqrtpi VCL_STATIC_CONST_INIT_FLOAT_DECL(1.12837916709551257390); - static VNL_DLL_DATA const double sqrt2 VCL_STATIC_CONST_INIT_FLOAT_DECL(1.41421356237309504880); - static VNL_DLL_DATA const double sqrt1_2 VCL_STATIC_CONST_INIT_FLOAT_DECL(0.70710678118654752440); + static VNL_DLL_DATA const double e VCL_STATIC_CONST_INIT_FLOAT_DECL(2.7182818284590452354); + static VNL_DLL_DATA const double log2e VCL_STATIC_CONST_INIT_FLOAT_DECL(1.4426950408889634074); + static VNL_DLL_DATA const double log10e VCL_STATIC_CONST_INIT_FLOAT_DECL(0.43429448190325182765); + static VNL_DLL_DATA const double ln2 VCL_STATIC_CONST_INIT_FLOAT_DECL(0.69314718055994530942); + static VNL_DLL_DATA const double ln10 VCL_STATIC_CONST_INIT_FLOAT_DECL(2.30258509299404568402); + static VNL_DLL_DATA const double pi VCL_STATIC_CONST_INIT_FLOAT_DECL(3.14159265358979323846); + static VNL_DLL_DATA const double pi_over_2 VCL_STATIC_CONST_INIT_FLOAT_DECL(1.57079632679489661923); + static VNL_DLL_DATA const double pi_over_4 VCL_STATIC_CONST_INIT_FLOAT_DECL(0.78539816339744830962); + static VNL_DLL_DATA const double one_over_pi VCL_STATIC_CONST_INIT_FLOAT_DECL(0.31830988618379067154); + static VNL_DLL_DATA const double two_over_pi VCL_STATIC_CONST_INIT_FLOAT_DECL(0.63661977236758134308); + static VNL_DLL_DATA const double two_over_sqrtpi VCL_STATIC_CONST_INIT_FLOAT_DECL(1.12837916709551257390); + static VNL_DLL_DATA const double one_over_sqrt2pi VCL_STATIC_CONST_INIT_FLOAT_DECL(0.39894228040143267794); + static VNL_DLL_DATA const double sqrt2 VCL_STATIC_CONST_INIT_FLOAT_DECL(1.41421356237309504880); + static VNL_DLL_DATA const double sqrt1_2 VCL_STATIC_CONST_INIT_FLOAT_DECL(0.70710678118654752440); //: IEEE double machine precision static VNL_DLL_DATA const double eps VCL_STATIC_CONST_INIT_FLOAT_DECL(2.2204460492503131e-16); @@ -140,50 +171,353 @@ bool vnl_math_isfinite(long double); template <class T> bool vnl_math_isfinite(T); #endif -// rnd (rounding; 0.5 rounds up) -#if VXL_C_MATH_HAS_LROUND -// Use C99 functions, which GCC implements as an intrinsic -// Or in simpler terms - is at least 3 times faster. -inline int vnl_math_rnd(float x) { return static_cast<int>(lroundf(x)); } -inline int vnl_math_rnd(double x) { return static_cast<int>(lround(x)); } -#elif defined (VCL_VC) && !defined(__GCCXML__) && !defined(_WIN64) -// Use assembly inline function from -// http://mega-nerd.com/FPcast/ + + +// vnl_math_rnd_halfinttoeven -- round towards nearest integer +// halfway cases are rounded towards the nearest even integer, e.g. +// vnl_math_rnd_halfinttoeven( 1.5) == 2 +// vnl_math_rnd_halfinttoeven(-1.5) == -2 +// vnl_math_rnd_halfinttoeven( 2.5) == 2 +// vnl_math_rnd_halfinttoeven( 3.5) == 4 // +// We assume that the rounding mode is not changed from the default +// one (or at least that it is always restored to the default one). + +#if USE_SSE2_IMPL // Fast sse2 implementation + +inline int vnl_math_rnd_halfinttoeven(float x) +{ +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround()==FE_TONEAREST); +# endif + return _mm_cvtss_si32(_mm_set_ss(x)); +} +inline int vnl_math_rnd_halfinttoeven(double x) +{ +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround()==FE_TONEAREST); +# endif + return _mm_cvtsd_si32(_mm_set_sd(x)); +} + +#elif GCC_USE_FAST_IMPL // Fast gcc asm implementation + +inline int vnl_math_rnd_halfinttoeven(float x) +{ +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround()==FE_TONEAREST); +# endif + int r; + __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return r; +} +inline int vnl_math_rnd_halfinttoeven(double x) +{ +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround()==FE_TONEAREST); +# endif + int r; + __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return r; +} + +#elif VC_USE_FAST_IMPL // Fast msvc asm implementation + +inline int vnl_math_rnd_halfinttoeven(float x) +{ + int r; + __asm { + fld x + fistp r + } + return r; +} +inline int vnl_math_rnd_halfinttoeven(double x) +{ + int r; + __asm { + fld x + fistp r + } + return r; +} + +#else // Vanilla implementation + +inline int vnl_math_rnd_halfinttoeven(float x) +{ + if (x>=0.f) + { + x+=0.5f; + const int r = static_cast<int>(x); + if ( x != static_cast<float>(r) ) return r; + return 2*(r/2); + } + else + { + x-=0.5f; + const int r = static_cast<int>(x); + if ( x != static_cast<float>(r) ) return r; + return 2*(r/2); + } +} +inline int vnl_math_rnd_halfinttoeven(double x) +{ + if (x>=0.) + { + x+=0.5; + const int r = static_cast<int>(x); + if ( x != static_cast<double>(r) ) return r; + return 2*(r/2); + } + else + { + x-=0.5; + const int r = static_cast<int>(x); + if ( x != static_cast<double>(r) ) return r; + return 2*(r/2); + } +} + +#endif + + + +// vnl_math_rnd_halfintup -- round towards nearest integer +// halfway cases are rounded upward, e.g. +// vnl_math_rnd_halfintup( 1.5) == 2 +// vnl_math_rnd_halfintup(-1.5) == -1 +// vnl_math_rnd_halfintup( 2.5) == 3 +// +// Be careful: argument absolute value must be less than INT_MAX/2 +// for vnl_math_rnd_halfintup to be guaranteed to work. +// We also assume that the rounding mode is not changed from the default +// one (or at least that it is always restored to the default one). + +#if USE_SSE2_IMPL || GCC_USE_FAST_IMPL || VC_USE_FAST_IMPL + +inline int vnl_math_rnd_halfintup(float x) { return vnl_math_rnd_halfinttoeven(2*x+0.5f)>>1; } +inline int vnl_math_rnd_halfintup(double x) { return vnl_math_rnd_halfinttoeven(2*x+0.5)>>1; } + +#else // Vanilla implementation + +inline int vnl_math_rnd_halfintup(float x) +{ + x+=0.5f; + return static_cast<int>(x>=0.f?x:(x==static_cast<int>(x)?x:x-1.f)); +} +inline int vnl_math_rnd_halfintup(double x) +{ + x+=0.5; + return static_cast<int>(x>=0.?x:(x==static_cast<int>(x)?x:x-1.)); +} - // Win32 doesn't seem to have these functions. - // Therefore implement inline versions of these functions here. -// NB But Win64 does not support the non-standard _asm - __inline int - vnl_math_rnd (double flt) - { int intgr; - _asm - { fld flt - fistp intgr - } ; - return intgr ; - } - - __inline int - vnl_math_rnd (float flt) - { int intgr; - _asm - { fld flt - fistp intgr - } ; - return intgr; - } -#else -inline int vnl_math_rnd(float x) { return (x>=0.0)?(int)(x + 0.5):(int)(x - 0.5); } -inline int vnl_math_rnd(double x) { return (x>=0.0)?(int)(x + 0.5):(int)(x - 0.5); } #endif + + +// vnl_math_rnd -- round towards nearest integer +// halfway cases such as 0.5 may be rounded either up or down +// so as to maximize the efficiency, e.g. +// vnl_math_rnd_halfinttoeven( 1.5) == 1 or 2 +// vnl_math_rnd_halfinttoeven(-1.5) == -2 or -1 +// vnl_math_rnd_halfinttoeven( 2.5) == 2 or 3 +// vnl_math_rnd_halfinttoeven( 3.5) == 3 or 4 +// +// We assume that the rounding mode is not changed from the default +// one (or at least that it is always restored to the default one). + +#if USE_SSE2_IMPL || GCC_USE_FAST_IMPL || VC_USE_FAST_IMPL + +inline int vnl_math_rnd(float x) { return vnl_math_rnd_halfinttoeven(x); } +inline int vnl_math_rnd(double x) { return vnl_math_rnd_halfinttoeven(x); } + +#else // Vanilla implementation + +inline int vnl_math_rnd(float x) { return x>=0.f?static_cast<int>(x+.5f):static_cast<int>(x-.5f); } +inline int vnl_math_rnd(double x) { return x>=0.0?static_cast<int>(x+0.5):static_cast<int>(x-0.5); } + + +#endif + + + +// vnl_math_floor -- round towards minus infinity +// +// Be careful: argument absolute value must be less than INT_MAX/2 +// for vnl_math_floor to be guaranteed to work. +// We also assume that the rounding mode is not changed from the default +// one (or at least that it is always restored to the default one). + +#if USE_SSE2_IMPL // Fast sse2 implementation + +inline int vnl_math_floor(float x) +{ +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround()==FE_TONEAREST); +# endif + return _mm_cvtss_si32(_mm_set_ss(2*x-.5f))>>1; +} +inline int vnl_math_floor(double x) +{ +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround()==FE_TONEAREST); +# endif + return _mm_cvtsd_si32(_mm_set_sd(2*x-.5))>>1; +} + +#elif GCC_USE_FAST_IMPL // Fast gcc asm implementation + +inline int vnl_math_floor(float x) +{ +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround()==FE_TONEAREST); +# endif + int r; + x = 2*x-.5f; + __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return r>>1; +} +inline int vnl_math_floor(double x) +{ +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround()==FE_TONEAREST); +# endif + int r; + x = 2*x-.5; + __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return r>>1; +} + +#elif VC_USE_FAST_IMPL // Fast msvc asm implementation + +inline int vnl_math_floor(float x) +{ + int r; + x = 2*x-.5f; + __asm { + fld x + fistp r + } + return r>>1; +} +inline int vnl_math_floor(double x) +{ + int r; + x = 2*x-.5; + __asm { + fld x + fistp r + } + return r>>1; +} + +#else // Vanilla implementation + +inline int vnl_math_floor(float x) +{ + return static_cast<int>(x>=0.f?x:(x==static_cast<int>(x)?x:x-1.f)); +} +inline int vnl_math_floor(double x) +{ + return static_cast<int>(x>=0.0?x:(x==static_cast<int>(x)?x:x-1.0)); +} + +#endif + + + +// vnl_math_ceil -- round towards plus infinity +// +// Be careful: argument absolute value must be less than INT_MAX/2 +// for vnl_math_ceil to be guaranteed to work. +// We also assume that the rounding mode is not changed from the default +// one (or at least that it is always restored to the default one). + +#if USE_SSE2_IMPL // Fast sse2 implementation + +inline int vnl_math_ceil(float x) +{ +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround()==FE_TONEAREST); +# endif + return -(_mm_cvtss_si32(_mm_set_ss(-.5f-2*x))>>1); +} +inline int vnl_math_ceil(double x) +{ +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround()==FE_TONEAREST); +# endif + return -(_mm_cvtsd_si32(_mm_set_sd(-.5-2*x))>>1); +} + +#elif GCC_USE_FAST_IMPL // Fast gcc asm implementation + +inline int vnl_math_ceil(float x) +{ +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround()==FE_TONEAREST); +# endif + int r; + x = -.5f-2*x; + __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return -(r>>1); +} +inline int vnl_math_ceil(double x) +{ +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround()==FE_TONEAREST); +# endif + int r; + x = -.5-2*x; + __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return -(r>>1); +} + +#elif VC_USE_FAST_IMPL // Fast msvc asm implementation + +inline int vnl_math_ceil(float x) +{ + int r; + x = -.5f-2*x; + __asm { + fld x + fistp r + } + return -(r>>1); +} +inline int vnl_math_ceil(double x) +{ + int r; + x = -.5-2*x; + __asm { + fld x + fistp r + } + return -(r>>1); +} + +#else // Vanilla implementation + +inline int vnl_math_ceil(float x) +{ + return static_cast<int>(x<0.f?x:(x==static_cast<int>(x)?x:x+1.f)); +} +inline int vnl_math_ceil(double x) +{ + return static_cast<int>(x<0.0?x:(x==static_cast<int>(x)?x:x+1.0)); +} + +#endif + + + // abs inline bool vnl_math_abs(bool x) { return x; } inline unsigned char vnl_math_abs(unsigned char x) { return x; } -inline unsigned char vnl_math_abs(signed char x) { return x < 0 ? -x : x; } -inline unsigned char vnl_math_abs(char x) { return (unsigned char)x; } -inline unsigned short vnl_math_abs(short x) { return x < 0 ? -x : x; } +inline unsigned char vnl_math_abs(signed char x) { return x < 0 ? static_cast<unsigned char>(-x) : x; } +inline unsigned char vnl_math_abs(char x) { return static_cast<unsigned char>(x); } +inline unsigned short vnl_math_abs(short x) { return x < 0 ? static_cast<unsigned short>(-x) : x; } inline unsigned short vnl_math_abs(unsigned short x){ return x; } inline unsigned int vnl_math_abs(int x) { return x < 0 ? -x : x; } inline unsigned int vnl_math_abs(unsigned int x) { return x; } diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_header.h b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_header.h index 05867855ba..9e374ee06e 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_header.h +++ b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_header.h @@ -34,4 +34,47 @@ struct vnl_matlab_header }; }; +namespace byteswap +{ +// +// byteswap routines, stolen from +// ITK +inline void +swap32(void *ptr) +{ + char one_byte; + char *p = reinterpret_cast<char *>(ptr); + + one_byte = p[0]; + p[0] = p[3]; + p[3] = one_byte; + + one_byte = p[1]; + p[1] = p[2]; + p[2] = one_byte; +} +inline void +swap64(void *ptr) +{ + char one_byte; + char *p = reinterpret_cast<char *>(ptr); + + one_byte = p[0]; + p[0] = p[7]; + p[7] = one_byte; + + one_byte = p[1]; + p[1] = p[6]; + p[6] = one_byte; + + one_byte = p[2]; + p[2] = p[5]; + p[5] = one_byte; + + one_byte = p[3]; + p[3] = p[4]; + p[4] = one_byte; +} +} + #endif // vnl_matlab_header_h_ diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_read.cxx b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_read.cxx index 23cb7594aa..aca69d06dc 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_read.cxx +++ b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_read.cxx @@ -5,7 +5,7 @@ //: // \file // \author fsm - +#include <vxl_config.h> #include "vnl_matlab_read.h" #include <vcl_ios.h> // for vcl_ios_cur #include <vcl_iostream.h> @@ -13,6 +13,7 @@ #include <vcl_complex.h> #include <vnl/vnl_c_vector.h> + // FIXME: Currently ignores the byte ordering of the MAT file header, effectively // assuming the MAT file was written with the native byte ordering. @@ -52,7 +53,7 @@ implement_read_complex_data(double) //-------------------------------------------------------------------------------- -vnl_matlab_readhdr::vnl_matlab_readhdr(vcl_istream &s_) : s(s_), varname(0), data_read(false) +vnl_matlab_readhdr::vnl_matlab_readhdr(vcl_istream &s_) : s(s_), varname(0), data_read(false), need_swap(false) { read_hdr(); } @@ -95,6 +96,45 @@ void vnl_matlab_readhdr::read_hdr() { vcl_memset(&hdr, 0, sizeof hdr); ::vnl_read_bytes(s, &hdr, sizeof(hdr)); + // + // determine if data needs swapping when read + // Everything else depends on this; if the header needs swapping + // and is not, nothing good will happen. + switch(hdr.type) + { + case 0: + // 0 means double-precision values, column-major, little-endian, + // so you need to swap if the system is big-endian +#if VXL_BIG_ENDIAN + need_swap = true; +#endif + break; + case 10: + // Regardless of endian-ness, these flag values are + // what the writer puts in the header in the native format, + // therefore if you see any of them, the file is the same-endian + // as the system you're reading on. + case 100: + case 110: + case 1000: + case 1100: + case 1110: + need_swap = false; + break; + default: + // any other values are either gibberish, or need to be byte-swapped + // we hope that it means the file needs byte-swapping, and not that + // the file is corrupt. + need_swap = true; + } + if(need_swap) + { + byteswap::swap32(&hdr.type); + byteswap::swap32(&hdr.rows); + byteswap::swap32(&hdr.cols); + byteswap::swap32(&hdr.imag); + byteswap::swap32(&hdr.namlen); + } if (varname) delete [] varname; varname = new char[hdr.namlen+1]; @@ -107,7 +147,6 @@ void vnl_matlab_readhdr::read_hdr() #endif ::vnl_read_bytes(s, varname, hdr.namlen); varname[hdr.namlen] = '\0'; - data_read = false; } @@ -140,12 +179,23 @@ bool vnl_matlab_readhdr::read_data(T &v) { \ if (!type_chck(v)) { vcl_cerr << "type_check\n"; return false; }\ if (rows()!=1 || cols()!=1) { vcl_cerr << "size0\n"; return false; } \ vnl_matlab_read_data(s, &v, 1); \ + if(need_swap) \ + { \ + if(sizeof(v) == 4) byteswap::swap32(&v); else byteswap::swap64(&v); \ + } \ data_read = true; return *this; \ } \ bool vnl_matlab_readhdr::read_data(T *p) { \ if (!type_chck(p[0])) { vcl_cerr << "type_check\n"; return false; } \ if (rows()!=1 && cols()!=1) { vcl_cerr << "size1\n"; return false; } \ vnl_matlab_read_data(s, p, rows()*cols()); \ + if(need_swap) \ + { \ + for(unsigned i = 0; i < rows()*cols(); i++) \ + { \ + if(sizeof(*p) == 4) byteswap::swap32(&(p[i])); else byteswap::swap64(&(p[i])); \ + } \ + } \ data_read = true; return *this; \ } \ bool vnl_matlab_readhdr::read_data(T * const *m) { \ @@ -153,6 +203,13 @@ bool vnl_matlab_readhdr::read_data(T * const *m) { \ T *tmp = vnl_c_vector<T >::allocate_T(rows()*cols()); \ /*vnl_c_vector<T >::fill(tmp, rows()*cols(), 3.14159);*/ \ vnl_matlab_read_data(s, tmp, rows()*cols()); \ + if(need_swap) \ + { \ + for(unsigned i = 0; i < rows()*cols(); i++) \ + { \ + if(sizeof(T) == 4) byteswap::swap32(&(tmp[i])); else byteswap::swap64(&(tmp[i])); \ + } \ + } \ int a, b; \ if (is_rowwise()) { \ a = cols(); \ diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_read.h b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_read.h index 9e12a79123..7d869fcf9c 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_read.h +++ b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_matlab_read.h @@ -81,7 +81,7 @@ fsm_declare_methods(vcl_complex<double>); vnl_matlab_header hdr; char *varname; bool data_read; - + bool need_swap; void read_hdr(); // internal work routine }; diff --git a/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/ItkVtkGlue/CMakeLists.txt b/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/ItkVtkGlue/CMakeLists.txt index b909ac5111..652d06b1d9 100644 --- a/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/ItkVtkGlue/CMakeLists.txt +++ b/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/ItkVtkGlue/CMakeLists.txt @@ -1,3 +1,8 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.4) +IF(COMMAND CMAKE_POLICY) + CMAKE_POLICY(SET CMP0003 NEW) +ENDIF(COMMAND CMAKE_POLICY) + PROJECT(ItkVtkGlue) OPTION(BUILD_WRAPPERS "Wrap library" OFF) diff --git a/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.h b/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.h index ca87d71d98..af044aac31 100644 --- a/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.h +++ b/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPyBuffer.h,v $ Language: C++ - Date: $Date: 2006-09-06 20:58:41 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-05-22 16:39:34 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. diff --git a/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx b/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx index e2fab069f3..0abfddc1e1 100644 --- a/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx +++ b/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPyBuffer.txx,v $ Language: C++ - Date: $Date: 2006-09-06 20:58:41 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-05-22 16:39:34 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -43,7 +43,7 @@ PyBuffer<TImage> image->Update(); - import_array(); + import_array1(0); PixelType * buffer = const_cast < PixelType * > ( image->GetBufferPointer() ); @@ -61,7 +61,7 @@ PyBuffer<TImage> int item_type = GetPyType(); // TODO find a way of doing this through pixel traits // figure out an appropriate type - PyObject * obj = PyArray_FromDimsAndData( ImageDimension, dimensions, item_type, data ); + PyObject * obj = PyArray_SimpleNewFromData( ImageDimension, dimensions, item_type, data ); return obj; } @@ -74,7 +74,7 @@ PyBuffer<TImage> ::GetImageFromArray( PyObject *obj ) { - import_array(); + import_array1(0); int element_type = GetPyType(); ///PyArray_DOUBLE; // change this with pixel traits. diff --git a/Utilities/ITK/itkConfigure.h.in b/Utilities/ITK/itkConfigure.h.in index 37a88d2109..02d90e51e3 100644 --- a/Utilities/ITK/itkConfigure.h.in +++ b/Utilities/ITK/itkConfigure.h.in @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConfigure.h.in,v $ Language: C++ - Date: $Date: 2008-09-13 14:23:58 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-05-07 14:03:33 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -79,10 +79,14 @@ #cmakedefine USE_FFTWD #cmakedefine ITK_USE_MINC2 #cmakedefine ITK_USE_OPTIMIZED_REGISTRATION_METHODS +#cmakedefine ITK_USE_REVIEW_STATISTICS #cmakedefine ITK_USE_CONSOLIDATED_MORPHOLOGY #cmakedefine ITK_USE_TRANSFORM_IO_FACTORIES #cmakedefine ITK_USE_ORIENTED_IMAGE_DIRECTION #cmakedefine ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE +#cmakedefine ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY +#cmakedefine ITK_USE_PORTABLE_ROUND +#cmakedefine ITK_USE_REGION_VALIDATION_IN_ITERATORS #cmakedefine ITK_USE_TEMPLATE_META_PROGRAMMING_LOOP_UNROLLING #cmakedefine ITK_USE_DEPRECATED_LEVELSET_INTERPOLATION #cmakedefine ITK_USE_REVIEW diff --git a/Utilities/ITK/itkIncludeDirectories.cmake b/Utilities/ITK/itkIncludeDirectories.cmake index 8b3507eabb..a3c6c01108 100644 --- a/Utilities/ITK/itkIncludeDirectories.cmake +++ b/Utilities/ITK/itkIncludeDirectories.cmake @@ -25,7 +25,6 @@ SET(ITK_INCLUDE_DIRS_BUILD_TREE ${ITK_INCLUDE_DIRS_BUILD_TREE} ${ITK_SOURCE_DIR}/Code/Numerics ${ITK_SOURCE_DIR}/Code/IO ${ITK_SOURCE_DIR}/Code/Numerics/FEM - ${ITK_SOURCE_DIR}/Code/Numerics/Statistics ${ITK_SOURCE_DIR}/Code/Numerics/NeuralNetworks ${ITK_SOURCE_DIR}/Code/SpatialObject ${ITK_SOURCE_DIR}/Utilities/MetaIO @@ -43,6 +42,13 @@ SET(ITK_INCLUDE_DIRS_BUILD_TREE ${ITK_INCLUDE_DIRS_BUILD_TREE} ${ITK_SOURCE_DIR}/Utilities ) + +IF( NOT ITK_USE_REVIEW_STATISTICS ) + SET( ITK_INCLUDE_DIRS_BUILD_TREE ${ITK_INCLUDE_DIRS_BUILD_TREE} + ${ITK_SOURCE_DIR}/Code/Numerics/Statistics ) +ENDIF( NOT ITK_USE_REVIEW_STATISTICS ) + + # For explicit instantiation. Probably should make it ${ITK_BINARY_DIR}/Code/Common IF(ITK_EXPLICIT_INSTANTIATION) SET(ITK_INCLUDE_DIRS_BUILD_TREE ${ITK_INCLUDE_DIRS_BUILD_TREE} @@ -102,8 +108,17 @@ IF(ITK_USE_REVIEW) SET(ITK_INCLUDE_DIRS_BUILD_TREE ${ITK_INCLUDE_DIRS_BUILD_TREE} ${ITK_SOURCE_DIR}/Code/Review ) + IF(ITK_USE_REVIEW_STATISTICS) + SET(ITK_INCLUDE_DIRS_BUILD_TREE ${ITK_INCLUDE_DIRS_BUILD_TREE} + ${ITK_SOURCE_DIR}/Code/Review/Statistics ) + ENDIF(ITK_USE_REVIEW_STATISTICS) ENDIF(ITK_USE_REVIEW) +IF( NOT ITK_USE_REVIEW_STATISTICS ) + SET(ITK_INCLUDE_RELATIVE_DIRS ${ITK_INCLUDE_RELATIVE_DIRS} Numerics/Statistics) +ENDIF( NOT ITK_USE_REVIEW_STATISTICS ) + + #----------------------------------------------------------------------------- # Include directories needed for .cxx files in ITK. These include @@ -127,7 +142,6 @@ SET(ITK_INCLUDE_RELATIVE_DIRS ${ITK_INCLUDE_RELATIVE_DIRS} Numerics IO Numerics/FEM - Numerics/Statistics Numerics/NeuralNetworks SpatialObject Utilities/MetaIO @@ -173,6 +187,10 @@ IF(ITK_USE_REVIEW) SET(ITK_INCLUDE_RELATIVE_DIRS ${ITK_INCLUDE_RELATIVE_DIRS} Review ) + IF(ITK_USE_REVIEW_STATISTICS) + SET(ITK_INCLUDE_RELATIVE_DIRS ${ITK_INCLUDE_RELATIVE_DIRS} + Review/Statistics ) + ENDIF(ITK_USE_REVIEW_STATISTICS) ENDIF(ITK_USE_REVIEW) -- GitLab