21 This script demonstrates the use of the Exhaustive optimizer in the
22 ImageRegistrationMethod to estimate a good initial rotation position.
24 Because gradient descent base optimization can get stuck in local
25 minima, a good initial transform is critical for reasonable
26 results. Search a reasonable space on a grid with brute force may be a
27 reliable way to get a starting location for further optimization.
29 The initial translation and center of rotation for the transform is
30 initialized based on the first principle moments of the intensities of
31 the image. Then in either 2D or 3D a Euler transform is used to
32 exhaustively search a grid of the rotation space at a certain step
33 size. The resulting transform is a reasonable guess where to start
37 from __future__
import print_function
38 from __future__
import division
41 import SimpleITK
as sitk
47 def command_iteration(method) :
48 if (method.GetOptimizerIteration()==0):
49 print(
"Scales: ", method.GetOptimizerScales())
50 print(
"{0:3} = {1:7.5f} : {2}".format(method.GetOptimizerIteration(),
51 method.GetMetricValue(),
52 method.GetOptimizerPosition()))
56 if len ( sys.argv ) < 4:
57 print(
"Usage: {0} <fixedImageFilter> <movingImageFile> <outputTransformFile>".format(sys.argv[0]))
66 R.SetMetricAsMattesMutualInformation(numberOfHistogramBins = 50)
69 if fixed.GetDimension() == 2:
73 R.SetOptimizerAsExhaustive([sample_per_axis//2,0,0])
75 R.SetOptimizerScales([2.0*pi/sample_per_axis, 1.0,1.0])
76 elif fixed.GetDimension() == 3:
78 R.SetOptimizerAsExhaustive([sample_per_axis//2,sample_per_axis//2,sample_per_axis//4,0,0,0])
79 R.SetOptimizerScales([2.0*pi/sample_per_axis,2.0*pi/sample_per_axis,2.0*pi/sample_per_axis,1.0,1.0,1.0])
85 R.SetInitialTransform(tx)
87 R.SetInterpolator(sitk.sitkLinear)
89 R.AddCommand( sitk.sitkIterationEvent,
lambda: command_iteration(R) )
91 outTx = R.Execute(fixed, moving)
95 print(
"Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription()))
96 print(
" Iteration: {0}".format(R.GetOptimizerIteration()))
97 print(
" Metric value: {0}".format(R.GetMetricValue()))
102 if (
not "SITK_NOSHOW" in os.environ ):
105 resampler.SetReferenceImage(fixed);
106 resampler.SetInterpolator(sitk.sitkLinear)
107 resampler.SetDefaultPixelValue(1)
108 resampler.SetTransform(outTx)
110 out = resampler.Execute(moving)
115 sitk.Show( cimg,
"ImageRegistrationExhaustive Composition" )