SimpleITK  
ImageRegistrationMethod3/ImageRegistrationMethod3.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
21  correlation metric and the center of mass initial transformation
22  estimation method. """
23 
24 import sys
25 import os
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("Estimated Scales: ", method.GetOptimizerScales())
33  print(
34  f"{method.GetOptimizerIteration():3} "
35  + f"= {method.GetMetricValue():7.5f} "
36  + f": {method.GetOptimizerPosition()}"
37  )
38 
39 
40 def main(args):
41  """ A SimpleITK example demonstrating image registration using the
42  correlation metric and the center of mass initial transformation
43  estimation method. """
44  if len(args) < 3:
45  print(
46  "Usage:",
47  "ImageRegistrationMethod3"
48  "<fixedImageFilter> <movingImageFile> <outputTransformFile>",
49  )
50  sys.exit(1)
51 
52  fixed = sitk.ReadImage(args[1], sitk.sitkFloat32)
53 
54  moving = sitk.ReadImage(args[2], sitk.sitkFloat32)
55 
57 
58  R.SetMetricAsCorrelation()
59 
60  R.SetOptimizerAsRegularStepGradientDescent(
61  learningRate=2.0,
62  minStep=1e-4,
63  numberOfIterations=500,
64  gradientMagnitudeTolerance=1e-8,
65  )
66  R.SetOptimizerScalesFromIndexShift()
67 
69  R.SetInitialTransform(tx)
70 
71  R.SetInterpolator(sitk.sitkLinear)
72 
73  R.AddCommand(sitk.sitkIterationEvent, lambda: command_iteration(R))
74 
75  outTx = R.Execute(fixed, moving)
76 
77  print("-------")
78  print(outTx)
79  print(f"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
80  print(f" Iteration: {R.GetOptimizerIteration()}")
81  print(f" Metric value: {R.GetMetricValue()}")
82 
83  sitk.WriteTransform(outTx, args[3])
84 
85  resampler = sitk.ResampleImageFilter()
86  resampler.SetReferenceImage(fixed)
87  resampler.SetInterpolator(sitk.sitkLinear)
88  resampler.SetDefaultPixelValue(100)
89  resampler.SetTransform(outTx)
90 
91  out = resampler.Execute(moving)
92 
93  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
94  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
95  cimg = sitk.Compose(simg1, simg2, simg1 // 2.0 + simg2 // 2.0)
96 
97  return {"fixed": fixed, "moving": moving, "composition": cimg}
98 
99 
100 if __name__ == "__main__":
101  return_dict = main(sys.argv)
102  if "SITK_NOSHOW" not in os.environ:
103  sitk.Show(return_dict["composition"], "ImageRegistration3 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::Similarity2DTransform
A similarity 2D transform with rotation in radians and isotropic scaling around a fixed center with t...
Definition: sitkSimilarity2DTransform.h:33
itk::simple::Cast
Image Cast(const Image &image, PixelIDValueEnum pixelID)
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::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 ...