Hello,
I’m trying to write a DICOM series after some image processing, and to do that I’m following the code in the example.
Since I upsampled the volume, the spacing between slices has changed and I added it to the tags to be modified, here is an extract of the code (after having loaded a sitk image, img
, and its metadata, reader
):
# Initialize writer object
writer = sitk.ImageFileWriter()
# Use the study/series/frame of reference information given in the meta-data
# dictionary and not the automatically generated information from the file IO
writer.KeepOriginalImageUIDOn()
# Copy all the DICOM tags from the first slice
tags_to_copy = reader.GetMetaDataKeys( 0 )
# Get spacing between slices (DICOM tag "0018|0088")
spacing = img.GetSpacing()[2]
# Create list of tuples (tag, values), and add the ones to modify
series_tag_values = [
(k, reader.GetMetaData(0, k))
for k in tags_to_copy
if reader.HasMetaDataKey(0, k)] + \
[ # Tags to modify #
("0018|0088", str(spacing)), # Spacing Between Slices
]
# Save DICOM slices
for i in range( img.GetDepth() ):
image_slice = img[:, :, i]
# Tags shared by the series.
for tag, value in series_tag_values:
image_slice.SetMetaData(tag, unidecode.unidecode(value))
# Slice specific tags.
# Instance Creation Date
image_slice.SetMetaData("0008|0012", time.strftime("%Y%m%d"))
# Instance Creation Time
image_slice.SetMetaData("0008|0013", time.strftime("%H%M%S"))
# Instance Number
image_slice.SetMetaData("0020|0013", str(i))
# Image Position (Patient)
image_slice.SetMetaData("0020|0032", '\\'.join(
map(str, volume.TransformIndexToPhysicalPoint((0, 0, i)))))
# In-Stack Position Number
image_slice.SetMetaData("0020|9057", str(i))
# Write to the output directory and add the extension dcm, to force writing
# in DICOM format.
writer.SetFileName( os.path.join( saving_directory, "IM-" + str(i).zfill(4) + '.dcm') )
writer.Execute(image_slice)
The problem is, if I print the SpacingBetweenSlices metadata juste before the writer execution,
by image_slice.GetMetaData("0018|0088")
, I get the correct spacing, but once the whole volume is written the spacing between slices tag is always changed to 1.
Do you have any clue of what I could be doing wrong?
Thanks!