-
-
Save nickv2002/459e4dfd94ae2b221c7d to your computer and use it in GitHub Desktop.
1-Dimentional Mean and Median Filters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
def medfilt (x, k): | |
"""Apply a length-k median filter to a 1D array x. | |
Boundaries are extended by repeating endpoints. | |
""" | |
import numpy as np | |
assert k % 2 == 1, "Median filter length must be odd." | |
assert x.ndim == 1, "Input must be one-dimensional." | |
k2 = (k - 1) // 2 | |
y = np.zeros ((len (x), k), dtype=x.dtype) | |
y[:,k2] = x | |
for i in range (k2): | |
j = k2 - i | |
y[j:,i] = x[:-j] | |
y[:j,i] = x[0] | |
y[:-j,-(i+1)] = x[j:] | |
y[-j:,-(i+1)] = x[-1] | |
return np.median (y, axis=1) | |
def meanfilt (x, k): | |
"""Apply a length-k mean filter to a 1D array x. | |
Boundaries are extended by repeating endpoints. | |
""" | |
import numpy as np | |
assert k % 2 == 1, "Median filter length must be odd." | |
assert x.ndim == 1, "Input must be one-dimensional." | |
k2 = (k - 1) // 2 | |
y = np.zeros ((len (x), k), dtype=x.dtype) | |
y[:,k2] = x | |
for i in range (k2): | |
j = k2 - i | |
y[j:,i] = x[:-j] | |
y[:j,i] = x[0] | |
y[:-j,-(i+1)] = x[j:] | |
y[-j:,-(i+1)] = x[-1] | |
return np.mean (y, axis=1) | |
if __name__ == '__main__': | |
def test (): | |
import pylab as p | |
x = np.linspace (0, 1, 101) | |
x[3::10] = 1.5 | |
p.plot (x) | |
p.plot (meanfilt(x,3)) | |
p.plot (medfilt (x,3)) | |
p.show () | |
test () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment