SimpleITK  
ImageRegistrationMethodDisplacement1/ImageRegistrationMethodDisplacement1.py
1 #!/usr/bin/env python
2 # =========================================================================
3 #
4 # Copyright NumFOCUS
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0.txt
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 # =========================================================================
19 
20 import SimpleITK as sitk
21 import sys
22 import os
23 
24 
25 def command_iteration(method):
26  if method.GetOptimizerIteration() == 0:
27  print(f"\tLevel: {method.GetCurrentLevel()}")
28  print(f"\tScales: {method.GetOptimizerScales()}")
29  print(f"#{method.GetOptimizerIteration()}")
30  print(f"\tMetric Value: {method.GetMetricValue():10.5f}")
31  print(f"\tLearningRate: {method.GetOptimizerLearningRate():10.5f}")
32  if method.GetOptimizerConvergenceValue() != sys.float_info.max:
33  print("\tConvergence Value: " + f"{method.GetOptimizerConvergenceValue():.5e}")
34 
35 
36 def command_multiresolution_iteration(method):
37  print(f"\tStop Condition: {method.GetOptimizerStopConditionDescription()}")
38  print("============= Resolution Change =============")
39 
40 
41 if len(sys.argv) < 4:
42  print(
43  "Usage:",
44  sys.argv[0],
45  "<fixedImageFilter> <movingImageFile>",
46  "<outputTransformFile>",
47  )
48  sys.exit(1)
49 
50 fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32)
51 
52 moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32)
53 
55  fixed, moving, sitk.AffineTransform(fixed.GetDimension())
56 )
57 
59 
60 R.SetShrinkFactorsPerLevel([3, 2, 1])
61 R.SetSmoothingSigmasPerLevel([2, 1, 1])
62 
63 R.SetMetricAsJointHistogramMutualInformation(20)
64 R.MetricUseFixedImageGradientFilterOff()
65 
66 R.SetOptimizerAsGradientDescent(
67  learningRate=1.0,
68  numberOfIterations=100,
69  estimateLearningRate=R.EachIteration,
70 )
71 R.SetOptimizerScalesFromPhysicalShift()
72 
73 R.SetInitialTransform(initialTx)
74 
75 R.SetInterpolator(sitk.sitkLinear)
76 
77 R.AddCommand(sitk.sitkIterationEvent, lambda: command_iteration(R))
78 R.AddCommand(
79  sitk.sitkMultiResolutionIterationEvent,
80  lambda: command_multiresolution_iteration(R),
81 )
82 
83 outTx1 = R.Execute(fixed, moving)
84 
85 print("-------")
86 print(outTx1)
87 print(f"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
88 print(f" Iteration: {R.GetOptimizerIteration()}")
89 print(f" Metric value: {R.GetMetricValue()}")
90 
91 displacementField = sitk.Image(fixed.GetSize(), sitk.sitkVectorFloat64)
92 displacementField.CopyInformation(fixed)
93 displacementTx = sitk.DisplacementFieldTransform(displacementField)
94 del displacementField
95 displacementTx.SetSmoothingGaussianOnUpdate(
96  varianceForUpdateField=0.0, varianceForTotalField=1.5
97 )
98 
99 R.SetMovingInitialTransform(outTx1)
100 R.SetInitialTransform(displacementTx, inPlace=True)
101 
102 R.SetMetricAsANTSNeighborhoodCorrelation(4)
103 R.MetricUseFixedImageGradientFilterOff()
104 
105 R.SetShrinkFactorsPerLevel([3, 2, 1])
106 R.SetSmoothingSigmasPerLevel([2, 1, 1])
107 
108 R.SetOptimizerScalesFromPhysicalShift()
109 R.SetOptimizerAsGradientDescent(
110  learningRate=1,
111  numberOfIterations=300,
112  estimateLearningRate=R.EachIteration,
113 )
114 
115 R.Execute(fixed, moving)
116 
117 print("-------")
118 print(displacementTx)
119 print(f"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
120 print(f" Iteration: {R.GetOptimizerIteration()}")
121 print(f" Metric value: {R.GetMetricValue()}")
122 
123 compositeTx = sitk.CompositeTransform([outTx1, displacementTx])
124 sitk.WriteTransform(compositeTx, sys.argv[3])
125 
126 if "SITK_NOSHOW" not in os.environ:
127  sitk.Show(displacementTx.GetDisplacementField(), "Displacement Field")
128 
129  resampler = sitk.ResampleImageFilter()
130  resampler.SetReferenceImage(fixed)
131  resampler.SetInterpolator(sitk.sitkLinear)
132  resampler.SetDefaultPixelValue(100)
133  resampler.SetTransform(compositeTx)
134 
135  out = resampler.Execute(moving)
136  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
137  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
138  cimg = sitk.Compose(simg1, simg2, simg1 // 2.0 + simg2 // 2.0)
139  sitk.Show(cimg, "ImageRegistration1 Composition")
itk::simple::Image
The Image class for SimpleITK.
Definition: sitkImage.h:76
itk::simple::DisplacementFieldTransform
A dense deformable transform over a bounded spatial domain for 2D or 3D coordinates space.
Definition: sitkDisplacementFieldTransform.h:34
itk::simple::RescaleIntensity
Image RescaleIntensity(const Image &image1, double outputMinimum=0, double outputMaximum=255)
Applies a linear transformation to the intensity levels of the input Image .
itk::simple::Show
void SITKIO_EXPORT Show(const Image &image, const std::string &title="", const bool debugOn=ProcessObject::GetGlobalDefaultDebug())
itk::simple::Cast
Image Cast(const Image &image, PixelIDValueEnum pixelID)
itk::simple::ResampleImageFilter
Resample an image via a coordinate transform.
Definition: sitkResampleImageFilter.h:52
itk::simple::WriteTransform
SITKCommon_EXPORT void WriteTransform(const Transform &transform, const PathType &filename)
itk::simple::CompositeTransform
This class contains a stack of transforms and concatenates them by composition.
Definition: sitkCompositeTransform.h:58
itk::simple::Compose
Image Compose(const Image &image1, const Image &image2, const Image &image3, const Image &image4, const Image &image5)
ComposeImageFilter combine several scalar images into a multicomponent image.
itk::simple::ImageRegistrationMethod
An interface method to the modular ITKv4 registration framework.
Definition: sitkImageRegistrationMethod.h:87
itk::simple::AffineTransform
An affine transformation about a fixed center with translation for a 2D or 3D coordinate.
Definition: sitkAffineTransform.h:33
itk::simple::ReadImage
SITKIO_EXPORT Image ReadImage(const std::vector< PathType > &fileNames, PixelIDValueEnum outputPixelType=sitkUnknown, const std::string &imageIO="")
ReadImage is a procedural interface to the ImageSeriesReader class which is convenient for most image...
itk::simple::CenteredTransformInitializer
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 ...