SimpleITK  
ImageRegistrationMethodBSpline2/ImageRegistrationMethodBSpline2.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 MattesMutualInformation metric. """
22
23import sys
24import os
25import SimpleITK as sitk
26
27
28def command_iteration(method):
29 """ Callback invoked each iteration. """
30 print(f"{method.GetOptimizerIteration():3} " + f"= {method.GetMetricValue():10.5f}")
31 print("\t#: ", len(method.GetOptimizerPosition()))
32
33
34def command_multi_iteration(_):
35 """ Callback invoked at the end of each multi-resolution iteration. """
36 print("--------- Resolution Changing ---------")
37
38
39if len(sys.argv) < 4:
40 print(
41 "Usage:",
42 sys.argv[0],
43 "<fixedImageFilter> <movingImageFile>",
44 "<outputTransformFile>",
45 )
46 sys.exit(1)
47
48fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32)
49
50moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32)
51
52transformDomainMeshSize = [10] * moving.GetDimension()
53tx = sitk.BSplineTransformInitializer(fixed, transformDomainMeshSize)
54
55print("Initial Parameters:")
56print(tx.GetParameters())
57
59R.SetMetricAsMattesMutualInformation(50)
60R.SetOptimizerAsGradientDescentLineSearch(
61 5.0, 100, convergenceMinimumValue=1e-4, convergenceWindowSize=5
62)
63R.SetOptimizerScalesFromPhysicalShift()
64R.SetInitialTransform(tx)
65R.SetInterpolator(sitk.sitkLinear)
66
67R.SetShrinkFactorsPerLevel([6, 2, 1])
68R.SetSmoothingSigmasPerLevel([6, 2, 1])
69
70R.AddCommand(sitk.sitkIterationEvent, lambda: command_iteration(R))
71R.AddCommand(sitk.sitkMultiResolutionIterationEvent, lambda: command_multi_iteration(R))
72
73outTx = R.Execute(fixed, moving)
74
75print("-------")
76print(outTx)
77print(f"Optimizer stop condition: {R.GetOptimizerStopConditionDescription()}")
78print(f" Iteration: {R.GetOptimizerIteration()}")
79print(f" Metric value: {R.GetMetricValue()}")
80
81sitk.WriteTransform(outTx, sys.argv[3])
82
83if "SITK_NOSHOW" not in os.environ:
84 resampler = sitk.ResampleImageFilter()
85 resampler.SetReferenceImage(fixed)
86 resampler.SetInterpolator(sitk.sitkLinear)
87 resampler.SetDefaultPixelValue(100)
88 resampler.SetTransform(outTx)
89
90 out = resampler.Execute(moving)
91 simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
92 simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
93 cimg = sitk.Compose(simg1, simg2, simg1 // 2.0 + simg2 // 2.0)
94 sitk.Show(cimg, "ImageRegistration1 Composition")
An interface method to the modular ITKv4 registration framework.
Resample an image via a coordinate transform.
SITKIO_EXPORT Image ReadImage(const PathType &filename, PixelIDValueEnum outputPixelType=sitkUnknown, const std::string &imageIO="")
ReadImage is a procedural interface to the ImageFileReader class which is convenient for most image r...
Image Compose(const std::vector< Image > &images)
ComposeImageFilter combine several scalar images into a multicomponent image.
void SITKIO_EXPORT Show(const Image &image, const std::string &title="", const bool debugOn=ProcessObject::GetGlobalDefaultDebug())
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...
SITKCommon_EXPORT void WriteTransform(const Transform &transform, const PathType &filename)
Image RescaleIntensity(Image &&image1, double outputMinimum=0, double outputMaximum=255)
Applies a linear transformation to the intensity levels of the input Image .
Image Cast(const Image &image, PixelIDValueEnum pixelID)