SimpleITK  
DicomSeriesFromArray/DicomSeriesFromArray.py
1 # =========================================================================
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 # =========================================================================
18 
19 import SimpleITK as sitk
20 
21 import sys
22 import time
23 import os
24 import numpy as np
25 
26 pixel_dtypes = {"int16": np.int16, "float64": np.float64}
27 
28 
29 def writeSlices(series_tag_values, new_img, out_dir, i):
30  image_slice = new_img[:, :, i]
31 
32  # Tags shared by the series.
33  list(
34  map(
35  lambda tag_value: image_slice.SetMetaData(tag_value[0], tag_value[1]),
36  series_tag_values,
37  )
38  )
39 
40  # Slice specific tags.
41  # Instance Creation Date
42  image_slice.SetMetaData("0008|0012", time.strftime("%Y%m%d"))
43  # Instance Creation Time
44  image_slice.SetMetaData("0008|0013", time.strftime("%H%M%S"))
45 
46  # Setting the type to CT so that the slice location is preserved and
47  # the thickness is carried over.
48  image_slice.SetMetaData("0008|0060", "CT")
49 
50  # (0020, 0032) image position patient determines the 3D spacing between
51  # slices.
52  # Image Position (Patient)
53  image_slice.SetMetaData(
54  "0020|0032",
55  "\\".join(map(str, new_img.TransformIndexToPhysicalPoint((0, 0, i)))),
56  )
57  # Instance Number
58  image_slice.SetMetaData("0020|0013", str(i))
59 
60  # Write to the output directory and add the extension dcm, to force
61  # writing in DICOM format.
62  writer.SetFileName(os.path.join(out_dir, str(i) + ".dcm"))
63  writer.Execute(image_slice)
64 
65 
66 if len(sys.argv) < 3:
67  print(
68  "Usage: python "
69  + __file__
70  + " <output_directory> ["
71  + ", ".join(pixel_dtypes)
72  + "]"
73  )
74  sys.exit(1)
75 
76 # Create a new series from a numpy array
77 try:
78  pixel_dtype = pixel_dtypes[sys.argv[2]]
79 except KeyError:
80  pixel_dtype = pixel_dtypes["int16"]
81 
82 new_arr = np.random.uniform(-10, 10, size=(3, 4, 5)).astype(pixel_dtype)
83 new_img = sitk.GetImageFromArray(new_arr)
84 new_img.SetSpacing([2.5, 3.5, 4.5])
85 
86 # Write the 3D image as a series
87 # IMPORTANT: There are many DICOM tags that need to be updated when you modify
88 # an original image. This is a delicate operation and requires
89 # knowledge of the DICOM standard. This example only modifies some.
90 # For a more complete list of tags that need to be modified see:
91 # http://gdcm.sourceforge.net/wiki/index.php/Writing_DICOM
92 # If it is critical for your work to generate valid DICOM files,
93 # It is recommended to use David Clunie's Dicom3tools to validate
94 # the files:
95 # http://www.dclunie.com/dicom3tools.html
96 
97 writer = sitk.ImageFileWriter()
98 # Use the study/series/frame of reference information given in the meta-data
99 # dictionary and not the automatically generated information from the file IO
100 writer.KeepOriginalImageUIDOn()
101 
102 modification_time = time.strftime("%H%M%S")
103 modification_date = time.strftime("%Y%m%d")
104 
105 # Copy some of the tags and add the relevant tags indicating the change.
106 # For the series instance UID (0020|000e), each of the components is a number,
107 # cannot start with zero, and separated by a '.' We create a unique series ID
108 # using the date and time. Tags of interest:
109 direction = new_img.GetDirection()
110 series_tag_values = [
111  ("0008|0031", modification_time), # Series Time
112  ("0008|0021", modification_date), # Series Date
113  ("0008|0008", "DERIVED\\SECONDARY"), # Image Type
114  (
115  "0020|000e",
116  "1.2.826.0.1.3680043.2.1125." + modification_date + ".1" + modification_time,
117  ), # Series Instance UID
118  (
119  "0020|0037",
120  "\\".join(
121  map(
122  str,
123  (
124  direction[0],
125  direction[3],
126  direction[6],
127  direction[1],
128  direction[4],
129  direction[7],
130  ),
131  )
132  ),
133  ), # Image Orientation
134  # (Patient)
135  ("0008|103e", "Created-SimpleITK"), # Series Description
136 ]
137 
138 if pixel_dtype == np.float64:
139  # If we want to write floating point values, we need to use the rescale
140  # slope, "0028|1053", to select the number of digits we want to keep. We
141  # also need to specify additional pixel storage and representation
142  # information.
143  rescale_slope = 0.001 # keep three digits after the decimal point
144  series_tag_values = series_tag_values + [
145  ("0028|1053", str(rescale_slope)), # rescale slope
146  ("0028|1052", "0"), # rescale intercept
147  ("0028|0100", "16"), # bits allocated
148  ("0028|0101", "16"), # bits stored
149  ("0028|0102", "15"), # high bit
150  ("0028|0103", "1"),
151  ] # pixel representation
152 
153 # Write slices to output directory
154 list(
155  map(
156  lambda i: writeSlices(series_tag_values, new_img, sys.argv[1], i),
157  range(new_img.GetDepth()),
158  )
159 )
160 
161 # Re-read the series
162 # Read the original series. First obtain the series file names using the
163 # image series reader.
164 data_directory = sys.argv[1]
165 series_IDs = sitk.ImageSeriesReader.GetGDCMSeriesIDs(data_directory)
166 if not series_IDs:
167  print(
168  'ERROR: given directory "'
169  + data_directory
170  + '" does not contain a DICOM series.'
171  )
172  sys.exit(1)
173 series_file_names = sitk.ImageSeriesReader.GetGDCMSeriesFileNames(
174  data_directory, series_IDs[0]
175 )
176 
177 series_reader = sitk.ImageSeriesReader()
178 series_reader.SetFileNames(series_file_names)
179 
180 # Configure the reader to load all of the DICOM tags (public+private):
181 # By default tags are not loaded (saves time).
182 # By default if tags are loaded, the private tags are not loaded.
183 # We explicitly configure the reader to load tags, including the
184 # private ones.
185 series_reader.LoadPrivateTagsOn()
186 image3D = series_reader.Execute()
187 print(image3D.GetSpacing(), "vs", new_img.GetSpacing())
188 sys.exit(0)
itk::simple::ImageSeriesReader
Read series of image files into a SimpleITK image.
Definition: sitkImageSeriesReader.h:68
itk::simple::ImageFileWriter
Write out a SimpleITK image to the specified file location.
Definition: sitkImageFileWriter.h:51