19 """ A SimpleITK example demonstrating how to write a DICOM series. """
25 import SimpleITK
as sitk
27 pixel_dtypes = {
"int16": np.int16,
"float64": np.float64}
30 def writeSlices(series_tag, in_image, out_dir, i):
31 """ Write slices to output directory """
32 image_slice = in_image[:, :, i]
37 lambda tag_value: image_slice.SetMetaData(tag_value[0], tag_value[1]),
44 image_slice.SetMetaData(
"0008|0012", time.strftime(
"%Y%m%d"))
46 image_slice.SetMetaData(
"0008|0013", time.strftime(
"%H%M%S"))
50 image_slice.SetMetaData(
"0008|0060",
"CT")
55 image_slice.SetMetaData(
57 "\\".join(map(str, in_image.TransformIndexToPhysicalPoint((0, 0, i)))),
60 image_slice.SetMetaData(
"0020|0013", str(i))
64 writer.SetFileName(os.path.join(out_dir, str(i) +
".dcm"))
65 writer.Execute(image_slice)
72 +
" <output_directory> ["
73 +
", ".join(pixel_dtypes)
80 pixel_dtype = pixel_dtypes[sys.argv[2]]
82 pixel_dtype = pixel_dtypes[
"int16"]
84 new_arr = np.random.uniform(-10, 10, size=(3, 4, 5)).astype(pixel_dtype)
85 new_img = sitk.GetImageFromArray(new_arr)
86 new_img.SetSpacing([2.5, 3.5, 4.5])
102 writer.KeepOriginalImageUIDOn()
104 modification_time = time.strftime(
"%H%M%S")
105 modification_date = time.strftime(
"%Y%m%d")
111 direction = new_img.GetDirection()
112 series_tag_values = [
113 (
"0008|0031", modification_time),
114 (
"0008|0021", modification_date),
115 (
"0008|0008",
"DERIVED\\SECONDARY"),
118 "1.2.826.0.1.3680043.2.1125." + modification_date +
".1" + modification_time,
137 (
"0008|103e",
"Created-SimpleITK"),
140 if pixel_dtype == np.float64:
145 rescale_slope = 0.001
146 series_tag_values = series_tag_values + [
147 (
"0028|1053", str(rescale_slope)),
158 lambda i: writeSlices(series_tag_values, new_img, sys.argv[1], i),
159 range(new_img.GetDepth()),
166 data_directory = sys.argv[1]
167 series_IDs = sitk.ImageSeriesReader.GetGDCMSeriesIDs(data_directory)
170 'ERROR: given directory "'
172 +
'" does not contain a DICOM series.'
175 series_file_names = sitk.ImageSeriesReader.GetGDCMSeriesFileNames(
176 data_directory, series_IDs[0]
180 series_reader.SetFileNames(series_file_names)
187 series_reader.LoadPrivateTagsOn()
188 image3D = series_reader.Execute()
189 print(image3D.GetSpacing(),
"vs", new_img.GetSpacing())