This example contains two use filters for arrays:
def MedianFilter(x,n):
# median filter of array x, length n
# filter behaves pretty well at the edges (shortens the length as needed)
def med(x):
x.sort()
return x[len(x)/2]
# force odd filter order (better filters then)
if n%2==0:
n += 1
nh = n/2
l = len(x)
p = list(x)
for i in range(nh):
v = x[0:n-nh+i]
p[i] = med(v)
for i in range(nh,l-nh):
v = x[i-nh:i-nh+n]
p[i] = med(v)
for i in range(l-nh,l):
v = x[i-nh:l]
p[i] = med(v)
return p
def LowpassFilter(p,N,C):
# N-tap running average, run C times
l = len(p)
if (N%2): N += 1 # N odd: zero phase
NH = N / 2
r = list(p)
for c in range(C):
lpad = [r[0] for i in range(NH)]
rpad = [r[l-1] for i in range(NH)]
rr = lpad + r + rpad
r = [sum(rr[i:i+N])/N for i in range(l)]
return r
|