ITK  5.2.0
Insight Toolkit
SphinxExamples/src/Filtering/ImageGrid/ProcessA2DSliceOfA3DImage/Code.py
1 #!/usr/bin/env python
2 
3 # Copyright NumFOCUS
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0.txt
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 
17 import sys
18 import itk
19 
20 if len(sys.argv) != 4:
21  print('Usage: ' + sys.argv[0] +
22  ' input3DImageFile output3DImageFile sliceNumber')
23  sys.exit(1)
24 inputFilename = sys.argv[1]
25 outputFilename = sys.argv[2]
26 
27 Dimension = 3
28 PixelType = itk.ctype('short')
29 ImageType = itk.Image[PixelType, Dimension]
30 
31 reader = itk.ImageFileReader[ImageType].New()
32 reader.SetFileName(inputFilename)
33 reader.Update()
34 inputImage = reader.GetOutput()
35 
36 extractFilter = itk.ExtractImageFilter.New(inputImage)
37 extractFilter.SetDirectionCollapseToSubmatrix()
38 
39 # set up the extraction region [one slice]
40 inputRegion = inputImage.GetBufferedRegion()
41 size = inputRegion.GetSize()
42 size[2] = 1 # we extract along z direction
43 start = inputRegion.GetIndex()
44 sliceNumber = int(sys.argv[3])
45 start[2] = sliceNumber
46 desiredRegion = inputRegion
47 desiredRegion.SetSize(size)
48 desiredRegion.SetIndex(start)
49 
50 extractFilter.SetExtractionRegion(desiredRegion)
51 pasteFilter = itk.PasteImageFilter.New(inputImage)
52 medianFilter = itk.MedianImageFilter.New(extractFilter)
53 pasteFilter.SetSourceImage(medianFilter.GetOutput())
54 pasteFilter.SetDestinationImage(inputImage)
55 pasteFilter.SetDestinationIndex(start)
56 
57 indexRadius = size
58 indexRadius[0] = 1 # radius along x
59 indexRadius[1] = 1 # radius along y
60 indexRadius[2] = 0 # radius along z
61 medianFilter.SetRadius(indexRadius)
62 medianFilter.UpdateLargestPossibleRegion()
63 medianImage = medianFilter.GetOutput()
64 pasteFilter.SetSourceRegion(medianImage.GetBufferedRegion())
65 
66 itk.imwrite(pasteFilter.GetOutput(), outputFilename)
itk::MedianImageFilter::New
static Pointer New()
itk::ImageFileReader
Data source that reads image data from a single file.
Definition: itkImageFileReader.h:75
itk::PasteImageFilter::New
static Pointer New()
itk::ExtractImageFilter::New
static Pointer New()
itk::Image
Templated n-dimensional image class.
Definition: itkImage.h:86