Hi,
In the following simple piece of code I’m trying to read a DICOM image as sitkImage and its tags as a python dictionary. then I call another function to write that image in another location with the same tags reading from the dictionary.
yet the output dicom folder is shown as 180 separate slices in the output folder (when I open the folder with a DICOM viewer) and not as a single multi slice image.
here’s the code:
import SimpleITK as sitk
import sys, os, json, time
dicom_directory = "D:\\0-image_orig"
output_directory = "D:\\1-image_copy"
#reads DICOM, returns dicom tags and image3D
def read_dicom_tags(dicom_dir):
series_IDs = sitk.ImageSeriesReader.GetGDCMSeriesIDs(dicom_dir)
series_file_names = sitk.ImageSeriesReader.GetGDCMSeriesFileNames(
dicom_dir, series_IDs[0])
series_reader = sitk.ImageSeriesReader()
series_reader.SetFileNames(series_file_names)
series_reader.MetaDataDictionaryArrayUpdateOn()
series_reader.LoadPrivateTagsOn()
image = series_reader.Execute()
tags_dict = {}
for j, key in enumerate(series_reader.GetMetaDataKeys(1)):
if(key != "ITK_non_uniform_sampling_deviation"):
tags_dict[key] = series_reader.GetMetaData(0, key)
dicom_tags_file_address = os.path.join(dicom_dir, '../', dicom_dir.split('\\')[-1]+'_tags.json')
with open(os.path.join(dicom_dir, '../', dicom_dir.split('\\')[-1]+'_tags.json'), 'w') as f:
json.dump(tags_dict, f)
return dicom_tags_file_address, tags_dict, image
#writes image3D with the dicom tags
def write_dicom_image_with_tags(image, dicom_tags, output_dir):
for i in range(image.GetDepth()):
writer = sitk.ImageFileWriter()
writer.KeepOriginalImageUIDOn()
image_slice = image[:, :, i]
# Tags shared by the series.
for j, key in enumerate(dicom_tags):
image_slice.SetMetaData(key, dicom_tags[key])
# Write to the output directory and add the extension dcm, to force writing in DICOM format.
image_slice.SetMetaData("0008|0012", time.strftime("%Y%m%d")) # Instance Creation Date
image_slice.SetMetaData("0008|0013", time.strftime("%H%M%S")) # Instance Creation Time
image_slice.SetMetaData("0020|0032", '\\'.join(map(str,image3D.TransformIndexToPhysicalPoint((0,0,i))))) # Image Position (Patient)
image_slice.SetMetaData("0020,0013", str(i)) # Instance Number
writer.SetFileName(os.path.join(output_dir, str(i) + '.dcm'))
writer.Execute(image_slice)
tagsFile, tagsDict, image3D = read_dicom_tags(dicom_directory)
write_dicom_image_with_tags(image3D, tagsDict, output_directory)
any thoughts on what am I missing in here?
Thanks in advance