SimpleITK  
ImageRegistrationMethodBSpline3/ImageRegistrationMethodBSpline3.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 import SimpleITK as sitk
21 import sys
22 import os
23 
24 
25 def command_iteration(method, bspline_transform):
26  if method.GetOptimizerIteration() == 0:
27  # The BSpline is resized before the first optimizer
28  # iteration is completed per level. Print the transform object
29  # to show the adapted BSpline transform.
30  print(bspline_transform)
31 
32  print(f"{method.GetOptimizerIteration():3} " + f"= {method.GetMetricValue():10.5f}")
33 
34 
35 def command_multi_iteration(method):
36  # The sitkMultiResolutionIterationEvent occurs before the
37  # resolution of the transform. This event is used here to print
38  # the status of the optimizer from the previous registration level.
39  if R.GetCurrentLevel() > 0:
40  print(
41  "Optimizer stop condition: " + f"{R.GetOptimizerStopConditionDescription()}"
42  )
43  print(f" Iteration: {R.GetOptimizerIteration()}")
44  print(f" Metric value: {R.GetMetricValue()}")
45 
46  print("--------- Resolution Changing ---------")
47 
48 
49 if len(sys.argv) < 4:
50  print(
51  "Usage:",
52  sys.argv[0],
53  "<fixedImageFilter> <movingImageFile>",
54  "<outputTransformFile>",
55  )
56  sys.exit(1)
57 
58 fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32)
59 
60 moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32)
61 
62 transformDomainMeshSize = [2] * fixed.GetDimension()
63 tx = sitk.BSplineTransformInitializer(fixed, transformDomainMeshSize)
64 
65 print(f"Initial Number of Parameters: {tx.GetNumberOfParameters()}")
66 
68 R.SetMetricAsJointHistogramMutualInformation()
69 
70 R.SetOptimizerAsGradientDescentLineSearch(
71  5.0, 100, convergenceMinimumValue=1e-4, convergenceWindowSize=5
72 )
73 
74 R.SetInterpolator(sitk.sitkLinear)
75 
76 R.SetInitialTransformAsBSpline(tx, inPlace=True, scaleFactors=[1, 2, 5])
77 R.SetShrinkFactorsPerLevel([4, 2, 1])
78 R.SetSmoothingSigmasPerLevel([4, 2, 1])
79 
80 R.AddCommand(sitk.sitkIterationEvent, lambda: command_iteration(R, tx))
81 R.AddCommand(sitk.sitkMultiResolutionIterationEvent, lambda: command_multi_iteration(R))
82 
83 outTx = R.Execute(fixed, moving)
84 
85 print("-------")
86 print(tx)
87 print(outTx)
88 print(f"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
89 print(f" Iteration: {R.GetOptimizerIteration()}")
90 print(f" Metric value: {R.GetMetricValue()}")
91 
92 sitk.WriteTransform(outTx, sys.argv[3])
93 
94 if "SITK_NOSHOW" not in os.environ:
95  resampler = sitk.ResampleImageFilter()
96  resampler.SetReferenceImage(fixed)
97  resampler.SetInterpolator(sitk.sitkLinear)
98  resampler.SetDefaultPixelValue(100)
99  resampler.SetTransform(outTx)
100 
101  out = resampler.Execute(moving)
102  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
103  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
104  cimg = sitk.Compose(simg1, simg2, simg1 // 2.0 + simg2 // 2.0)
105  sitk.Show(cimg, "Image Registration 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::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...