ITK  6.0.0
Insight Toolkit
SphinxExamples/src/Numerics/Optimizers/ExhaustiveOptimizer/Code.py
1 #!/usr/bin/env python
2 # =========================================================================
3 #
4 # Copyright NumFOCUS
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 # https://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 # Python example demonstrating itk.ExhaustiveOptimizer usage
21 import sys
22 from math import pi
23 
24 import itk
25 
26 EXIT_SUCCESS = 0
27 EXIT_FAILURE = 1
28 
29 
30 def main(argv):
31  if len(argv) < 3:
32  raise Exception(f"Usage: {argv[0]} fixed_image moving_image")
33 
34  fixed_image = itk.imread(argv[1], itk.F)
35  moving_image = itk.imread(argv[2], itk.F)
36 
37  dimension = fixed_image.GetImageDimension()
38  FixedImageType = type(fixed_image)
39  MovingImageType = type(moving_image)
40 
41  if dimension == 2:
42  transform = itk.Euler2DTransform[itk.D].New()
43  else:
44  raise Exception(f"Unsupported dimension: {dimension}")
45 
46  TransformInitializerType = itk.CenteredTransformInitializer[
47  itk.MatrixOffsetTransformBase[itk.D, dimension, dimension],
48  FixedImageType,
49  MovingImageType,
50  ]
51  initializer = TransformInitializerType.New(
52  Transform=transform,
53  FixedImage=fixed_image,
54  MovingImage=moving_image,
55  )
56  initializer.InitializeTransform()
57 
58  metric = itk.MeanSquaresImageToImageMetricv4[FixedImageType, MovingImageType].New()
59 
60  optimizer = itk.ExhaustiveOptimizerv4[itk.D].New()
61 
62  def print_iteration():
63  print(
64  f"Iteration:"
65  f"{optimizer.GetCurrentIteration()}\t"
66  f"{list(optimizer.GetCurrentIndex())} \t"
67  f"{optimizer.GetCurrentValue():10.4f}\t"
68  f"{list(optimizer.GetCurrentPosition())}\t"
69  )
70 
71  optimizer.AddObserver(itk.IterationEvent(), print_iteration)
72 
73  angles = 12
74  optimizer.SetNumberOfSteps([int(angles / 2), 0, 0])
75 
76  # Initialize scales and set back to optimizer
77  scales = optimizer.GetScales()
78  scales.SetSize(3)
79  scales.SetElement(0, 2.0 * pi / angles)
80  scales.SetElement(1, 1.0)
81  scales.SetElement(2, 1.0)
82  optimizer.SetScales(scales)
83 
84  RegistrationType = itk.ImageRegistrationMethodv4[FixedImageType, MovingImageType]
85  registration = RegistrationType.New(
86  Metric=metric,
87  Optimizer=optimizer,
88  FixedImage=fixed_image,
89  MovingImage=moving_image,
90  InitialTransform=transform,
91  NumberOfLevels=1,
92  )
93 
94  try:
95  registration.Update()
96 
97  print(
98  f"MinimumMetricValue: {optimizer.GetMinimumMetricValue():.4f}\t"
99  f"MaximumMetricValue: {optimizer.GetMaximumMetricValue():.4f}\n"
100  f"MinimumMetricValuePosition: {list(optimizer.GetMinimumMetricValuePosition())}\t"
101  f"MaximumMetricValuePosition: {list(optimizer.GetMaximumMetricValuePosition())}\n"
102  f"StopConditionDescription: {optimizer.GetStopConditionDescription()}\t"
103  )
104 
105  except Exception as e:
106  print(f"Exception caught: {e}")
107  return EXIT_FAILURE
108 
109  return EXIT_SUCCESS
110 
111 
112 if __name__ == "__main__":
113  main(sys.argv)
itk::ExhaustiveOptimizerv4
Optimizer that fully samples a grid on the parametric space.
Definition: itkExhaustiveOptimizerv4.h:84
itk::MatrixOffsetTransformBase
Matrix and Offset transformation of a vector space (e.g. space coordinates)
Definition: itkMatrixOffsetTransformBase.h:106
itk::Euler2DTransform
Euler2DTransform of a vector space (e.g. space coordinates)
Definition: itkEuler2DTransform.h:41
itk::ImageRegistrationMethodv4
Interface method for the current registration framework.
Definition: itkImageRegistrationMethodv4.h:117
itk::MeanSquaresImageToImageMetricv4
Class implementing a mean squares metric.
Definition: itkMeanSquaresImageToImageMetricv4.h:46
New
static Pointer New()
itk::CenteredTransformInitializer
CenteredTransformInitializer is a helper class intended to initialize the center of rotation and the ...
Definition: itkCenteredTransformInitializer.h:61