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 import SimpleITK
as sitk
43 def command_iteration(method):
44 if (method.GetOptimizerIteration() == 0):
45 print(
"Scales: ", method.GetOptimizerScales())
46 print(f
"{method.GetOptimizerIteration():3} = {method.GetMetricValue():7.5f} : {method.GetOptimizerPosition()}")
50 print(
"Usage:", sys.argv[0],
"<fixedImageFilter> <movingImageFile>",
51 "<outputTransformFile>")
60 R.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)
63 if fixed.GetDimension() == 2:
67 R.SetOptimizerAsExhaustive([sample_per_axis // 2, 0, 0])
69 R.SetOptimizerScales([2.0 * pi / sample_per_axis, 1.0, 1.0])
70 elif fixed.GetDimension() == 3:
72 R.SetOptimizerAsExhaustive([sample_per_axis // 2, sample_per_axis // 2,
73 sample_per_axis // 4, 0, 0, 0])
75 [2.0 * pi / sample_per_axis, 2.0 * pi / sample_per_axis,
76 2.0 * pi / sample_per_axis, 1.0, 1.0, 1.0])
82 R.SetInitialTransform(tx)
84 R.SetInterpolator(sitk.sitkLinear)
86 R.AddCommand(sitk.sitkIterationEvent,
lambda: command_iteration(R))
88 outTx = R.Execute(fixed, moving)
92 print(f
"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
93 print(f
" Iteration: {R.GetOptimizerIteration()}")
94 print(f
" Metric value: {R.GetMetricValue()}")
98 if (
"SITK_NOSHOW" not in os.environ):
100 resampler.SetReferenceImage(fixed)
101 resampler.SetInterpolator(sitk.sitkLinear)
102 resampler.SetDefaultPixelValue(1)
103 resampler.SetTransform(outTx)
105 out = resampler.Execute(moving)
109 cimg =
sitk.Compose(simg1, simg2, simg1 // 2. + simg2 // 2.)
110 sitk.Show(cimg,
"ImageRegistrationExhaustive Composition")