SimpleITK  1.0.1
ImageRegistrationMethodDisplacement1/ImageRegistrationMethodDisplacement1.py
1 #!/usr/bin/env python
2 #=========================================================================
3 #
4 # Copyright Insight Software Consortium
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 from __future__ import print_function
21 
22 import SimpleITK as sitk
23 import sys
24 import os
25 
26 
27 def command_iteration(method) :
28  if (method.GetOptimizerIteration() == 0):
29  print("\tLevel: {0}".format(method.GetCurrentLevel()))
30  print("\tScales: {0}".format(method.GetOptimizerScales()))
31  print("#{0}".format(method.GetOptimizerIteration()))
32  print("\tMetric Value: {0:10.5f}".format( method.GetMetricValue()))
33  print("\tLearningRate: {0:10.5f}".format(method.GetOptimizerLearningRate()))
34  if (method.GetOptimizerConvergenceValue() != sys.float_info.max):
35  print("\tConvergence Value: {0:.5e}".format(method.GetOptimizerConvergenceValue()))
36 
37 
38 def command_multiresolution_iteration(method):
39  print("\tStop Condition: {0}".format(method.GetOptimizerStopConditionDescription()))
40  print("============= Resolution Change =============")
41 
42 
43 if len ( sys.argv ) < 4:
44  print( "Usage: {0} <fixedImageFilter> <movingImageFile> <outputTransformFile>".format(sys.argv[0]))
45  sys.exit ( 1 )
46 
47 
48 fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32)
49 
50 moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32)
51 
52 initialTx = sitk.CenteredTransformInitializer(fixed, moving, sitk.AffineTransform(fixed.GetDimension()))
53 
55 
56 R.SetShrinkFactorsPerLevel([3,2,1])
57 R.SetSmoothingSigmasPerLevel([2,1,1])
58 
59 R.SetMetricAsJointHistogramMutualInformation(20)
60 R.MetricUseFixedImageGradientFilterOff()
61 R.MetricUseFixedImageGradientFilterOff()
62 
63 
64 R.SetOptimizerAsGradientDescent(learningRate=1.0,
65  numberOfIterations=100,
66  estimateLearningRate = R.EachIteration)
67 R.SetOptimizerScalesFromPhysicalShift()
68 
69 R.SetInitialTransform(initialTx,inPlace=True)
70 
71 R.SetInterpolator(sitk.sitkLinear)
72 
73 R.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(R) )
74 R.AddCommand( sitk.sitkMultiResolutionIterationEvent, lambda: command_multiresolution_iteration(R) )
75 
76 outTx = R.Execute(fixed, moving)
77 
78 
79 print("-------")
80 print(outTx)
81 print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription()))
82 print(" Iteration: {0}".format(R.GetOptimizerIteration()))
83 print(" Metric value: {0}".format(R.GetMetricValue()))
84 
85 
86 displacementField = sitk.Image(fixed.GetSize(), sitk.sitkVectorFloat64)
87 displacementField.CopyInformation(fixed)
88 displacementTx = sitk.DisplacementFieldTransform(displacementField)
89 del displacementField
90 displacementTx.SetSmoothingGaussianOnUpdate(varianceForUpdateField=0.0,
91  varianceForTotalField=1.5)
92 
93 
94 
95 R.SetMovingInitialTransform(outTx)
96 R.SetInitialTransform(displacementTx, inPlace=True)
97 
98 R.SetMetricAsANTSNeighborhoodCorrelation(4)
99 R.MetricUseFixedImageGradientFilterOff()
100 R.MetricUseFixedImageGradientFilterOff()
101 
102 
103 R.SetShrinkFactorsPerLevel([3,2,1])
104 R.SetSmoothingSigmasPerLevel([2,1,1])
105 
106 R.SetOptimizerScalesFromPhysicalShift()
107 R.SetOptimizerAsGradientDescent(learningRate=1,
108  numberOfIterations=300,
109  estimateLearningRate=R.EachIteration)
110 
111 outTx.AddTransform( R.Execute(fixed, moving) )
112 
113 
114 print("-------")
115 print(outTx)
116 print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription()))
117 print(" Iteration: {0}".format(R.GetOptimizerIteration()))
118 print(" Metric value: {0}".format(R.GetMetricValue()))
119 
120 
121 sitk.WriteTransform(outTx, sys.argv[3])
122 
123 if ( not "SITK_NOSHOW" in os.environ ):
124 
125  sitk.Show(displacementTx.GetDisplacementField(), "Displacement Field")
126 
127  resampler = sitk.ResampleImageFilter()
128  resampler.SetReferenceImage(fixed);
129  resampler.SetInterpolator(sitk.sitkLinear)
130  resampler.SetDefaultPixelValue(100)
131  resampler.SetTransform(outTx)
132 
133  out = resampler.Execute(moving)
134  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
135  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
136  cimg = sitk.Compose(simg1, simg2, simg1/2.+simg2/2.)
137  sitk.Show( cimg, "ImageRegistration1 Composition" )