SimpleITK  
DicomSeriesReadModifyWrite/DicomSeriesReadModifySeriesWrite.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 
20 import SimpleITK as sitk
21 
22 import sys
23 import time
24 import os
25 
26 if len(sys.argv) < 3:
27  print(
28  "Usage: python "
29  + __file__
30  + " <input_directory_with_DICOM_series> <output_directory>"
31  )
32  sys.exit(1)
33 
34 # Read the original series. First obtain the series file names using the
35 # image series reader.
36 data_directory = sys.argv[1]
37 series_IDs = sitk.ImageSeriesReader.GetGDCMSeriesIDs(data_directory)
38 if not series_IDs:
39  print(
40  'ERROR: given directory "'
41  + data_directory
42  + '" does not contain a DICOM series.'
43  )
44  sys.exit(1)
45 series_file_names = sitk.ImageSeriesReader.GetGDCMSeriesFileNames(
46  data_directory, series_IDs[0]
47 )
48 
49 series_reader = sitk.ImageSeriesReader()
50 series_reader.SetFileNames(series_file_names)
51 
52 # Configure the reader to load all of the DICOM tags (public+private):
53 # By default tags are not loaded (saves time).
54 # By default if tags are loaded, the private tags are not loaded.
55 # We explicitly configure the reader to load tags, including the
56 # private ones.
57 series_reader.MetaDataDictionaryArrayUpdateOn()
58 series_reader.LoadPrivateTagsOn()
59 image3D = series_reader.Execute()
60 
61 # Modify the image (blurring)
62 filtered_image = sitk.DiscreteGaussian(image3D)
63 
64 # Write the 3D image as a series
65 # IMPORTANT: There are many DICOM tags that need to be updated when you modify
66 # an original image. This is a delicate operation and requires
67 # knowledge of the DICOM standard. This example only modifies some.
68 # For a more complete list of tags that need to be modified see:
69 # http://gdcm.sourceforge.net/wiki/index.php/Writing_DICOM
70 
71 writer = sitk.ImageFileWriter()
72 # Use the study/series/frame of reference information given in the meta-data
73 # dictionary and not the automatically generated information from the file IO
74 writer.KeepOriginalImageUIDOn()
75 
76 # Copy relevant tags from the original meta-data dictionary (private tags are
77 # also accessible).
78 tags_to_copy = [
79  "0010|0010", # Patient Name
80  "0010|0020", # Patient ID
81  "0010|0030", # Patient Birth Date
82  "0020|000D", # Study Instance UID, for machine consumption
83  "0020|0010", # Study ID, for human consumption
84  "0008|0020", # Study Date
85  "0008|0030", # Study Time
86  "0008|0050", # Accession Number
87  "0008|0060", # Modality
88 ]
89 
90 modification_time = time.strftime("%H%M%S")
91 modification_date = time.strftime("%Y%m%d")
92 
93 # Copy some of the tags and add the relevant tags indicating the change.
94 # For the series instance UID (0020|000e), each of the components is a number,
95 # cannot start with zero, and separated by a '.' We create a unique series ID
96 # using the date and time.
97 # NOTE: DICOM tags represent hexadecimal numbers, so 0020|000D and 0020|000d
98 # are equivalent. The ITK/SimpleITK dictionary is string based, so these
99 # are two different keys, case sensitive. When read from a DICOM file the
100 # hexadecimal string representations are in lower case, so we check for
101 # existence and get the value after converting to lower case.
102 # Tags of interest:
103 direction = filtered_image.GetDirection()
104 series_tag_values = [
105  (k, series_reader.GetMetaData(0, k.lower()))
106  for k in tags_to_copy
107  if series_reader.HasMetaDataKey(0, k.lower())
108 ] + [
109  ("0008|0031", modification_time), # Series Time
110  ("0008|0021", modification_date), # Series Date
111  ("0008|0008", "DERIVED\\SECONDARY"), # Image Type
112  (
113  "0020|000e",
114  "1.2.826.0.1.3680043.2.1125." + modification_date + ".1" + modification_time,
115  ),
116  # Series Instance UID
117  (
118  "0020|0037",
119  "\\".join(
120  map(
121  str,
122  (
123  direction[0],
124  direction[3],
125  direction[6],
126  direction[1],
127  direction[4],
128  direction[7],
129  ), # Image Orientation (Patient)
130  )
131  ),
132  ),
133  (
134  "0008|103e",
135  series_reader.GetMetaData(0, "0008|103e")
136  if series_reader.HasMetaDataKey(0, "0008|103e")
137  else "" + " Processed-SimpleITK",
138  ), # Series Description is an optional tag, so may not exist
139 ]
140 
141 for i in range(filtered_image.GetDepth()):
142  image_slice = filtered_image[:, :, i]
143  # Tags shared by the series.
144  for tag, value in series_tag_values:
145  image_slice.SetMetaData(tag, value)
146  # Slice specific tags.
147  # Instance Creation Date
148  image_slice.SetMetaData("0008|0012", time.strftime("%Y%m%d"))
149  # Instance Creation Time
150  image_slice.SetMetaData("0008|0013", time.strftime("%H%M%S"))
151  # Image Position (Patient)
152  image_slice.SetMetaData(
153  "0020|0032",
154  "\\".join(map(str, filtered_image.TransformIndexToPhysicalPoint((0, 0, i)))),
155  )
156  # Instance Number
157  image_slice.SetMetaData("0020|0013", str(i))
158 
159  # Write to the output directory and add the extension dcm, to force writing
160  # in DICOM format.
161  writer.SetFileName(os.path.join(sys.argv[2], str(i) + ".dcm"))
162  writer.Execute(image_slice)
163 sys.exit(0)
itk::simple::DiscreteGaussian
Image DiscreteGaussian(const Image &image1, std::vector< double > variance=std::vector< double >(3, 1.0), unsigned int maximumKernelWidth=32u, std::vector< double > maximumError=std::vector< double >(3, 0.01), bool useImageSpacing=true)
Blurs an image by separable convolution with discrete gaussian kernels. This filter performs Gaussian...
itk::simple::ImageSeriesReader
Read series of image files into a SimpleITK image.
Definition: sitkImageSeriesReader.h:55
itk::simple::ImageFileWriter
Write out a SimpleITK image to the specified file location.
Definition: sitkImageFileWriter.h:48