geometry.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import numpy
  2. import scipy.interpolate
  3. def getGeometry(img):
  4. origin=numpy.array(img.GetOrigin())
  5. direction=numpy.array(img.GetDirection())
  6. direction=numpy.reshape(direction,(3,3))
  7. spacing=numpy.array(img.GetSpacing())
  8. #print(origin)
  9. #print(direction)
  10. #print(spacing)
  11. class geometry:pass
  12. geometry.origin=origin
  13. geometry.spacing=spacing
  14. geometry.direction=direction
  15. return geometry
  16. def pixelToVector(geometry,pixel):
  17. #accounts for reverse order of coordiantes in numpy array relative to SimpleITK image
  18. return numpy.dot(geometry.direction,numpy.flip(pixel)*geometry.spacing)+geometry.origin
  19. def vectorToPixel(geometry,vector):
  20. #accounts for reverse order of coordinates in numpy array relative to SimpleITK image
  21. return numpy.flip(numpy.dot(geometry.direction.transpose(),vector-geometry.origin)/geometry.spacing)
  22. def toSpace2(spect,gSPECT,ct,gCT,method='linear'):
  23. #convert array spect with geometry gSPECT to an array of size equal to CT w/ corresponding geometry gCT
  24. out=numpy.zeros(ct.shape)
  25. pixels=[]
  26. for i in range(out.shape[0]):
  27. print('{}/{}'.format(i,out.shape[0]))
  28. for j in range(out.shape[1]):
  29. for k in range(out.shape[2]):
  30. pixel=[i,j,k]
  31. v=pixelToVector(gCT,pixel)
  32. pixelSPECT=vectorToPixel(gSPECT,v)
  33. pixels.append(pixelSPECT)
  34. print('Interpolating {} pixels'.format(len(pixels)))
  35. outs=interpolate(spect,pixels,method=method)
  36. print('Done')
  37. m=0
  38. for i in range(out.shape[0]):
  39. for j in range(out.shape[1]):
  40. for k in range(out.shape[2]):
  41. out[i,j,k]=outs[m]
  42. m+=1
  43. return out
  44. def interpolate(ar,c,method='linear'):
  45. points=[numpy.linspace(0.5,ar.shape[i]-0.5,ar.shape[i]) for i in range(3)]
  46. return scipy.interpolate.interpn(points,ar,c,method=method,fill_value=-1,bounds_error=False)