FilterNoise.py 933 B

1234567891011121314151617181920212223242526272829
  1. from scipy.ndimage import convolve1d
  2. from pylab import ceil, zeros, pi, e, exp, sqrt, array
  3. def f(x, s):
  4. """Return the value of a 1D Gaussian function for a given x and scale."""
  5. return exp(-(x ** 2 / (2 * s ** 2))) / (sqrt(2 * pi) * s)
  6. def gauss1(s, order=0):
  7. """Sample a one-dimensional Gaussian function of scale s."""
  8. s = float(s)
  9. r = int(ceil(3 * s))
  10. size = 2 * r + 1
  11. W = zeros(size)
  12. # Sample the Gaussian function
  13. W = array([f(x - r, s) for x in xrange(size)])
  14. if not order:
  15. # Make sure that the sum of all kernel values is equal to one
  16. W /= W.sum()
  17. return W
  18. def filterNoise(image, s):
  19. '''Apply a gaussian blur to an image, to suppress noise.'''
  20. filt = gauss1(s)
  21. image = convolve1d(image.data, filt, axis=0, mode='nearest')
  22. return convolve1d(image, filt, axis=1, mode='nearest')