SimpleITK  1.2.4
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 
62 R.SetOptimizerAsGradientDescent(learningRate=1.0,
63  numberOfIterations=100,
64  estimateLearningRate = R.EachIteration)
65 R.SetOptimizerScalesFromPhysicalShift()
66 
67 R.SetInitialTransform(initialTx,inPlace=True)
68 
69 R.SetInterpolator(sitk.sitkLinear)
70 
71 R.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(R) )
72 R.AddCommand( sitk.sitkMultiResolutionIterationEvent, lambda: command_multiresolution_iteration(R) )
73 
74 outTx = R.Execute(fixed, moving)
75 
76 
77 print("-------")
78 print(outTx)
79 print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription()))
80 print(" Iteration: {0}".format(R.GetOptimizerIteration()))
81 print(" Metric value: {0}".format(R.GetMetricValue()))
82 
83 
84 displacementField = sitk.Image(fixed.GetSize(), sitk.sitkVectorFloat64)
85 displacementField.CopyInformation(fixed)
86 displacementTx = sitk.DisplacementFieldTransform(displacementField)
87 del displacementField
88 displacementTx.SetSmoothingGaussianOnUpdate(varianceForUpdateField=0.0,
89  varianceForTotalField=1.5)
90 
91 
92 
93 R.SetMovingInitialTransform(outTx)
94 R.SetInitialTransform(displacementTx, inPlace=True)
95 
96 R.SetMetricAsANTSNeighborhoodCorrelation(4)
97 R.MetricUseFixedImageGradientFilterOff()
98 
99 R.SetShrinkFactorsPerLevel([3,2,1])
100 R.SetSmoothingSigmasPerLevel([2,1,1])
101 
102 R.SetOptimizerScalesFromPhysicalShift()
103 R.SetOptimizerAsGradientDescent(learningRate=1,
104  numberOfIterations=300,
105  estimateLearningRate=R.EachIteration)
106 
107 outTx.AddTransform( R.Execute(fixed, moving) )
108 
109 
110 print("-------")
111 print(outTx)
112 print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription()))
113 print(" Iteration: {0}".format(R.GetOptimizerIteration()))
114 print(" Metric value: {0}".format(R.GetMetricValue()))
115 
116 
117 sitk.WriteTransform(outTx, sys.argv[3])
118 
119 if ( not "SITK_NOSHOW" in os.environ ):
120 
121  sitk.Show(displacementTx.GetDisplacementField(), "Displacement Field")
122 
123  resampler = sitk.ResampleImageFilter()
124  resampler.SetReferenceImage(fixed);
125  resampler.SetInterpolator(sitk.sitkLinear)
126  resampler.SetDefaultPixelValue(100)
127  resampler.SetTransform(outTx)
128 
129  out = resampler.Execute(moving)
130  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
131  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
132  cimg = sitk.Compose(simg1, simg2, simg1//2.+simg2//2.)
133  sitk.Show( cimg, "ImageRegistration1 Composition" )