SimpleITK  1.2.4
DemonsRegistration1/DemonsRegistration1.py
1 #!/usr/bin/env python
2 #=========================================================================
3 #
4 # Copyright Insight Software Consortium
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 from __future__ import print_function
21 
22 import SimpleITK as sitk
23 import sys
24 import os
25 
26 
27 def command_iteration(filter) :
28  print("{0:3} = {1:10.5f}".format(filter.GetElapsedIterations(),
29  filter.GetMetric()))
30 
31 if len ( sys.argv ) < 4:
32  print( "Usage: {0} <fixedImageFilter> <movingImageFile> <outputTransformFile>".format(sys.argv[0]))
33  sys.exit ( 1 )
34 
35 
36 fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32)
37 
38 moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32)
39 
40 
42 matcher.SetNumberOfHistogramLevels(1024)
43 matcher.SetNumberOfMatchPoints(7)
44 matcher.ThresholdAtMeanIntensityOn()
45 moving = matcher.Execute(moving,fixed)
46 
47 # The basic Demons Registration Filter
48 # Note there is a whole family of Demons Registration algorithms included in SimpleITK
50 demons.SetNumberOfIterations( 50 )
51 # Standard deviation for Gaussian smoothing of displacement field
52 demons.SetStandardDeviations( 1.0 )
53 
54 demons.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(demons) )
55 
56 displacementField = demons.Execute( fixed, moving )
57 
58 
59 print("-------")
60 print("Number Of Iterations: {0}".format(demons.GetElapsedIterations()))
61 print(" RMS: {0}".format(demons.GetRMSChange()))
62 
63 outTx = sitk.DisplacementFieldTransform( displacementField )
64 
65 sitk.WriteTransform(outTx, sys.argv[3])
66 
67 if ( not "SITK_NOSHOW" in os.environ ):
68 
69  resampler = sitk.ResampleImageFilter()
70  resampler.SetReferenceImage(fixed);
71  resampler.SetInterpolator(sitk.sitkLinear)
72  resampler.SetDefaultPixelValue(100)
73  resampler.SetTransform(outTx)
74 
75  out = resampler.Execute(moving)
76  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
77  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
78  # Use the // floor division operator so that the pixel type is
79  # the same for all three images which is the expectation for
80  # the compose filter.
81  cimg = sitk.Compose(simg1, simg2, simg1//2.+simg2//2.)
82  sitk.Show( cimg, "DeformableRegistration1 Composition" )