changSNR.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """ Changs's method
  2. {chang2005automatic,
  3. title={An automatic method for estimating noise-induced signal variance in magnitude-reconstructed magnetic resonance images},
  4. author={Chang, Lin-Ching and Rohde, Gustavo K and Pierpaoli, Carlo},
  5. booktitle={Medical Imaging},
  6. pages={1136--1142},
  7. year={2005},
  8. organization={International Society for Optics and Photonics}"""
  9. from math import *
  10. import numpy as np
  11. import matplotlib.pyplot as plt
  12. np.seterr(divide='ignore', invalid='ignore')
  13. def calcSNR(img, show, fac):
  14. # Normalize input dataset and plot histogram
  15. # img = np.fliplr(img)
  16. img = img.astype(float)
  17. maxi = img.max()
  18. imgFlat = img.flatten()
  19. imgNorm = imgFlat / maxi
  20. bins = ceil(sqrt(imgNorm.size)) * fac
  21. binCount, binLoc = np.histogram(imgNorm, int(bins))
  22. n = len(imgNorm)
  23. estStd = np.argmax(binCount)
  24. if binCount.max() > 0:
  25. estStd = (estStd) / binCount.shape
  26. x = np.linspace(0, 1, bins)
  27. fhat = np.zeros([1, len(x)])
  28. if binCount.max() > 0:
  29. h = 1.06 * n ** (-1 / 5) * estStd
  30. # define function
  31. gauss = lambda x: gaussianFct(x)
  32. for i in range(n):
  33. # get each kernel function evaluated at x
  34. # centered at data
  35. f = gauss((x - imgNorm[i]) / h)
  36. # plot(x, f / (n * h))
  37. fhat = fhat + f
  38. fhat = fhat / (n * h)
  39. # SNR-Map
  40. maxPos = np.argmax(fhat)
  41. estStdNorm = binLoc[maxPos]
  42. estStd = (binLoc[maxPos] * maxi) / 10
  43. snrMap = np.sqrt(abs(np.square(img) - (np.square(estStd)))) / estStd
  44. if show > 0:
  45. if len(img.shape) == 2:
  46. figChang = plt.figure(3)
  47. plt.imshow(snrMap)
  48. plt.show()
  49. elif len(img.shape) == 3:
  50. figChang = plt.figure(3)
  51. plt.imshow(snrMap[:, :, int(np.ceil(len(img.shape) / 2))])
  52. plt.show()
  53. return snrMap, estStd, estStdNorm
  54. def gaussianFct(x):
  55. y = 1 / sqrt(2 * pi) * np.exp((-(np.square(x))) / 2)
  56. return y