SimpleITK  
ImageRegistrationMethodBSpline1/ImageRegistrationMethodBSpline1.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  BSplineTransform and the ComplexCorrelation metric. """
22 
23 import sys
24 import os
25 import SimpleITK as sitk
26 
27 
28 def command_iteration(method):
29  """ Callback invoked when the optimization has an iteration """
30  print(f"{method.GetOptimizerIteration():3} " + f"= {method.GetMetricValue():10.5f}")
31 
32 
33 def main(args):
34  """ A SimpleITK example demonstrating image registration using the
35  BSplineTransform and the ComplexCorrelation metric. """
36  if len(args) < 4:
37  print(
38  "Usage:",
39  sys.argv[0],
40  "<fixedImageFilter> <movingImageFile>",
41  "<outputTransformFile>",
42  )
43  sys.exit(1)
44 
45  fixed = sitk.ReadImage(args[1], sitk.sitkFloat32)
46 
47  moving = sitk.ReadImage(args[2], sitk.sitkFloat32)
48 
49  transformDomainMeshSize = [8] * moving.GetDimension()
50  tx = sitk.BSplineTransformInitializer(fixed, transformDomainMeshSize)
51 
52  print("Initial Parameters:")
53  print(tx.GetParameters())
54 
56  R.SetMetricAsCorrelation()
57 
58  R.SetOptimizerAsLBFGSB(
59  gradientConvergenceTolerance=1e-5,
60  numberOfIterations=100,
61  maximumNumberOfCorrections=5,
62  maximumNumberOfFunctionEvaluations=1000,
63  costFunctionConvergenceFactor=1e7,
64  )
65  R.SetInitialTransform(tx, True)
66  R.SetInterpolator(sitk.sitkLinear)
67 
68  R.AddCommand(sitk.sitkIterationEvent, lambda: command_iteration(R))
69 
70  outTx = R.Execute(fixed, moving)
71 
72  print("-------")
73  print(outTx)
74  print(f"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
75  print(f" Iteration: {R.GetOptimizerIteration()}")
76  print(f" Metric value: {R.GetMetricValue()}")
77 
78  sitk.WriteTransform(outTx, args[3])
79 
80  resampler = sitk.ResampleImageFilter()
81  resampler.SetReferenceImage(fixed)
82  resampler.SetInterpolator(sitk.sitkLinear)
83  resampler.SetDefaultPixelValue(100)
84  resampler.SetTransform(outTx)
85 
86  out = resampler.Execute(moving)
87  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
88  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
89  cimg = sitk.Compose(simg1, simg2, simg1 // 2.0 + simg2 // 2.0)
90 
91  return_images = {"fixed": fixed, "moving": moving, "composition": cimg}
92  return return_images
93 
94 
95 if __name__ == "__main__":
96  return_dict = main(sys.argv)
97  if "SITK_NOSHOW" not in os.environ:
98  sitk.Show(
99  return_dict["composition"], "ImageRegistrationMethodBSpline1 Composition"
100  )
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::BSplineTransformInitializer
BSplineTransform BSplineTransformInitializer(const Image &image1, const std::vector< uint32_t > &transformDomainMeshSize=std::vector< uint32_t >(3, 1u), unsigned int order=3u)
BSplineTransformInitializerFilter is a helper class intended to initialize the control point grid suc...
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::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...