SimpleITK  1.3.0.dev466
Python/DicomSeriesReader2.py
1 #!/usr/bin/env python
2 
3 #=========================================================================
4 #
5 # Copyright Insight Software Consortium
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0.txt
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 #
19 #=========================================================================
20 
21 
22 #
23 # This example shows how to read a specific series from a Dicom directory that
24 # may contain more than one series. The script scans for all series. If an
25 # output name is given, it writes out the requested series. If no specific
26 # series name is given, the first series found is written.
27 #
28 
29 from __future__ import print_function
30 
31 import sys, getopt
32 import SimpleITK as sitk
33 
34 target_series = ""
35 output_image = ""
36 
37 def usage():
38  print ( "\nUsage: %s [-s series_name] input_directory [output_image]\n" % (sys.argv[0]) )
39 
40 # Parse command line options
41 try:
42  opts, args = getopt.getopt(sys.argv[1:], "s:", [ "series" ] )
43 except getopt.GetoptError as err:
44  usage()
45  sys.exit(1)
46 
47 for o, a in opts:
48  if o in ("-s", "--series"):
49  target_series = a
50  else:
51  assert False, "unhandled options"
52 
53 
54 # Get input/output names
55 if len(args) < 1:
56  print( args )
57  usage()
58  sys.exit(1)
59 
60 input_directory = args[0]
61 if len(args)>1:
62  output_image = args[1]
63 
64 # Find the Dicom series
65 reader = sitk.ImageSeriesReader()
66 written = False
67 
68 series_found = reader.GetGDCMSeriesIDs(input_directory)
69 
70 # Process each Dicom series
71 if len(series_found):
72 
73  for serie in series_found:
74 
75  print( "\nSeries:", serie )
76 
77  # Get the Dicom filename corresponding to the current series
78  dicom_names = reader.GetGDCMSeriesFileNames(input_directory, serie)
79 
80  print( "\nFiles in series: ", dicom_names )
81 
82  if len(dicom_names):
83  reader.SetFileNames(dicom_names)
84  image = reader.Execute()
85  print( "\nImage size: ", image.GetSize() )
86 
87  if (output_image != "") and not written:
88  if (target_series == "" or target_series == serie):
89 
90  print( "\nWriting", output_image )
91  sitk.WriteImage(image, output_image)
92  written = True
93 else:
94  sys.exit(1)
95 
96 print ()