20 """ A SimpleITK example demonstrating image registration using the
21 BSplineTransform and the JointHistogramMutualInformation metric. """
25 import SimpleITK
as sitk
28 def command_iteration(method, bspline_transform):
29 """ Callback invoked each iteration """
30 if method.GetOptimizerIteration() == 0:
34 print(bspline_transform)
36 print(f
"{method.GetOptimizerIteration():3} " + f
"= {method.GetMetricValue():10.5f}")
39 def command_multi_iteration(method):
40 """ Callback invoked before starting a multi-resolution level.
41 The sitkMultiResolutionIterationEvent occurs before the
42 resolution of the transform. This event is used here to print
43 the status of the optimizer from the previous registration level.
45 if method.GetCurrentLevel() > 0:
47 "Optimizer stop condition: " + f
"{R.GetOptimizerStopConditionDescription()}"
49 print(f
" Iteration: {R.GetOptimizerIteration()}")
50 print(f
" Metric value: {R.GetMetricValue()}")
52 print(
"--------- Resolution Changing ---------")
59 "<fixedImageFilter> <movingImageFile>",
60 "<outputTransformFile>",
68 transformDomainMeshSize = [2] * fixed.GetDimension()
71 print(f
"Initial Number of Parameters: {tx.GetNumberOfParameters()}")
74 R.SetMetricAsJointHistogramMutualInformation()
76 R.SetOptimizerAsGradientDescentLineSearch(
77 5.0, 100, convergenceMinimumValue=1e-4, convergenceWindowSize=5
80 R.SetInterpolator(sitk.sitkLinear)
82 R.SetInitialTransformAsBSpline(tx, inPlace=
True, scaleFactors=[1, 2, 5])
83 R.SetShrinkFactorsPerLevel([4, 2, 1])
84 R.SetSmoothingSigmasPerLevel([4, 2, 1])
86 R.AddCommand(sitk.sitkIterationEvent,
lambda: command_iteration(R, tx))
87 R.AddCommand(sitk.sitkMultiResolutionIterationEvent,
lambda: command_multi_iteration(R))
89 outTx = R.Execute(fixed, moving)
94 print(f
"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
95 print(f
" Iteration: {R.GetOptimizerIteration()}")
96 print(f
" Metric value: {R.GetMetricValue()}")
100 if "SITK_NOSHOW" not in os.environ:
102 resampler.SetReferenceImage(fixed)
103 resampler.SetInterpolator(sitk.sitkLinear)
104 resampler.SetDefaultPixelValue(100)
105 resampler.SetTransform(outTx)
107 out = resampler.Execute(moving)
110 cimg =
sitk.Compose(simg1, simg2, simg1 // 2.0 + simg2 // 2.0)
111 sitk.Show(cimg,
"Image Registration Composition")