loadDicom.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import pydicom
  2. import numpy
  3. import sys
  4. import os
  5. import nibabel
  6. # load the DICOM files
  7. def load(dir):
  8. files = []
  9. print('Loading: {}'.format(dir))
  10. for fname in os.listdir(dir):
  11. print("loading: {}".format(fname))
  12. files.append(pydicom.dcmread(os.path.join(dir,fname)))
  13. print("file count: {}".format(len(files)))
  14. # skip files with no SliceLocation (eg scout views)
  15. slices = []
  16. skipcount = 0
  17. for f in files:
  18. if hasattr(f, 'SliceLocation'):
  19. slices.append(f)
  20. else:
  21. skipcount = skipcount + 1
  22. print("skipped, no SliceLocation: {}".format(skipcount))
  23. # ensure they are in the correct order
  24. slices = sorted(slices, key=lambda s: s.SliceLocation)
  25. return slices;
  26. # pixel aspects, assuming all slices are the same
  27. for s in slices:
  28. print("Pixel spacing: {}".format(s.PixelSpacing))
  29. return;
  30. def convertToNIfTI(slices):
  31. # create 3D array
  32. img_shape = list(slices[0].pixel_array.shape)
  33. img_shape.append(len(slices))
  34. img3d = numpy.zeros(img_shape)
  35. # get position and orientation parameters
  36. x0=numpy.array([float(f) for f in slices[0].ImagePositionPatient])
  37. x1=numpy.array([float(f) for f in slices[-1].ImagePositionPatient])
  38. n=(x1-x0)/(len(slices)-1.);
  39. f=numpy.array([float(f) for f in slices[0].ImageOrientationPatient])
  40. s=numpy.array([float(f) for f in slices[0].PixelSpacing])
  41. #create affine
  42. a=numpy.zeros((4,4))
  43. f1=numpy.zeros(4)
  44. f1[0:3]=f[0:3]
  45. #swap to account for row/column to (c,r) position mismatch
  46. a[:,1]=f1*s[1]
  47. f2=numpy.zeros(4)
  48. f2[0:3]=f[3:6]
  49. a[:,0]=f2*s[0]
  50. nn=numpy.zeros(4)
  51. nn[0:3]=n[0:3]
  52. a[:,2]=nn
  53. xn=numpy.ones(4)
  54. xn[0:3]=x0[0:3]
  55. a[:,3]=xn
  56. # fill 3D array with the images from the files
  57. for i, s in enumerate(slices):
  58. img2d = s.pixel_array
  59. img3d[:, :, i] = img2d
  60. #orientation and pixel spacing
  61. img = nibabel.Nifti1Image(img3d, a)
  62. return img