parseNPZ.py 987 B

12345678910111213141516171819202122232425262728293031
  1. import SimpleITK
  2. import numpy
  3. import os
  4. def convertToITK(dt,label):
  5. #convert to SimpleITKimage to display it
  6. imgArray=dt[label]
  7. org=dt['{}origin'.format(label)]
  8. orient=dt['{}orientation'.format(label)]
  9. spacing=[numpy.linalg.norm(x) for x in orient]
  10. print(spacing)
  11. orient=[orient[i]/spacing[i] for i in range(3)]
  12. direction=numpy.reshape(orient,9)
  13. print(direction)
  14. img = SimpleITK.GetImageFromArray(imgArray)
  15. img.SetOrigin(org)
  16. img.SetDirection(direction)
  17. img.SetSpacing(spacing)
  18. return img
  19. def generateNiftyFromNPZ(infile):
  20. #generate nifty files for PET and CT stored in NPZ
  21. outdir=os.path.dirname(infile)
  22. baseName=os.path.basename(infile).replace('.npz','')
  23. dt=numpy.load(infile)
  24. ct=convertToITK(dt,'CT')
  25. pet=convertToITK(dt,'PET')
  26. SimpleITK.WriteImage(ct,os.path.join(outdir,f'{baseName}_CT.nii.gz'))
  27. SimpleITK.WriteImage(pet,os.path.join(outdir,f'{baseName}_PET.nii.gz'))
  28. del pet
  29. del ct