The core part is as follows. If you specify tiff in the output, it will automatically become a stack file.
import SimpleITK as sitk
reader = sitk.ImageFileReader()
reader.SetImageIO("MetaImageIO")
reader.SetFileName(inputImageFileName)
image = reader.Execute();
writer = sitk.ImageFileWriter()
writer.SetImageIO("TIFFImageIO")
writer.SetFileName(outputImageFileName)
writer.Execute(image)
You can read and write other files by changing SetImageIO
.
To make it easier to use in the terminal, I do the following:
mhd2tif
#!/usr/bin/env python3
import os,sys
import SimpleITK as sitk
if len(sys.argv)!=3 :
print("usage: mhd2tif infile.mhd out.tif")
exit()
inputImageFileName = sys.argv[1]
outputImageFileName = sys.argv[2]
if os.path.isfile(inputImageFileName)==False :
print(inputImageFileName + ": not found.")
exit()
reader = sitk.ImageFileReader()
reader.SetImageIO("MetaImageIO")
reader.SetFileName(inputImageFileName)
image = reader.Execute();
writer = sitk.ImageFileWriter()
writer.SetImageIO("TIFFImageIO")
writer.SetFileName(outputImageFileName)
writer.Execute(image)
https://simpleitk.readthedocs.io/en/master/IO.html