ImageDev

- Getting Started
- ImageDev Python
- ImageDev C#
- ImageDev C++
- Licensing Information
- Redistributable Files
- Processing
- Image Manipulation
- - Synthetic Images
  - - RandomImage2d
    - RandomImage3d
    - RandomGaussianImage2d
    - RandomGaussianImage3d
    - RadialFunctionImage2d
    - RadialFunctionImage3d
    - OrientedLinesImage2d
    - OrientedLinesImage3d
    - RandomSphereImage3d
    - BoxGridImage2d
    - BoxGridImage3d
    - WedgeMaskImage3d
    - PointSpreadFunctionImage3d
  - Image Editing
  - - ConvertImage
    - ResetImage
    - CopyImage
    - PasteImage2d
    - PasteImage3d
    - CropImage2d
    - CropImage3d
    - SampleImage2d
    - SampleImage3d
    - InterlaceFrames2d
    - DeinterlaceFrames2d
  - Stack Operations
  - - SequenceConcatenation
    - SequenceToMultispectral
    - SequenceToVolume
    - VolumeToSequence
    - MultispectralToSequence
    - GetSliceFromVolume3d
    - SetSliceToVolume3d
    - GetObliqueSliceFromVolume3d
    - ImageStackProjection3d
    - VolumeProjection3d
- Geometry And Matching
- - Geometric Transforms
  - - Shearing3d
    - TranslateImage2d
    - TranslateImage3d
    - Flip2d
    - Flip3d
    - FlipImage2d
    - FlipImage3d
    - TransposeImage2d
    - TransposeImage3d
    - SwapQuadrants
    - Rotate2d
    - Rotate3d
    - RotationGenerator3d
    - Resize2d
    - Resize3d
    - RescaleByFactor
    - RescaleImageByFactor
    - ResampleAffine2d
    - ResampleAffine3d
    - ResampleElastic2d
    - SurfaceUnfolding3d
  - Pattern Recognition
  - - BinaryCorrelation2d
    - CrossCorrelation2d
    - CorrelationByDifference2d
    - CorrelationBySignChange2d
  - Registration
  - - ImagePrealignment3d
    - AffineRegistration
    - ElasticRegistration2d
- Arithmetic And Logic
- - Arithmetical Operations
  - - AbsoluteValue
    - AbsoluteMaximumWithImage
    - ArithmeticOperationWithImage
    - ArithmeticOperationWithValue
    - BlendWithImage
    - BlendWithValue
    - DirectionalBlending2d
    - CombineByMask
    - ImageFormula
    - EigenDecomposition2d
    - EigenDecomposition3d
  - Logical Operations
  - - MaskImage
    - LogicalOperationWithImage
    - LogicalOperationWithValue
    - LogicalNot
    - InvertImage
    - BitShift
- Image Filtering
- - Grayscale Transforms
  - - RescaleIntensity
    - StackRescaleIntensity
    - MatchContrast
    - HistogramEqualization
    - Clahe2d
    - Clahe3d
    - AdaptiveHistogramEqualization
    - ApplyGrayscaleLut
    - BackgroundImage2d
    - RadialBackgroundImage2d
    - ShadingCorrection
    - Exponential
    - Logarithm
    - Square
    - SquareRoot
    - RingArtifactRemoval3d
    - BeamHardeningCorrection3d
  - Color Transforms
  - - ColorToLightness
    - GetColorChannel
    - ColorToGrayscale
    - GrayscaleToColor
    - ColorSpaceConversion
    - ColorAntialiasing2d
    - BayerToRgb2d
    - DecorrelationStretch2d
    - BlendAlphaChannelWithImage
    - BlendAlphaChannelWithValue
  - Smoothing And Denoising
  - - BoxFilter2d
    - BoxFilter3d
    - MedianFilter2d
    - MedianFilter3d
    - GaussianFilter2d
    - GaussianFilter3d
    - ExponentialFilter2d
    - RecursiveExponentialFilter2d
    - RecursiveExponentialFilter3d
    - NonLocalMeansFilter2d
    - NonLocalMeansFilter3d
    - CurvatureDrivenDiffusion
    - BilateralFilter2d
    - BilateralFilter3d
    - MajorityFilter2d
    - MajorityFilter3d
    - SigmaFilter2d
    - SigmaFilter3d
    - Despeckle2d
    - Despeckle3d
    - NagaoFilter2d
    - NagaoFilter3d
    - SnnFilter2d
    - SnnFilter3d
    - FlowInpainting
  - Sharpening
  - - Deblurring2d
    - Delineate2d
    - Delineate3d
    - UnsharpMasking2d
    - UnsharpMasking3d
    - Shade2d
    - RichardsonLucyDeconvolution
  - Texture Filters
  - - MeanFilter2d
    - MeanFilter3d
    - VarianceFilter2d
    - VarianceFilter3d
    - SkewnessFilter2d
    - SkewnessFilter3d
    - KurtosisFilter2d
    - KurtosisFilter3d
    - ContrastFilter2d
    - ContrastFilter3d
    - VariationFilter2d
    - VariationFilter3d
    - EnergyFilter2d
    - EnergyFilter3d
    - EntropyFilter2d
    - EntropyFilter3d
    - AutocorrelationFilter
    - LocalAutocorrelationFilter2d
    - ImageCurvature2d
    - ImageCurvature3d
    - StructureEnhancementFilter2d
    - StructureEnhancementFilter3d
    - ScaleSpaceLogFilter2d
    - ScaleSpaceLogFilter3d
  - Frequency Domain
  - - ComplexFft
    - ComplexFftInverse
    - ComplexCenteredFft
    - ComplexCenteredFftInverse
    - CartesianToPolar2d
    - PolarToCartesian2d
    - ConvolutionWithImage
    - ConvolutionWithImage2d
    - RadialFrequencyFilter2d
    - GaborFiltering2d
- Edge Detection
- - Gradient
  - - GradientOperator2d
    - GradientOperator3d
    - VectorToMagnitude2d
    - VectorToMagnitude3d
    - GradientVector2d
    - GradientVector3d
    - GradientMagnitude2d
    - GradientMagnitude3d
    - MorphologicalGradient2d
    - MorphologicalGradient3d
    - RadialGradientCentered2d
    - RadialGradientCentered3d
    - RadialGradientContour2d
    - RadialGradientContour3d
    - RadialGradientLabel2d
    - RadialGradientLabel3d
  - Laplacian
  - - DobFilter2d
    - DobFilter3d
    - MorphologicalLaplacian
    - RecursiveLaplacian2d
    - RecursiveLaplacian3d
  - Other Derivatives
  - - GaussianDerivative2d
    - GaussianDerivative3d
    - GaussianHessianMatrix2d
    - GaussianHessianMatrix3d
    - GaussianGradientTensor2d
    - GaussianGradientTensor3d
  - Edge Marking
  - - ImageLocalMaxima2d
    - ImageLocalMaxima3d
    - RidgeDetection
    - ZeroCrossings2d
    - DijkstraShortestPath2d
    - EigenvaluesToStructureness2d
    - EigenvaluesToStructureness3d
    - TensorVoting2d
    - CannyEdgeDetector2d
    - CannyEdgeDetector3d
- Image Segmentation
- - Binarization
  - - Thresholding
    - ThresholdingByCriterion
    - AutoThresholdingBright
    - AutoThresholdingDark
    - ColorThresholding
    - TopHat
    - FeatureAdaptiveThresholding
    - AdaptiveThresholding2d
    - AdaptiveThresholding3d
    - HysteresisThresholding
  - Labeling
  - - Labeling2d
    - Labeling3d
    - ReorderLabels
    - AssignLabel
    - AddObjectToLabel
    - GroupCloseLabelsl2d
  - Feature Selection
  - - KillBorder2d
    - KillBorder3d
    - RemoveSmallSpots
    - ObjectBoundaries
    - BinarySmoothing2d
    - BinarySmoothing3d
    - LabelInterfaces
  - Separating And Filling
  - - FillHoles2d
    - FillHoles3d
    - RemoveSmallHoles
    - FillImageBorder3d
    - ExpandLabelBoundaries
    - SeparateObjects
    - HExtremaWatershed
    - SeparateObjectsByBlock
    - HExtremaWatershedByBlock
    - ConvexHull2d
  - Region Growing
  - - MarkerBasedWatershed2d
    - MarkerBasedWatershed3d
    - MarkerBasedWatershedByBlock
    - MarkerBasedWatershedBasinsByBlock
    - ExpandLabelsOnBackground
    - FloodFillThreshold2d
    - FloodFillThreshold3d
    - Waterpixel
  - Computational Geometry
  - - PolylineResampler2d
    - PolylineResampler3d
    - PolylineExtrusion3d
    - SurfaceFitting3d
- Mathematical Morphology
- - Erosion And Dilation
  - - Erosion2d
    - Erosion3d
    - Dilation2d
    - Dilation3d
    - ErosionDisk2d
    - ErosionDisk3d
    - ErosionBall3d
    - DilationDisk2d
    - DilationDisk3d
    - DilationBall3d
    - ErosionLine2d
    - ErosionLine3d
    - DilationLine2d
    - DilationLine3d
    - ErosionColor2d
    - DilationColor2d
    - SelectiveErosion2d
    - SelectiveErosion3d
    - SelectiveDilation2d
    - SelectiveDilation3d
  - Opening And Closing
  - - Opening2d
    - Opening3d
    - Closing2d
    - Closing3d
    - OpeningDisk2d
    - OpeningDisk3d
    - OpeningBall3d
    - ClosingDisk2d
    - ClosingDisk3d
    - ClosingBall3d
    - OpeningLine2d
    - OpeningLine3d
    - ClosingLine2d
    - ClosingLine3d
    - OpeningLineMaximum
    - ClosingLineMinimum
    - OpeningColor2d
    - ClosingColor2d
    - OpeningByReconstruction2d
    - OpeningByReconstruction3d
    - ClosingByReconstruction2d
    - ClosingByReconstruction3d
    - OpeningDiskByReconstruction2d
    - OpeningBallByReconstruction3d
    - ClosingDiskByReconstruction2d
    - ClosingBallByReconstruction3d
    - SelectiveOpening2d
    - SelectiveOpening3d
    - SelectiveClosing2d
    - SelectiveClosing3d
  - Hit Or Miss And Skeleton
  - - Skeleton
    - Centerline3d
    - InfluenceZones
    - Centroid2d
    - EndPoints2d
    - EndPoints3d
    - Pruning2d
    - Pruning3d
    - IsolatedPoints2d
    - IsolatedPoints3d
    - TriplePoints2d
    - InteriorPoints2d
    - ApplyMorphologicalLut2d
    - ApplyMorphologicalLut3d
  - Geodesic Transformations
  - - ReconstructionFromMarkers2d
    - ReconstructionFromMarkers3d
    - GrayscaleReconstruction2d
    - GrayscaleReconstruction3d
    - GrayscaleFillHoles2d
    - GrayscaleFillHoles3d
    - HExtrema2d
    - HExtrema3d
    - RegionalExtrema2d
    - RegionalExtrema3d
    - UltimateErosion
  - Distance Maps
  - - DistanceMap2d
    - DistanceMap3d
    - EuclideanDistanceMap3d
    - EuclideanDistanceMap2d
    - GeodesicDistanceMap
    - ClosestBoundaryPoints2d
    - ClosestBoundaryPoints3d
    - TimeMap
    - LocalThicknessMap3d
    - GeodesicPropagation2d
    - GeodesicMaxima
    - GeodesicMinima
- Image Analysis
- - Image Measurements
  - - BinaryAnalysis
    - Area2d
    - Area3d
    - IntensityIntegral2d
    - IntensityIntegral3d
    - ObjectCount
    - DistanceMean2d
    - EulerNumber2d
    - EulerNumber3d
    - FractalDimension
    - CurvatureIntegrals3d
  - Image Statistics
  - - IntensityExtrema
    - IntensityStatistics
    - IntensityMaskedStatistics
    - IntensityHistogram
    - IntensityBinHistogram
    - AutoThresholdingValue
    - CompareImage
    - CompareValue
    - SimilarityMetricValue
    - SsimValue2d
    - SsimValue3d
    - RegionSimilarity
    - RadialIntensityProfile2d
    - RadialIntensityProfile3d
    - CylindricalIntensityProfile3d
    - RadialAutocorrelationProfile
    - Cooccurrence2d
    - MeasureGaussianNoise
    - LocalMaxima2d
    - LocalMaxima3d
    - PeakExtractor
    - LocalDensityMap2d
    - LocalDensityMap3d
    - SegmentationMetrics
  - Individual Measurements
  - - VolumeFractionByLabel
    - LabelCountByRegion
    - VolumeFractionByRegion
    - LabelAnalysis
    - LabelFiltering
    - LabelFilteringAnalysis
    - FilterAnalysis
    - MeasurementToImage
    - FilterByMeasurement
    - SieveLabeling
  - Moments And Orientations
  - - MomentsOfInertia2d
    - MomentsOfInertia3d
    - InertiaMoment2d
    - Eccentricity2d
    - OrientationMapFourier3d
    - OrientationMatchingFourier3d
  - Morphometry
  - - ObjectVolume
    - TotalImageVolume
    - ObjectBoundaryArea
    - TotalImageBoundaryArea
    - AverageObjectAreaPerSlice3d
    - AverageObjectCountPerSlice3d
    - ObjectImageRatio
    - ObjectSpecificSurface
    - ObjectSurfaceDensity
    - PorosityPercentage3d
    - FragmentationIndex
    - StructureModelIndex3d
    - AverageObjectThickness3d
    - AverageSpaceThickness3d
    - ObjectLinearDensity3d
    - DegreeOfAnisotropy
  - Propagation
  - - AxisPropagationBinary3d
    - AxisPropagationBinaryWithSeeds3d
    - AxisPropagationLabel3d
    - AxisPropagationLabelWithSeeds3d
    - AxisPropagationDistance3d
    - EstimateShortestPath3d
    - PercolationThreshold3d
    - AxisConnectivity3d
    - CentroidPathTortuosity3d
- Machine Learning
- - Classification
  - - AutoSegmentation3Phases
    - AutoIntensityClassification
    - SupervisedTextureClassification2d
    - SupervisedTextureClassification3d
    - TextureClassificationCreate
    - TextureClassificationTrain
    - TextureClassificationApply
  - Deep learning
  - - OnnxPredictionFiltering2d
    - OnnxPredictionFiltering3d
    - OnnxPredictionSegmentation2d
    - OnnxPredictionSegmentation3d
    - OnnxPredictionTwoOutputs2d
    - OnnxPredictionTwoOutputs3d
- Business Application
- - Dental
  - - DentalWallSegmentation3d
    - DentalMeshExtraction3d
    - DentalUnfolding3d
- IO
- - Image Data
  - - ReadVipImage
    - WriteVipImage
  - Algebraic Data
  - - ReadArrayXd
    - ReadArrayXi64
    - WriteArrayXd
    - WriteArrayXi64
  - Model
  - - ReadOnnxModel
- CUDA
- - Geometry And Matching
  - - CudaCrossCorrelation2d
    - CudaTemplateMatching3d
  - Image Filtering
  - - CudaBoxFilter2d
    - CudaMedianFilter2d
    - CudaGaussianFilter3d
    - CudaAdaptiveManifoldNlmFilter
  - Mathematical Morphology
  - - CudaErosion2d
    - CudaDilation2d
    - CudaOpening2d
    - CudaClosing2d
- Utilities
- Initialization
- Processing
- Syntax Check
- Visualization
- Data Object
- Image Data
- Kernels
- - MorphologicalKernel2d
  - MorphologicalKernel3d
  - MorphologicalLut2d
  - MorphologicalLut3d
- Model
- - TextureClassificationModel
  - OnnxModel
- Global Measurements
- - Image Measurements
  - - Area2dMsr
    - Area3dMsr
    - IntensityIntegral2dMsr
    - IntensityIntegral3dMsr
    - ObjectCountMsr
    - DistanceMeanMsr
    - Euler2dMsr
    - Euler3dMsr
    - FractalMsr
    - CurvatureIntegralsMsr
  - Image Statistics
  - - IntensityExtremaMsr
    - StatisticsMsr
    - IntensityHistogramMsr
    - IntensityBinHistogramMsr
    - CompareMsr
    - SimilarityMetricValueMsr
    - SsimValueMsr
    - RegionSimilarityMsr
    - SegmentationMetricsObjectMsr
    - SegmentationMetricsImageMsr
    - CylindricalIntensityProfileMsr
    - RadialIntensityProfileMsr
    - CorrelationMsr
    - CoocurrrenceMsr
    - GaussianNoiseMsr
    - LocalMaximaMsr
    - PeakExtractorMsr
  - Individual Measurements
  - - VolumeFractionByLabelMsr
    - LabelCountByRegionMsr
    - VolumeFractionByRegionMsr
  - Moments And Orientations
  - - MomentsOfInertia2dMsr
    - MomentsOfInertia3dMsr
    - MeanInertiaMomentMsr
    - Eccentricity2dMsr
    - LocalOrientation3dMsr
  - Morphometry
  - - ObjectVolumeMsr
    - ImageVolumeMsr
    - ObjectBoundaryAreaMsr
    - ImageBoundaryAreaMsr
    - AverageObjectAreaPerSliceMsr
    - AverageObjectCountPerSliceMsr
    - ObjectImageRatioMsr
    - ObjectSpecificSurfaceMsr
    - ObjectSurfaceDensityMsr
    - PorosityPercentageMsr
    - FragmentationMsr
    - StructureModelIndexMsr
    - AverageObjectThicknessMsr
    - AverageSpaceThicknessMsr
    - ObjectLinearDensityMsr
    - AnisotropyDegreeMsr
  - Propagation
  - - AxisPropagationBinary3dMsr
    - AxisPropagationLabel3dMsr
    - AxisPropagationDistance3dMsr
    - PercolationThreshold3dMsr
    - CentroidTortuosity3dMsr
  - Geometry And Matching
  - - CrossCorrelation2dMsr
  - Edge Detection
  - - CannyEdgeDetectorMsr
  - Image Segmentation
  - - AutoThresholdingMsr
    - AutoSegmentation3PhasesMsr
  - Mathematical Morphology
  - - ApplyMorphologicalLutMsr
- Analysis Measurements
- - AnalysisMsr
  - Measurement
  - Native Measurements
  - - Geometry
    - Feret
    - Intensity
    - Histogram
    - Inertia
    - Locate
    - Segment
    - Cooccurrence
  - CustomMeasurement
  - MeasurementAttributes
  - - Quantile
    - Histogram
    - Feret2d
    - Feret3d
    - NeighborCount
    - Cooccurrence
    - Breadth3d
  - MeasurementGroup
- Measurement Information
- - FieldInformation
  - CustomMeasurementInfo
- CUDA
- - CudaContext
- User Guide
- First Steps
- - Hello ImageDev
  - Initialize ImageDev
- Image Management
- - Create 2D Image
  - Create 3D Image
  - Data Transfer
- Standard Processing
- - Denoising
  - Thresholding
- Image Analysis
- - Global Analysis
  - Label Analysis
  - Measurement Browsing
  - Measurement Group
  - Custom Analysis
- Advanced Processing
- - Algorithm Tracking
- Typical Use Cases
- - Particle Analysis
  - Pore Analysis

# AffineRegistration

Computes the best transformation for the co-registration of two images, using an iterative optimization algorithm.
Access to parameter description

## Overview

This algorithm computes the best transformation for the co-registration of two images, using an iterative optimization algorithm.
The goal of registration is to find a transformation aligning a moving image onto a fixed image, starting from an initial transformation and by optimizing a similarity criterion between both images.
The estimated transformation can be a single translation, rigid (translation and rotation only), rigid with scale factors (isotropic or anisotropic along axis directions), or affine (including shear transformation).
Figure 1. Types of affine transformations
A hierarchical strategy is applied, starting at a coarse resampling of the data set, and proceeding to finer resolutions later on. Different similarity measurements like Euclidean distance, mutual information, and correlation can be selected. After each iteration a similarity score is computed, and the transformation is refined according to an optimizer algorithm. If this score cannot be computed, for instance when the resampling or step parameters are not adapted, it remains at its default value -1000.
The optimizer behavior depends on the optimizerStep parameter which affects the search extent, precision, and computation time. A small optimizerStep is recommended when a pre-alignment has been performed in order to be more precise and avoid driving the transformation at a wrong location.
Different optimization algorithms can be selected with the optimizerType parameter.
Note that none of them can guarantee reaching a global optimal alignment. The registration result is thus dependent on the initial alignment of the dataset, as well as the optimizer steps.
Furthermore, note that whatever the optimizerType chosen, a quasi-Newton optimizer is used on the finest level computed except if there is only one level. This optimizer is best suited for finer resolution levels in order for refining the transformation.

## Automatic configuration mode

By default, the coarsestResampling and optimizerStep parameters are automatically estimated from the fixed image properties. To know the value of the automatically calculated parameters, you can enable the verbose mode. In this case, the parameters will be displayed on the standard output at the beginning of the execution.
If moving and fixed images have different resolutions or sizes (for instance, in multi-modality cases), these settings may be inappropriate and cause the registration to fail. In this case, the autoParameterMode parameter should be set to false and both parameters should be manually set to relevant values so that the coarsest resolution level generates a representative volume (not made of too few voxels); the displacement step is precise enough to not skip the searched transformation.
If the two input images have been carefully pre-aligned, it is not recommended to perform the registration at a too low sub-resolution level. It would not only perform useless computations but could also drive the transformation at a wrong location and thus miss the right transformation. Consequently, the following recommendations can be applied in this case:

- Do not use automatic parameters; that is, set autoParameterMode to false.
- Set the coarsest resolution level at half of the original resolution; that is, set the coarsestResampling parameter to (2,2,2).
- Set the optimizerStep parameter with half of the voxel size of the fixed image for finest resolution and the voxel size of fixed image for coarsest resolution.

## Algorithm notifications

This algorithm can notify some information during the processing (progression, current transformation, similarity) and can be interrupted. The current transformation and the similarity can be intercepted with the progress data callback function defined by the setProgressDataCallback function. In this case, data sent to the callback will be a string containing a JSON structure including the current transformation and the similarity. Two attributes are encoded in this string:

- "matrix": An array of 16 values representing the current 4x4 transformation matrix.
- "similarity": A string representing the similarity metric corresponding to the current transformation.

For example, if the data argument of the ProgressDataCallback equals:

    { "matrix": [0.99, 0.07, -0.06, -0.63, -0.08, 0.99, -0.06, -0.20, 0.06, 0.07, 0.99, -0.48, 0, 0, 0, 1], "similarity": "0.73" }

It is means that registrating the moving image on the fixed image with the transformation matrix $$ \begin{bmatrix} 0.99 & 0.07 & -0.06 & -0.63 \\ 0.08 & 0.99 & -0.06 & 0.20\\ 0.06 & 0.07 & 0.99 & -0.48\\ 0 & 0 & 0 & 1 \\ \end{bmatrix} $$ provides a similarity score of 0.73.
Intercepting these events can be very useful to provide a visual feedback to the application user, but may slow down the execution.
More information about the callback functions can be found in the Processing interaction section.
References
The Correlation Ratio metric is explained in the following publication:

- A. Roche, G. Malandain, X. Pennec, and N. Ayache. "The Correlation Ratio as a New Similarity Measure for Multimodal Image Registration". INRIA Sophia Antipolis, EPIDAURE project, 1998.

The Normalized Mutual Information metric is based on the following publication:

- C. Studholme, D.L.G. Hill, D.J. Hawkes. "An Overlap Invariant Entropy Measure of 3D Medical Image Alignment". Pattern Recognition, vol. 32, pp. 71-86, 1999.

Further references include:

- P.A. Viola. "Alignment by Maximization of Mutual Information". Massachusetts Institute of Technology, Diss., 1995.
- A. Collignon, F. Maes, D. Delaere, D. Vandermeulen, P. Suetens, G. Marchal. "Automated Multi-modality Image Registration Based on Information Theory". IPMI, Dordrecht, Niederlande: Kluwer Academics, pp. 263-274, 1995.

See also

- ImagePrealignment3d
- ResampleElastic2d
- ResampleAffine3d

##
Function Syntax

This function returns outputTransform.

    // Function prototype
    iolink::Matrix4d
    affineRegistration( std::shared_ptr< iolink::ImageView > inputMovingImage,
                        std::shared_ptr< iolink::ImageView > inputFixedImage,
                        const iolink::Matrix4d& initialTransform,
                        bool autoParameterMode,
                        const iolink::Vector2d& optimizerStep,
                        const iolink::Vector2d& intensityRangeFixed,
                        const iolink::Vector2d& intensityRangeMoving,
                        const iolink::Vector3i32& coarsestResampling,
                        AffineRegistration::RangeModeFixed rangeModeFixed,
                        AffineRegistration::RangeModeMoving rangeModeMoving,
                        AffineRegistration::TransformType transformType,
                        bool ignoreFinestLevel,
                        AffineRegistration::MetricType metricType,
                        double thresholdOutside,
                        AffineRegistration::OptimizerType optimizerType );

This function returns outputTransform.

    // Function prototype.
    affine_registration(input_moving_image: idt.ImageType,
                        input_fixed_image: idt.ImageType,
                        initial_transform: Union[idt.NDArrayAny, iolink.Matrix4d, iolink.Matrix4f] = _np.identity(4),
                        auto_parameter_mode: bool = True,
                        optimizer_step: Union[Iterable[int], Iterable[float]] = [4, 0.5],
                        intensity_range_fixed: Union[Iterable[int], Iterable[float]] = [0, 65535],
                        intensity_range_moving: Union[Iterable[int], Iterable[float]] = [0, 65535],
                        coarsest_resampling: Iterable[int] = [8, 8, 8],
                        range_mode_fixed: AffineRegistration.RangeModeFixed = AffineRegistration.RangeModeFixed.R_MIN_MAX,
                        range_mode_moving: AffineRegistration.RangeModeMoving = AffineRegistration.RangeModeMoving.M_MIN_MAX,
                        transform_type: AffineRegistration.TransformType = AffineRegistration.TransformType.RIGID,
                        ignore_finest_level: bool = False,
                        metric_type: AffineRegistration.MetricType = AffineRegistration.MetricType.CORRELATION,
                        threshold_outside: float = 0.2,
                        optimizer_type: AffineRegistration.OptimizerType = AffineRegistration.OptimizerType.EXTENSIVE_DIRECTION) -> Union[idt.NDArrayFloat, None]

This function returns outputTransform.

    // Function prototype.
    public static IOLink.Matrix4d
    AffineRegistration( IOLink.ImageView inputMovingImage,
                        IOLink.ImageView inputFixedImage,
                        IOLink.Matrix4d initialTransform = null,
                        bool autoParameterMode = true,
                        double[] optimizerStep = null,
                        double[] intensityRangeFixed = null,
                        double[] intensityRangeMoving = null,
                        int[] coarsestResampling = null,
                        AffineRegistration.RangeModeFixed rangeModeFixed = ImageDev.AffineRegistration.RangeModeFixed.R_MIN_MAX,
                        AffineRegistration.RangeModeMoving rangeModeMoving = ImageDev.AffineRegistration.RangeModeMoving.M_MIN_MAX,
                        AffineRegistration.TransformType transformType = ImageDev.AffineRegistration.TransformType.RIGID,
                        bool ignoreFinestLevel = false,
                        AffineRegistration.MetricType metricType = ImageDev.AffineRegistration.MetricType.CORRELATION,
                        double thresholdOutside = 0.2,
                        AffineRegistration.OptimizerType optimizerType = ImageDev.AffineRegistration.OptimizerType.EXTENSIVE_DIRECTION );

##
Class Syntax

    // Command constructor.
    AffineRegistration();

    /// Gets the inputMovingImage parameter.
    /// The input moving image, also known as the model image.
    std::shared_ptr< iolink::ImageView > inputMovingImage() const;
    /// Sets the inputMovingImage parameter.
    /// The input moving image, also known as the model image.
    void setInputMovingImage( std::shared_ptr< iolink::ImageView > inputMovingImage );

    /// Gets the inputFixedImage parameter.
    /// The input fixed image, also known as the reference image.
    std::shared_ptr< iolink::ImageView > inputFixedImage() const;
    /// Sets the inputFixedImage parameter.
    /// The input fixed image, also known as the reference image.
    void setInputFixedImage( std::shared_ptr< iolink::ImageView > inputFixedImage );

    /// Gets the initialTransform parameter.
    /// The initial transformation, which pre-aligns the moving image onto the fixed image. It is represented by a 4x4 matrix.
    iolink::Matrix4d initialTransform() const;
    /// Sets the initialTransform parameter.
    /// The initial transformation, which pre-aligns the moving image onto the fixed image. It is represented by a 4x4 matrix.
    void setInitialTransform( const iolink::Matrix4d& initialTransform );

    /// Gets the autoParameterMode parameter.
    /// Determines whether or not the coarsest resampling factor and optimizer steps are automatically computed.
    bool autoParameterMode() const;
    /// Sets the autoParameterMode parameter.
    /// Determines whether or not the coarsest resampling factor and optimizer steps are automatically computed.
    void setAutoParameterMode( const bool& autoParameterMode );

    /// Gets the optimizerStep parameter.
    /// The step sizes, in world coordinates, used by the optimizer at coarsest and finest scales.
    iolink::Vector2d optimizerStep() const;
    /// Sets the optimizerStep parameter.
    /// The step sizes, in world coordinates, used by the optimizer at coarsest and finest scales.
    void setOptimizerStep( const iolink::Vector2d& optimizerStep );

    /// Gets the intensityRangeFixed parameter.
    /// The range [a,b] of gray values for the fixed data set.
    iolink::Vector2d intensityRangeFixed() const;
    /// Sets the intensityRangeFixed parameter.
    /// The range [a,b] of gray values for the fixed data set.
    void setIntensityRangeFixed( const iolink::Vector2d& intensityRangeFixed );

    /// Gets the intensityRangeMoving parameter.
    /// The range [a,b] of gray values for the moving data set.
    iolink::Vector2d intensityRangeMoving() const;
    /// Sets the intensityRangeMoving parameter.
    /// The range [a,b] of gray values for the moving data set.
    void setIntensityRangeMoving( const iolink::Vector2d& intensityRangeMoving );

    /// Gets the coarsestResampling parameter.
    /// The sub-sampling factor along each axis.
    iolink::Vector3i32 coarsestResampling() const;
    /// Sets the coarsestResampling parameter.
    /// The sub-sampling factor along each axis.
    void setCoarsestResampling( const iolink::Vector3i32& coarsestResampling );

    /// Gets the rangeModeFixed parameter.
    /// The way to define the intensity range to be considered by the algorithm in the moving image.
    AffineRegistration::RangeModeFixed rangeModeFixed() const;
    /// Sets the rangeModeFixed parameter.
    /// The way to define the intensity range to be considered by the algorithm in the moving image.
    void setRangeModeFixed( const AffineRegistration::RangeModeFixed& rangeModeFixed );

    /// Gets the rangeModeMoving parameter.
    /// The way to define the intensity range to be considered by the algorithm in the fixed image.
    AffineRegistration::RangeModeMoving rangeModeMoving() const;
    /// Sets the rangeModeMoving parameter.
    /// The way to define the intensity range to be considered by the algorithm in the fixed image.
    void setRangeModeMoving( const AffineRegistration::RangeModeMoving& rangeModeMoving );

    /// Gets the transformType parameter.
    /// Selects the type of transformation to estimate. It determines the number of degrees of freedom of the transformation.
    AffineRegistration::TransformType transformType() const;
    /// Sets the transformType parameter.
    /// Selects the type of transformation to estimate. It determines the number of degrees of freedom of the transformation.
    void setTransformType( const AffineRegistration::TransformType& transformType );

    /// Gets the ignoreFinestLevel parameter.
    /// Skip the finest level of the pyramid if equal to true.
    bool ignoreFinestLevel() const;
    /// Sets the ignoreFinestLevel parameter.
    /// Skip the finest level of the pyramid if equal to true.
    void setIgnoreFinestLevel( const bool& ignoreFinestLevel );

    /// Gets the metricType parameter.
    /// The metric type to compute.
    AffineRegistration::MetricType metricType() const;
    /// Sets the metricType parameter.
    /// The metric type to compute.
    void setMetricType( const AffineRegistration::MetricType& metricType );

    /// Gets the thresholdOutside parameter.
    /// The factor used to define the importance of images coverage.
    double thresholdOutside() const;
    /// Sets the thresholdOutside parameter.
    /// The factor used to define the importance of images coverage.
    void setThresholdOutside( const double& thresholdOutside );

    /// Gets the optimizerType parameter.
    /// The optimizer strategy.It determines the descent gradient method that is applied to iteratively modify the transformation to produce a better similarity measure.
    AffineRegistration::OptimizerType optimizerType() const;
    /// Sets the optimizerType parameter.
    /// The optimizer strategy.It determines the descent gradient method that is applied to iteratively modify the transformation to produce a better similarity measure.
    void setOptimizerType( const AffineRegistration::OptimizerType& optimizerType );

    /// Gets the outputTransform parameter.
    /// The output transformation, which aligns the moving image onto the fixed image. It is represented by a 4x4 matrix.
    iolink::Matrix4d outputTransform() const;

    // Method to launch the command.
    void execute();

    # Property of the inputMovingImage parameter.
    AffineRegistration.input_moving_image
    # Property of the inputFixedImage parameter.
    AffineRegistration.input_fixed_image
    # Property of the initialTransform parameter.
    AffineRegistration.initial_transform
    # Property of the autoParameterMode parameter.
    AffineRegistration.auto_parameter_mode
    # Property of the optimizerStep parameter.
    AffineRegistration.optimizer_step
    # Property of the intensityRangeFixed parameter.
    AffineRegistration.intensity_range_fixed
    # Property of the intensityRangeMoving parameter.
    AffineRegistration.intensity_range_moving
    # Property of the coarsestResampling parameter.
    AffineRegistration.coarsest_resampling
    # Property of the rangeModeFixed parameter.
    AffineRegistration.range_mode_fixed
    # Property of the rangeModeMoving parameter.
    AffineRegistration.range_mode_moving
    # Property of the transformType parameter.
    AffineRegistration.transform_type
    # Property of the ignoreFinestLevel parameter.
    AffineRegistration.ignore_finest_level
    # Property of the metricType parameter.
    AffineRegistration.metric_type
    # Property of the thresholdOutside parameter.
    AffineRegistration.threshold_outside
    # Property of the optimizerType parameter.
    AffineRegistration.optimizer_type
    # Property of the outputTransform parameter.
    AffineRegistration.output_transform

    // Method to launch the command.
    execute()

    // Command constructor.
    AffineRegistration()

    // Property of the inputMovingImage parameter.
    AffineRegistration.inputMovingImage
    // Property of the inputFixedImage parameter.
    AffineRegistration.inputFixedImage
    // Property of the initialTransform parameter.
    AffineRegistration.initialTransform
    // Property of the autoParameterMode parameter.
    AffineRegistration.autoParameterMode
    // Property of the optimizerStep parameter.
    AffineRegistration.optimizerStep
    // Property of the intensityRangeFixed parameter.
    AffineRegistration.intensityRangeFixed
    // Property of the intensityRangeMoving parameter.
    AffineRegistration.intensityRangeMoving
    // Property of the coarsestResampling parameter.
    AffineRegistration.coarsestResampling
    // Property of the rangeModeFixed parameter.
    AffineRegistration.rangeModeFixed
    // Property of the rangeModeMoving parameter.
    AffineRegistration.rangeModeMoving
    // Property of the transformType parameter.
    AffineRegistration.transformType
    // Property of the ignoreFinestLevel parameter.
    AffineRegistration.ignoreFinestLevel
    // Property of the metricType parameter.
    AffineRegistration.metricType
    // Property of the thresholdOutside parameter.
    AffineRegistration.thresholdOutside
    // Property of the optimizerType parameter.
    AffineRegistration.optimizerType
    // Property of the outputTransform parameter.
    AffineRegistration.outputTransform

    // Method to launch the command.
    Execute()

## Parameters

Parameter Name | Description | Type | Supported Values | Default Value
--- | --- | --- | --- | ---
| inputMovingImage | The input moving image, also known as the model image. | Image | Grayscale | nullptr
| inputFixedImage | The input fixed image, also known as the reference image. | Image | Grayscale | nullptr
| initialTransform | The initial transformation, which pre-aligns the moving image onto the fixed image. It is represented by a 4x4 matrix. It is important to note that this transformation is a direct transformation, which means that it maps a point from the moving image to the fixed image. For instance, the output transform of ImagePrealignment3d can be used as initial transform. | Matrix4d |  | IDENTITY
| transformType | Selects the type of transformation to estimate. It determines the number of degrees of freedom of the transformation.
TRANSLATION | Translation only.
RIGID | Rigid transformation consisting of translation and rotation.
RIGID_ISOTROPIC_SCALING | Transformation consisting of translation, rotation, and scale (only one scale for all dimensions).
RIGID_ANISOTROPIC_SCALING | Transformation consisting of translation, rotation, and scales (one scale per dimension).
AFFINE | Affine transformation consisting of translation, rotation, scale, and shear.
| Enumeration |  | RIGID
| metricType | The metric type to compute.
EUCLIDEAN | The mean squared difference between the gray values of the moving and fixed image. This metric estimates the Euclidean distance (the mean squared difference between the gray values of the moving and fixed image). It computes values between $-\infty$ and 0. Images closer to each other will have a metric closer to 0. $$Similarity=\frac{\sum -(I_{f} - I_{m})^2}{n}$$ where $I$ are the individual voxels and $n$ is the voxel count.
CORRELATION | The correlation ratio of the registered images. This metric computes values between 0 and 1. The case correlation ratio = 1 corresponds to the case of two identical and registered images. $$Similarity=\frac{\sum (I_m - \overline{I_m} ).(I_f - \overline{I_f} )} { \sqrt{\sum (I_m - \overline{I_m} )^2}.\sqrt{\sum(I_f - \overline{I_f} )^2}}$$ where $\overline{I}$ is the voxel mean.
NORMALIZED_MUTUAL_INFORMATION | The information shared by both images. This metric computes values between 0 and $\infty$. For instance, if images are independent, knowing $I_f$ does not give any information about $I_m$ and vice versa, so their mutual information is zero. The mutual information metrics, especially the normalized one, are recommended when images from different modalities (for example, CT and MRT) are to be registered. The mutual information is: $$Similarity=\frac{H(I_m)+H(I_f)}{H(I_m,I_f)}$$ Where $H(I_m)$ and $H(I_f)$ are the marginal entropies of the image histrograms and $H(I_m,I_f)$ is the joint entropy of the image histograms.
| Enumeration |  | CORRELATION
| optimizerType | The optimizer strategy.It determines the descent gradient method that is applied to iteratively modify the transformation to produce a better similarity measure. Extensive direction, best neighbor and line search strategies are best suited for registering two images that are highly misaligned. Quasi newton and conjugated gradients are particularly efficient strategies to refine a transformation after pre-alignment step.
BEST_NEIGHBOUR | This Best neighbour strategy. It is the most straighforward. It checks each each transformation value forward, then backward and then keeps the best result. After checking each transformation value, the same process is applied with a smaller step from the initial to the final step values given by the optimizerStep parameter.
EXTENSIVE_DIRECTION | The Extensive direction strategy. It is similar to the best neighbor by integrating a gradient factor concept. This strategy also estimates the transformation forward and backward, but then computes the metric difference and uses this result as a gradient factor. The next stages of this strategy are the same as the best neighbor by multiplying each step by the corresponding gradient factor.
LINE_SEARCH | The line search strategy. It is roughly the same as the extensive direction except that it keeps incrementing the transformation as long as the metric is improved.
QUASI_NEWTON | The quasi-Newton strategy. The descent gradient used to find the best transformation is based on the quasi-Newton method.
CONJUGATED_GRADIENTS | The conjugated gradients strategy. The descent gradient used to find the best transformation is based on the conjugated gradients method.
| Enumeration |  | EXTENSIVE_DIRECTION
| autoParameterMode | Determines whether or not the coarsest resampling factor and optimizer steps are automatically computed. If computed automatically, the optimizerStep, for the coarsest resolution is 1/5 of the size of the fixed image bounding box; for the finest resolution it is 1/6 of the fixed image voxel size. For the coarsestResampling, if the voxels of the fixed image are anisotropic (have a different size in the X, Y, and Z directions), the default resampling rates are around 8 and adapted in order to achieve isotropic voxels on the coarsest level. If the voxels of the fixed image are isotropic (have a the same size in the X, Y, and Z directions), the default resampling rate is computed in order to get at least 30 voxels along each direction. | Bool |  | true
| optimizerStep | The step sizes, in world coordinates, used by the optimizer at coarsest and finest scales. These step sizes refer to translations. For rotations, scalings, and shearings appropriate values are chosen accordingly. The first parameter is applied to the coarsest resolution level, the second to the finest level. Steps at intermediate levels are deduced from them. High step values cover a larger registration area but increase the risk of failure. If the input transformation already provides a reasonable alignment, the steps can be set smaller than the values given by the automatic mode in order to reduce computation time and risk of failure. Assuming a voxel size of (1,1,1) and a coarsestResampling of (8,8,8), these parameters correspond to a displacement of half a voxel for the coarsest and finest level. As it is rarely the case, it is essential to set this parameter in relation with the fixed image voxel size if the automatic mode is disabled. This parameter is ignored if autoParameterMode is set to true. | Vector2d | >0 | {4.f, 0.5f}
| coarsestResampling | The sub-sampling factor along each axis. This parameter defines the resampling rate for the coarsest resolution level where registration starts. The resampling rate refers to the fixed data set. For instance, a coarsest resampling factor of 8 means that one voxel at the coarsest level of the fixed image corresponds to 8 voxels at its finest level. If the voxel sizes of the moving and fixed image differ, the resampling rates applied to the moving image are adjusted in order to achieve similar voxel sizes as for the fixed image at a same level. This resampling factor is specified for each dimension of the input volume. This parameter is ignored if autoParameterMode is set to true. | Vector3i32 | >0 | {8, 8, 8}
| ignoreFinestLevel | Skip the finest level of the pyramid if equal to true. | Bool |  | false
| rangeModeMoving | The way to define the intensity range to be considered by the algorithm in the fixed image.
M_MIN_MAX | The intensity range of the moving image is between the minimum and the maximum of the image intensities.
M_OTHER | The intensity range of the moving image is between user-defined bounds [a,b].
| Enumeration |  | M_MIN_MAX
| intensityRangeMoving | The range [a,b] of gray values for the moving data set. It works similarly to its fixed data set counterpart parameter. This parameter is ignored if the rangeModeMoving parameter is set to M_MIN_MAX | Vector2d | Any value | {0.f, 65535.f}
| rangeModeFixed | The way to define the intensity range to be considered by the algorithm in the moving image.
R_MIN_MAX | The intensity range of the fixed image is between the minimum and the maximum of the image intensities.
R_OTHER | The intensity range of the fixed image is between user-defined bounds [a,b].
| Enumeration |  | R_MIN_MAX
| intensityRangeFixed | The range [a,b] of gray values for the fixed data set. With the Mutual information metrics, gray values outside the range are sorted into the first or last histogram bin, respectively. With the Correlation metric, voxels with gray values outside the range are ignored. This parameter is ignored with the Euclidean metric or if the rangeModeFixed parameter is set to R_MIN_MAX. | Vector2d | Any value | {0.f, 65535.f}
| thresholdOutside | The factor used to define the importance of images coverage. The final model position can have different overlaps with the reference data set. For example, the model can lie completely inside the reference, or it can share only a small overlapping area. Overlapping area refers to the space that is common to the bounding boxes of both data sets. This parameter lets you use your prior knowledge about the overlap. Its values are between 0 and 1. If you expect that the model and the reference should have a large overlap, then set a large value. Due to numerical errors, it is not recommended to set the threshold value too close to 1. Values around 0.8 should be suitable. Otherwise, if you know that probably only small parts overlap, then use a small value or even zero. The higher the value, the stronger is the decrease of the metric value if the model has parts outside the bounding box of the reference. If an intensity range is selected with the Correlation or Mutual information metrics, the computed metric value can be radically lowered. In this case, the threshold must be thus reduced proportionally to the amount of data represented by the selected range. | Float64 | >0 | 0.2
| outputTransform | The output transformation, which aligns the moving image onto the fixed image. It is represented by a 4x4 matrix. It is important to note that this transformation is a direct transformation, which means that it maps a point from the moving image to the fixed image. It should be inverted before applying it to the moving image using the ResampleAffine3d algorithm in order to match it to the fixed image. | Matrix4d |  | IDENTITY

Parameter Name | Description | Type | Supported Values | Default Value
--- | --- | --- | --- | ---
| input_moving_image | The input moving image, also known as the model image. | image | Grayscale | None
| input_fixed_image | The input fixed image, also known as the reference image. | image | Grayscale | None
| initial_transform | The initial transformation, which pre-aligns the moving image onto the fixed image. It is represented by a 4x4 matrix. It is important to note that this transformation is a direct transformation, which means that it maps a point from the moving image to the fixed image. For instance, the output transform of ImagePrealignment3d can be used as initial transform. | matrix |  | _np.identity(4)
| transform_type | Selects the type of transformation to estimate. It determines the number of degrees of freedom of the transformation.
TRANSLATION | Translation only.
RIGID | Rigid transformation consisting of translation and rotation.
RIGID_ISOTROPIC_SCALING | Transformation consisting of translation, rotation, and scale (only one scale for all dimensions).
RIGID_ANISOTROPIC_SCALING | Transformation consisting of translation, rotation, and scales (one scale per dimension).
AFFINE | Affine transformation consisting of translation, rotation, scale, and shear.
| enumeration |  | RIGID
| metric_type | The metric type to compute.
EUCLIDEAN | The mean squared difference between the gray values of the moving and fixed image. This metric estimates the Euclidean distance (the mean squared difference between the gray values of the moving and fixed image). It computes values between $-\infty$ and 0. Images closer to each other will have a metric closer to 0. $$Similarity=\frac{\sum -(I_{f} - I_{m})^2}{n}$$ where $I$ are the individual voxels and $n$ is the voxel count.
CORRELATION | The correlation ratio of the registered images. This metric computes values between 0 and 1. The case correlation ratio = 1 corresponds to the case of two identical and registered images. $$Similarity=\frac{\sum (I_m - \overline{I_m} ).(I_f - \overline{I_f} )} { \sqrt{\sum (I_m - \overline{I_m} )^2}.\sqrt{\sum(I_f - \overline{I_f} )^2}}$$ where $\overline{I}$ is the voxel mean.
NORMALIZED_MUTUAL_INFORMATION | The information shared by both images. This metric computes values between 0 and $\infty$. For instance, if images are independent, knowing $I_f$ does not give any information about $I_m$ and vice versa, so their mutual information is zero. The mutual information metrics, especially the normalized one, are recommended when images from different modalities (for example, CT and MRT) are to be registered. The mutual information is: $$Similarity=\frac{H(I_m)+H(I_f)}{H(I_m,I_f)}$$ Where $H(I_m)$ and $H(I_f)$ are the marginal entropies of the image histrograms and $H(I_m,I_f)$ is the joint entropy of the image histograms.
| enumeration |  | CORRELATION
| optimizer_type | The optimizer strategy.It determines the descent gradient method that is applied to iteratively modify the transformation to produce a better similarity measure. Extensive direction, best neighbor and line search strategies are best suited for registering two images that are highly misaligned. Quasi newton and conjugated gradients are particularly efficient strategies to refine a transformation after pre-alignment step.
BEST_NEIGHBOUR | This Best neighbour strategy. It is the most straighforward. It checks each each transformation value forward, then backward and then keeps the best result. After checking each transformation value, the same process is applied with a smaller step from the initial to the final step values given by the optimizerStep parameter.
EXTENSIVE_DIRECTION | The Extensive direction strategy. It is similar to the best neighbor by integrating a gradient factor concept. This strategy also estimates the transformation forward and backward, but then computes the metric difference and uses this result as a gradient factor. The next stages of this strategy are the same as the best neighbor by multiplying each step by the corresponding gradient factor.
LINE_SEARCH | The line search strategy. It is roughly the same as the extensive direction except that it keeps incrementing the transformation as long as the metric is improved.
QUASI_NEWTON | The quasi-Newton strategy. The descent gradient used to find the best transformation is based on the quasi-Newton method.
CONJUGATED_GRADIENTS | The conjugated gradients strategy. The descent gradient used to find the best transformation is based on the conjugated gradients method.
| enumeration |  | EXTENSIVE_DIRECTION
| auto_parameter_mode | Determines whether or not the coarsest resampling factor and optimizer steps are automatically computed. If computed automatically, the optimizerStep, for the coarsest resolution is 1/5 of the size of the fixed image bounding box; for the finest resolution it is 1/6 of the fixed image voxel size. For the coarsestResampling, if the voxels of the fixed image are anisotropic (have a different size in the X, Y, and Z directions), the default resampling rates are around 8 and adapted in order to achieve isotropic voxels on the coarsest level. If the voxels of the fixed image are isotropic (have a the same size in the X, Y, and Z directions), the default resampling rate is computed in order to get at least 30 voxels along each direction. | bool |  | True
| optimizer_step | The step sizes, in world coordinates, used by the optimizer at coarsest and finest scales. These step sizes refer to translations. For rotations, scalings, and shearings appropriate values are chosen accordingly. The first parameter is applied to the coarsest resolution level, the second to the finest level. Steps at intermediate levels are deduced from them. High step values cover a larger registration area but increase the risk of failure. If the input transformation already provides a reasonable alignment, the steps can be set smaller than the values given by the automatic mode in order to reduce computation time and risk of failure. Assuming a voxel size of (1,1,1) and a coarsestResampling of (8,8,8), these parameters correspond to a displacement of half a voxel for the coarsest and finest level. As it is rarely the case, it is essential to set this parameter in relation with the fixed image voxel size if the automatic mode is disabled. This parameter is ignored if autoParameterMode is set to true. | vector2d | >0 | [4, 0.5]
| coarsest_resampling | The sub-sampling factor along each axis. This parameter defines the resampling rate for the coarsest resolution level where registration starts. The resampling rate refers to the fixed data set. For instance, a coarsest resampling factor of 8 means that one voxel at the coarsest level of the fixed image corresponds to 8 voxels at its finest level. If the voxel sizes of the moving and fixed image differ, the resampling rates applied to the moving image are adjusted in order to achieve similar voxel sizes as for the fixed image at a same level. This resampling factor is specified for each dimension of the input volume. This parameter is ignored if autoParameterMode is set to true. | vector3i32 | >0 | [8, 8, 8]
| ignore_finest_level | Skip the finest level of the pyramid if equal to true. | bool |  | False
| range_mode_moving | The way to define the intensity range to be considered by the algorithm in the fixed image.
M_MIN_MAX | The intensity range of the moving image is between the minimum and the maximum of the image intensities.
M_OTHER | The intensity range of the moving image is between user-defined bounds [a,b].
| enumeration |  | M_MIN_MAX
| intensity_range_moving | The range [a,b] of gray values for the moving data set. It works similarly to its fixed data set counterpart parameter. This parameter is ignored if the rangeModeMoving parameter is set to M_MIN_MAX | vector2d | Any value | [0, 65535]
| range_mode_fixed | The way to define the intensity range to be considered by the algorithm in the moving image.
R_MIN_MAX | The intensity range of the fixed image is between the minimum and the maximum of the image intensities.
R_OTHER | The intensity range of the fixed image is between user-defined bounds [a,b].
| enumeration |  | R_MIN_MAX
| intensity_range_fixed | The range [a,b] of gray values for the fixed data set. With the Mutual information metrics, gray values outside the range are sorted into the first or last histogram bin, respectively. With the Correlation metric, voxels with gray values outside the range are ignored. This parameter is ignored with the Euclidean metric or if the rangeModeFixed parameter is set to R_MIN_MAX. | vector2d | Any value | [0, 65535]
| threshold_outside | The factor used to define the importance of images coverage. The final model position can have different overlaps with the reference data set. For example, the model can lie completely inside the reference, or it can share only a small overlapping area. Overlapping area refers to the space that is common to the bounding boxes of both data sets. This parameter lets you use your prior knowledge about the overlap. Its values are between 0 and 1. If you expect that the model and the reference should have a large overlap, then set a large value. Due to numerical errors, it is not recommended to set the threshold value too close to 1. Values around 0.8 should be suitable. Otherwise, if you know that probably only small parts overlap, then use a small value or even zero. The higher the value, the stronger is the decrease of the metric value if the model has parts outside the bounding box of the reference. If an intensity range is selected with the Correlation or Mutual information metrics, the computed metric value can be radically lowered. In this case, the threshold must be thus reduced proportionally to the amount of data represented by the selected range. | float64 | >0 | 0.2
| output_transform | The output transformation, which aligns the moving image onto the fixed image. It is represented by a 4x4 matrix. It is important to note that this transformation is a direct transformation, which means that it maps a point from the moving image to the fixed image. It should be inverted before applying it to the moving image using the ResampleAffine3d algorithm in order to match it to the fixed image. | matrix |  | _np.identity(4)

Parameter Name | Description | Type | Supported Values | Default Value
--- | --- | --- | --- | ---
| inputMovingImage | The input moving image, also known as the model image. | Image | Grayscale | null
| inputFixedImage | The input fixed image, also known as the reference image. | Image | Grayscale | null
| initialTransform | The initial transformation, which pre-aligns the moving image onto the fixed image. It is represented by a 4x4 matrix. It is important to note that this transformation is a direct transformation, which means that it maps a point from the moving image to the fixed image. For instance, the output transform of ImagePrealignment3d can be used as initial transform. | Matrix4d |  | IDENTITY
| transformType | Selects the type of transformation to estimate. It determines the number of degrees of freedom of the transformation.
TRANSLATION | Translation only.
RIGID | Rigid transformation consisting of translation and rotation.
RIGID_ISOTROPIC_SCALING | Transformation consisting of translation, rotation, and scale (only one scale for all dimensions).
RIGID_ANISOTROPIC_SCALING | Transformation consisting of translation, rotation, and scales (one scale per dimension).
AFFINE | Affine transformation consisting of translation, rotation, scale, and shear.
| Enumeration |  | RIGID
| metricType | The metric type to compute.
EUCLIDEAN | The mean squared difference between the gray values of the moving and fixed image. This metric estimates the Euclidean distance (the mean squared difference between the gray values of the moving and fixed image). It computes values between $-\infty$ and 0. Images closer to each other will have a metric closer to 0. $$Similarity=\frac{\sum -(I_{f} - I_{m})^2}{n}$$ where $I$ are the individual voxels and $n$ is the voxel count.
CORRELATION | The correlation ratio of the registered images. This metric computes values between 0 and 1. The case correlation ratio = 1 corresponds to the case of two identical and registered images. $$Similarity=\frac{\sum (I_m - \overline{I_m} ).(I_f - \overline{I_f} )} { \sqrt{\sum (I_m - \overline{I_m} )^2}.\sqrt{\sum(I_f - \overline{I_f} )^2}}$$ where $\overline{I}$ is the voxel mean.
NORMALIZED_MUTUAL_INFORMATION | The information shared by both images. This metric computes values between 0 and $\infty$. For instance, if images are independent, knowing $I_f$ does not give any information about $I_m$ and vice versa, so their mutual information is zero. The mutual information metrics, especially the normalized one, are recommended when images from different modalities (for example, CT and MRT) are to be registered. The mutual information is: $$Similarity=\frac{H(I_m)+H(I_f)}{H(I_m,I_f)}$$ Where $H(I_m)$ and $H(I_f)$ are the marginal entropies of the image histrograms and $H(I_m,I_f)$ is the joint entropy of the image histograms.
| Enumeration |  | CORRELATION
| optimizerType | The optimizer strategy.It determines the descent gradient method that is applied to iteratively modify the transformation to produce a better similarity measure. Extensive direction, best neighbor and line search strategies are best suited for registering two images that are highly misaligned. Quasi newton and conjugated gradients are particularly efficient strategies to refine a transformation after pre-alignment step.
BEST_NEIGHBOUR | This Best neighbour strategy. It is the most straighforward. It checks each each transformation value forward, then backward and then keeps the best result. After checking each transformation value, the same process is applied with a smaller step from the initial to the final step values given by the optimizerStep parameter.
EXTENSIVE_DIRECTION | The Extensive direction strategy. It is similar to the best neighbor by integrating a gradient factor concept. This strategy also estimates the transformation forward and backward, but then computes the metric difference and uses this result as a gradient factor. The next stages of this strategy are the same as the best neighbor by multiplying each step by the corresponding gradient factor.
LINE_SEARCH | The line search strategy. It is roughly the same as the extensive direction except that it keeps incrementing the transformation as long as the metric is improved.
QUASI_NEWTON | The quasi-Newton strategy. The descent gradient used to find the best transformation is based on the quasi-Newton method.
CONJUGATED_GRADIENTS | The conjugated gradients strategy. The descent gradient used to find the best transformation is based on the conjugated gradients method.
| Enumeration |  | EXTENSIVE_DIRECTION
| autoParameterMode | Determines whether or not the coarsest resampling factor and optimizer steps are automatically computed. If computed automatically, the optimizerStep, for the coarsest resolution is 1/5 of the size of the fixed image bounding box; for the finest resolution it is 1/6 of the fixed image voxel size. For the coarsestResampling, if the voxels of the fixed image are anisotropic (have a different size in the X, Y, and Z directions), the default resampling rates are around 8 and adapted in order to achieve isotropic voxels on the coarsest level. If the voxels of the fixed image are isotropic (have a the same size in the X, Y, and Z directions), the default resampling rate is computed in order to get at least 30 voxels along each direction. | Bool |  | true
| optimizerStep | The step sizes, in world coordinates, used by the optimizer at coarsest and finest scales. These step sizes refer to translations. For rotations, scalings, and shearings appropriate values are chosen accordingly. The first parameter is applied to the coarsest resolution level, the second to the finest level. Steps at intermediate levels are deduced from them. High step values cover a larger registration area but increase the risk of failure. If the input transformation already provides a reasonable alignment, the steps can be set smaller than the values given by the automatic mode in order to reduce computation time and risk of failure. Assuming a voxel size of (1,1,1) and a coarsestResampling of (8,8,8), these parameters correspond to a displacement of half a voxel for the coarsest and finest level. As it is rarely the case, it is essential to set this parameter in relation with the fixed image voxel size if the automatic mode is disabled. This parameter is ignored if autoParameterMode is set to true. | Vector2d | >0 | {4f, 0.5f}
| coarsestResampling | The sub-sampling factor along each axis. This parameter defines the resampling rate for the coarsest resolution level where registration starts. The resampling rate refers to the fixed data set. For instance, a coarsest resampling factor of 8 means that one voxel at the coarsest level of the fixed image corresponds to 8 voxels at its finest level. If the voxel sizes of the moving and fixed image differ, the resampling rates applied to the moving image are adjusted in order to achieve similar voxel sizes as for the fixed image at a same level. This resampling factor is specified for each dimension of the input volume. This parameter is ignored if autoParameterMode is set to true. | Vector3i32 | >0 | {8, 8, 8}
| ignoreFinestLevel | Skip the finest level of the pyramid if equal to true. | Bool |  | false
| rangeModeMoving | The way to define the intensity range to be considered by the algorithm in the fixed image.
M_MIN_MAX | The intensity range of the moving image is between the minimum and the maximum of the image intensities.
M_OTHER | The intensity range of the moving image is between user-defined bounds [a,b].
| Enumeration |  | M_MIN_MAX
| intensityRangeMoving | The range [a,b] of gray values for the moving data set. It works similarly to its fixed data set counterpart parameter. This parameter is ignored if the rangeModeMoving parameter is set to M_MIN_MAX | Vector2d | Any value | {0f, 65535f}
| rangeModeFixed | The way to define the intensity range to be considered by the algorithm in the moving image.
R_MIN_MAX | The intensity range of the fixed image is between the minimum and the maximum of the image intensities.
R_OTHER | The intensity range of the fixed image is between user-defined bounds [a,b].
| Enumeration |  | R_MIN_MAX
| intensityRangeFixed | The range [a,b] of gray values for the fixed data set. With the Mutual information metrics, gray values outside the range are sorted into the first or last histogram bin, respectively. With the Correlation metric, voxels with gray values outside the range are ignored. This parameter is ignored with the Euclidean metric or if the rangeModeFixed parameter is set to R_MIN_MAX. | Vector2d | Any value | {0f, 65535f}
| thresholdOutside | The factor used to define the importance of images coverage. The final model position can have different overlaps with the reference data set. For example, the model can lie completely inside the reference, or it can share only a small overlapping area. Overlapping area refers to the space that is common to the bounding boxes of both data sets. This parameter lets you use your prior knowledge about the overlap. Its values are between 0 and 1. If you expect that the model and the reference should have a large overlap, then set a large value. Due to numerical errors, it is not recommended to set the threshold value too close to 1. Values around 0.8 should be suitable. Otherwise, if you know that probably only small parts overlap, then use a small value or even zero. The higher the value, the stronger is the decrease of the metric value if the model has parts outside the bounding box of the reference. If an intensity range is selected with the Correlation or Mutual information metrics, the computed metric value can be radically lowered. In this case, the threshold must be thus reduced proportionally to the amount of data represented by the selected range. | Float64 | >0 | 0.2
| outputTransform | The output transformation, which aligns the moving image onto the fixed image. It is represented by a 4x4 matrix. It is important to note that this transformation is a direct transformation, which means that it maps a point from the moving image to the fixed image. It should be inverted before applying it to the moving image using the ResampleAffine3d algorithm in order to match it to the fixed image. | Matrix4d |  | IDENTITY

## Object Examples

    auto polystyrene = ioformat::readImage( std::string( IMAGEDEVDATA_IMAGES_FOLDER ) + "polystyrene.tif" );

    AffineRegistration affineRegistrationAlgo;
    affineRegistrationAlgo.setInputMovingImage( polystyrene );
    affineRegistrationAlgo.setInputFixedImage( polystyrene );
    affineRegistrationAlgo.setInitialTransform( iolink::Matrix4d::identity() );
    affineRegistrationAlgo.setAutoParameterMode( true );
    affineRegistrationAlgo.setOptimizerStep( {4, 0.5} );
    affineRegistrationAlgo.setIntensityRangeFixed( {0, 65535} );
    affineRegistrationAlgo.setIntensityRangeMoving( {0, 65535} );
    affineRegistrationAlgo.setCoarsestResampling( {8, 8, 8} );
    affineRegistrationAlgo.setRangeModeFixed( AffineRegistration::RangeModeFixed::R_MIN_MAX );
    affineRegistrationAlgo.setRangeModeMoving( AffineRegistration::RangeModeMoving::M_MIN_MAX );
    affineRegistrationAlgo.setTransformType( AffineRegistration::TransformType::RIGID );
    affineRegistrationAlgo.setIgnoreFinestLevel( false );
    affineRegistrationAlgo.setMetricType( AffineRegistration::MetricType::CORRELATION );
    affineRegistrationAlgo.setThresholdOutside( 0.1 );
    affineRegistrationAlgo.setOptimizerType( AffineRegistration::OptimizerType::EXTENSIVE_DIRECTION );
    affineRegistrationAlgo.execute();

    std::cout << "outputTransform:" << affineRegistrationAlgo.outputTransform().toString();

    polystyrene = ioformat.read_image(imagedev_data.get_image_path("polystyrene.tif"))

    affine_registration_algo = imagedev.AffineRegistration()
    affine_registration_algo.input_moving_image = polystyrene
    affine_registration_algo.input_fixed_image = polystyrene
    affine_registration_algo.initial_transform = np.identity(4)
    affine_registration_algo.auto_parameter_mode = True
    affine_registration_algo.optimizer_step = [4, 0.5]
    affine_registration_algo.intensity_range_fixed = [0, 65535]
    affine_registration_algo.intensity_range_moving = [0, 65535]
    affine_registration_algo.coarsest_resampling = [8, 8, 8]
    affine_registration_algo.range_mode_fixed = imagedev.AffineRegistration.R_MIN_MAX
    affine_registration_algo.range_mode_moving = imagedev.AffineRegistration.M_MIN_MAX
    affine_registration_algo.transform_type = imagedev.AffineRegistration.RIGID
    affine_registration_algo.ignore_finest_level = False
    affine_registration_algo.metric_type = imagedev.AffineRegistration.CORRELATION
    affine_registration_algo.threshold_outside = 0.1
    affine_registration_algo.optimizer_type = imagedev.AffineRegistration.EXTENSIVE_DIRECTION
    affine_registration_algo.execute()

    print("output_transform:", str(affine_registration_algo.output_transform))

    ImageView polystyrene = ViewIO.ReadImage( @"Data/images/polystyrene.tif" );
    IOLink.Matrix4d initialTransform = IOLink.Matrix4d.Identity();

    AffineRegistration affineRegistrationAlgo = new AffineRegistration
    {
        inputMovingImage = polystyrene,
        inputFixedImage = polystyrene,
        initialTransform = initialTransform,
        autoParameterMode = true,
        optimizerStep = new double[]{4, 0.5},
        intensityRangeFixed = new double[]{0, 65535},
        intensityRangeMoving = new double[]{0, 65535},
        coarsestResampling = new int[]{8, 8, 8},
        rangeModeFixed = AffineRegistration.RangeModeFixed.R_MIN_MAX,
        rangeModeMoving = AffineRegistration.RangeModeMoving.M_MIN_MAX,
        transformType = AffineRegistration.TransformType.RIGID,
        ignoreFinestLevel = false,
        metricType = AffineRegistration.MetricType.CORRELATION,
        thresholdOutside = 0.1,
        optimizerType = AffineRegistration.OptimizerType.EXTENSIVE_DIRECTION
    };
    affineRegistrationAlgo.Execute();

    Console.WriteLine( "outputTransform:" + affineRegistrationAlgo.outputTransform.ToString() );

## Function Examples

    auto polystyrene = ioformat::readImage( std::string( IMAGEDEVDATA_IMAGES_FOLDER ) + "polystyrene.tif" );

    auto result = affineRegistration( polystyrene, polystyrene, iolink::Matrix4d::identity(), true, {4, 0.5}, {0, 65535}, {0, 65535}, {8, 8, 8}, AffineRegistration::RangeModeFixed::R_MIN_MAX, AffineRegistration::RangeModeMoving::M_MIN_MAX, AffineRegistration::TransformType::RIGID, false, AffineRegistration::MetricType::CORRELATION, 0.1, AffineRegistration::OptimizerType::EXTENSIVE_DIRECTION );

    std::cout << "outputTransform:" << result.toString();

    polystyrene = ioformat.read_image(imagedev_data.get_image_path("polystyrene.tif"))

    result = imagedev.affine_registration(polystyrene, polystyrene, np.identity(4), True, [4, 0.5], [0, 65535], [0, 65535], [8, 8, 8], imagedev.AffineRegistration.R_MIN_MAX, imagedev.AffineRegistration.M_MIN_MAX, imagedev.AffineRegistration.RIGID, False, imagedev.AffineRegistration.CORRELATION, 0.1, imagedev.AffineRegistration.EXTENSIVE_DIRECTION)

    print("output_transform:", str(result))

    ImageView polystyrene = ViewIO.ReadImage( @"Data/images/polystyrene.tif" );
    IOLink.Matrix4d initialTransform = IOLink.Matrix4d.Identity();

    IOLink.Matrix4d result = Processing.AffineRegistration( polystyrene, polystyrene, initialTransform, true, new double[]{4, 0.5}, new double[]{0, 65535}, new double[]{0, 65535}, new int[]{8, 8, 8}, AffineRegistration.RangeModeFixed.R_MIN_MAX, AffineRegistration.RangeModeMoving.M_MIN_MAX, AffineRegistration.TransformType.RIGID, false, AffineRegistration.MetricType.CORRELATION, 0.1, AffineRegistration.OptimizerType.EXTENSIVE_DIRECTION );

    Console.WriteLine( "outputTransform:" + result.ToString() );

© 2025 Thermo Fisher Scientific Inc. All rights reserved.