SimpleITK: how to save dicom header into nii.gz file?

I can save data into nii.gz file, but I find that the saved file do not include the dicom header information.

For example:

I load a mha as following:

reader = sitk.ImageFileReader()
position = reader.GetMetaData("0020|0032")

And the printed information is what I want:


Then, I save the image into nii.gz file:

sitk.WriteImage(sitk_img, fileName="test.nii.gz")

And it succeed.

Then, I load this nii.gz file, and want to print 0020|0032 information:

reader = sitk.ImageFileReader()
position = reader.GetMetaData("0020|0032")

A bug is reported:

Traceback (most recent call last):
  File "D:\Program Files\JetBrains\PyCharm Community Edition 2019.3.4\plugins\python-ce\helpers\pydev\", line 1434, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "D:\Program Files\JetBrains\PyCharm Community Edition 2019.3.4\plugins\python-ce\helpers\pydev\_pydev_imps\", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/MLoong/Desktop/medpro/Demo/", line 19, in <module>
    position = reader.GetMetaData("0020|0032")
  File "D:\Anaconda3\envs\gitlab_medpro\lib\site-packages\SimpleITK\", line 5827, in GetMetaData
    return _SimpleITK.ImageFileReader_GetMetaData(self, key)
RuntimeError: Exception thrown in SimpleITK ImageFileReader_GetMetaData: D:\a\1\sitk-build\ITK\Modules\Core\Common\src\itkMetaDataDictionary.cxx:77:
itk::ERROR: Key '0020|0032' does not exist 

How can I save dicom header information into nii.gz file? Any suggestion is appreciated~~~

Hello @zhang-qiang-github,

Not sure here what you are trying to do. You refer to a DICOM tag (image-position-patient, 0020|0032) but code appears to read a file in another format (mha), not sure what is going on here.

Also when reading a set of 2D slices in DICOM format into a 3D volume, each of the slices has this tag, but once you have a volume and save it to a single file (nii.gz) which of the tags should you keep? In any case, this value is readily obtained from the image itself on a per slice basis:

# read nii.gz volume
i = 5 # slice number six

Nifti format has a very limited and hardcoded metadata it supports. If you save to .mha or .nrrd you should be able to load the matadata you read from DICOM.