1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20""" A SimpleITK example demonstrating image registration using the
21 DisplacementFieldTransform and the JointHistogramMutualInformation
22 metric. """
23
24import sys
25import os
26import SimpleITK as sitk
27
28
29def command_iteration(method):
30 """ Callback invoked each iteration. """
31 if method.GetOptimizerIteration() == 0:
32 print(f"\tLevel: {method.GetCurrentLevel()}")
33 print(f"\tScales: {method.GetOptimizerScales()}")
34 print(f"#{method.GetOptimizerIteration()}")
35 print(f"\tMetric Value: {method.GetMetricValue():10.5f}")
36 print(f"\tLearningRate: {method.GetOptimizerLearningRate():10.5f}")
37 if method.GetOptimizerConvergenceValue() != sys.float_info.max:
38 print("\tConvergence Value: " + f"{method.GetOptimizerConvergenceValue():.5e}")
39
40
41def command_multiresolution_iteration(method):
42 """ Callback invoked at the end of each multi-resolution level. """
43 print(f"\tStop Condition: {method.GetOptimizerStopConditionDescription()}")
44 print("============= Resolution Change =============")
45
46
47if len(sys.argv) < 4:
48 print(
49 "Usage:",
50 sys.argv[0],
51 "<fixedImageFilter> <movingImageFile>",
52 "<outputTransformFile>",
53 )
54 sys.exit(1)
55
57
59
62)
63
65
66R.SetShrinkFactorsPerLevel([3, 2, 1])
67R.SetSmoothingSigmasPerLevel([2, 1, 1])
68
69R.SetMetricAsJointHistogramMutualInformation(20)
70R.MetricUseFixedImageGradientFilterOff()
71
72R.SetOptimizerAsGradientDescent(
73 learningRate=1.0,
74 numberOfIterations=100,
75 estimateLearningRate=R.EachIteration,
76)
77R.SetOptimizerScalesFromPhysicalShift()
78
79R.SetInitialTransform(initialTx)
80
81R.SetInterpolator(sitk.sitkLinear)
82
83R.AddCommand(sitk.sitkIterationEvent, lambda: command_iteration(R))
84R.AddCommand(
85 sitk.sitkMultiResolutionIterationEvent,
86 lambda: command_multiresolution_iteration(R),
87)
88
89outTx1 = R.Execute(fixed, moving)
90
91print("-------")
92print(outTx1)
93print(f"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
94print(f" Iteration: {R.GetOptimizerIteration()}")
95print(f" Metric value: {R.GetMetricValue()}")
96
97displacementField =
sitk.Image(fixed.GetSize(), sitk.sitkVectorFloat64)
98displacementField.CopyInformation(fixed)
100del displacementField
101displacementTx.SetSmoothingGaussianOnUpdate(
102 varianceForUpdateField=0.0, varianceForTotalField=1.5
103)
104
105R.SetMovingInitialTransform(outTx1)
106R.SetInitialTransform(displacementTx, inPlace=True)
107
108R.SetMetricAsANTSNeighborhoodCorrelation(4)
109R.MetricUseFixedImageGradientFilterOff()
110
111R.SetShrinkFactorsPerLevel([3, 2, 1])
112R.SetSmoothingSigmasPerLevel([2, 1, 1])
113
114R.SetOptimizerScalesFromPhysicalShift()
115R.SetOptimizerAsGradientDescent(
116 learningRate=1,
117 numberOfIterations=300,
118 estimateLearningRate=R.EachIteration,
119)
120
121R.Execute(fixed, moving)
122
123print("-------")
124print(displacementTx)
125print(f"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
126print(f" Iteration: {R.GetOptimizerIteration()}")
127print(f" Metric value: {R.GetMetricValue()}")
128
131
132if "SITK_NOSHOW" not in os.environ:
133 sitk.Show(displacementTx.GetDisplacementField(),
"Displacement Field")
134
136 resampler.SetReferenceImage(fixed)
137 resampler.SetInterpolator(sitk.sitkLinear)
138 resampler.SetDefaultPixelValue(100)
139 resampler.SetTransform(compositeTx)
140
141 out = resampler.Execute(moving)
144 cimg =
sitk.Compose(simg1, simg2, simg1 // 2.0 + simg2 // 2.0)
145 sitk.Show(cimg,
"ImageRegistration1 Composition")
An interface method to the modular ITKv4 registration framework.
The Image class for SimpleITK.
Resample an image via a coordinate transform.
SITKIO_EXPORT Image ReadImage(const PathType &filename, PixelIDValueEnum outputPixelType=sitkUnknown, const std::string &imageIO="")
ReadImage is a procedural interface to the ImageFileReader class which is convenient for most image r...
Image Compose(const std::vector< Image > &images)
ComposeImageFilter combine several scalar images into a multicomponent image.
void SITKIO_EXPORT Show(const Image &image, const std::string &title="", const bool debugOn=ProcessObject::GetGlobalDefaultDebug())
Transform CenteredTransformInitializer(const Image &fixedImage, const Image &movingImage, const Transform &transform, CenteredTransformInitializerFilter::OperationModeType operationMode=itk::simple::CenteredTransformInitializerFilter::MOMENTS)
CenteredTransformInitializer is a helper class intended to initialize the center of rotation and the ...
SITKCommon_EXPORT void WriteTransform(const Transform &transform, const PathType &filename)
Image RescaleIntensity(Image &&image1, double outputMinimum=0, double outputMaximum=255)
Applies a linear transformation to the intensity levels of the input Image .
Image Cast(const Image &image, PixelIDValueEnum pixelID)