ITK  5.0.0
Insight Segmentation and Registration Toolkit
SphinxExamples/src/IO/GDCM/ReadDICOMSeriesAndWrite3DImage/Code.py
1 #!/usr/bin/env python
2 
3 # Copyright Insight Software Consortium
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 os
19 
20 import itk
21 
22 if len(sys.argv) < 2:
23  print("Usage: " + sys.argv[0] +
24  " [DicomDirectory [outputFileName [seriesName]]]")
25  print("If DicomDirectory is not specified, current directory is used\n")
26 
27 # current directory by default
28 dirName = '.'
29 if len(sys.argv) > 1:
30  dirName = sys.argv[1]
31 
32 PixelType = itk.ctype('signed short')
33 Dimension = 3
34 
35 ImageType = itk.Image[PixelType, Dimension]
36 
37 namesGenerator = itk.GDCMSeriesFileNames.New()
38 namesGenerator.SetUseSeriesDetails(True)
39 namesGenerator.AddSeriesRestriction("0008|0021")
40 namesGenerator.SetGlobalWarningDisplay(False)
41 namesGenerator.SetDirectory(dirName)
42 
43 seriesUID = namesGenerator.GetSeriesUIDs()
44 
45 if len(seriesUID) < 1:
46  print('No DICOMs in: ' + dirName)
47  sys.exit(1)
48 
49 print('The directory: ' + dirName)
50 print('Contains the following DICOM Series: ')
51 for uid in seriesUID:
52  print(uid)
53 
54 seriesFound = False
55 for uid in seriesUID:
56  seriesIdentifier = uid
57  if len(sys.argv) > 3:
58  seriesIdentifier = sys.argv[3]
59  seriesFound = True
60  print('Reading: ' + seriesIdentifier)
61  fileNames = namesGenerator.GetFileNames(seriesIdentifier)
62 
63  reader = itk.ImageSeriesReader[ImageType].New()
64  dicomIO = itk.GDCMImageIO.New()
65  reader.SetImageIO(dicomIO)
66  reader.SetFileNames(fileNames)
67  reader.ForceOrthogonalDirectionOff()
68 
69  writer = itk.ImageFileWriter[ImageType].New()
70  outFileName = os.path.join(dirName, seriesIdentifier + '.nrrd')
71  if len(sys.argv) > 2:
72  outFileName = sys.argv[2]
73  writer.SetFileName(outFileName)
74  writer.UseCompressionOn()
75  writer.SetInput(reader.GetOutput())
76  print('Writing: ' + outFileName)
77  writer.Update()
78 
79  if seriesFound:
80  break