SimpleITK  
ImageRegistrationMethodExhaustive/ImageRegistrationMethodExhaustive.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 # 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 """ A SimpleITK example demonstrating image registration using the exhaustive
21  optimizer. """
22 
23 import sys
24 import os
25 from math import pi
26 import SimpleITK as sitk
27 
28 
29 def command_iteration(method):
30  """ Callback invoked when the optimization has an iteration """
31  if method.GetOptimizerIteration() == 0:
32  print("Scales: ", method.GetOptimizerScales())
33  print(
34  f"{method.GetOptimizerIteration():3} "
35  + f"= {method.GetMetricValue():7.5f} "
36  + f": {method.GetOptimizerPosition()}"
37  )
38 
39 
40 if len(sys.argv) < 4:
41  print(
42  "Usage:",
43  sys.argv[0],
44  "<fixedImageFilter> <movingImageFile>",
45  "<outputTransformFile>",
46  )
47  sys.exit(1)
48 
49 fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32)
50 
51 moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32)
52 
54 
55 R.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)
56 
57 sample_per_axis = 12
58 tx = None
59 
60 if fixed.GetDimension() == 2:
62  # Set the number of samples (radius) in each dimension, with a
63  # default step size of 1.0
64  R.SetOptimizerAsExhaustive([sample_per_axis // 2, 0, 0])
65  # Utilize the scale to set the step size for each dimension
66  R.SetOptimizerScales([2.0 * pi / sample_per_axis, 1.0, 1.0])
67 elif fixed.GetDimension() == 3:
69  R.SetOptimizerAsExhaustive(
70  [
71  sample_per_axis // 2,
72  sample_per_axis // 2,
73  sample_per_axis // 4,
74  0,
75  0,
76  0,
77  ]
78  )
79  R.SetOptimizerScales(
80  [
81  2.0 * pi / sample_per_axis,
82  2.0 * pi / sample_per_axis,
83  2.0 * pi / sample_per_axis,
84  1.0,
85  1.0,
86  1.0,
87  ]
88  )
89 
90 # Initialize the transform with a translation and the center of
91 # rotation from the moments of intensity.
92 tx = sitk.CenteredTransformInitializer(fixed, moving, tx)
93 
94 R.SetInitialTransform(tx)
95 
96 R.SetInterpolator(sitk.sitkLinear)
97 
98 R.AddCommand(sitk.sitkIterationEvent, lambda: command_iteration(R))
99 
100 outTx = R.Execute(fixed, moving)
101 
102 print("-------")
103 print(outTx)
104 print(f"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
105 print(f" Iteration: {R.GetOptimizerIteration()}")
106 print(f" Metric value: {R.GetMetricValue()}")
107 
108 sitk.WriteTransform(outTx, sys.argv[3])
109 
110 if "SITK_NOSHOW" not in os.environ:
111  resampler = sitk.ResampleImageFilter()
112  resampler.SetReferenceImage(fixed)
113  resampler.SetInterpolator(sitk.sitkLinear)
114  resampler.SetDefaultPixelValue(1)
115  resampler.SetTransform(outTx)
116 
117  out = resampler.Execute(moving)
118 
119  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
120  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
121  cimg = sitk.Compose(simg1, simg2, simg1 // 2.0 + simg2 // 2.0)
122  sitk.Show(cimg, "ImageRegistrationExhaustive Composition")
itk::simple::RescaleIntensity
Image RescaleIntensity(const Image &image1, double outputMinimum=0, double outputMaximum=255)
Applies a linear transformation to the intensity levels of the input Image .
itk::simple::Show
void SITKIO_EXPORT Show(const Image &image, const std::string &title="", const bool debugOn=ProcessObject::GetGlobalDefaultDebug())
itk::simple::Cast
Image Cast(const Image &image, PixelIDValueEnum pixelID)
itk::simple::Euler2DTransform
A rigid 2D transform with rotation in radians around a fixed center with translation.
Definition: sitkEuler2DTransform.h:33
itk::simple::ResampleImageFilter
Resample an image via a coordinate transform.
Definition: sitkResampleImageFilter.h:52
itk::simple::WriteTransform
SITKCommon_EXPORT void WriteTransform(const Transform &transform, const PathType &filename)
itk::simple::Compose
Image Compose(const Image &image1, const Image &image2, const Image &image3, const Image &image4, const Image &image5)
ComposeImageFilter combine several scalar images into a multicomponent image.
itk::simple::ImageRegistrationMethod
An interface method to the modular ITKv4 registration framework.
Definition: sitkImageRegistrationMethod.h:87
itk::simple::Euler3DTransform
A rigid 3D transform with rotation in radians around a fixed center with translation.
Definition: sitkEuler3DTransform.h:33
itk::simple::ReadImage
SITKIO_EXPORT Image ReadImage(const std::vector< PathType > &fileNames, PixelIDValueEnum outputPixelType=sitkUnknown, const std::string &imageIO="")
ReadImage is a procedural interface to the ImageSeriesReader class which is convenient for most image...
itk::simple::CenteredTransformInitializer
Transform CenteredTransformInitializer(const Image &fixedImage, const Image &movingImage, const Transform &transform, CenteredTransformInitializerFilter::OperationModeType operationMode=itk::simple::CenteredTransformInitializerFilter::MOMENTS)
CenteredTransformInitializer is a helper class intended to initialize the center of rotation and the ...