One-dimensional median filter (median filter)

A median filter often used in image processing. With OpenCV for a two-dimensional array of images median = cv2.medianBlur(img,5) It can be processed just by.

If there are outliers in one-dimensional data such as time series data, It can be removed with a median filter. I can't find any function for 1D median filter in numpy or opencv. I made a note because I devised a little. After extracting the area where the median is selected for each point in the index and making it a two-dimensional array, Applying np.median in the row direction.

median.py


import numpy as np
import matplotlib.pyplot as plt

#Median filter for one-dimensional arrays
#k is the size of the filter and is odd
def median1d(arr, k):
    w = len(arr)
    idx = np.fromfunction(lambda i, j: i + j, (k, w), dtype=np.int) - k // 2
    idx[idx < 0] = 0
    idx[idx > w - 1] = w - 1
    return np.median(arr[idx], axis=0)

#Sine wave with outliers
x = np.sin(np.arange(1000) / 50)
x[np.random.randint(0, len(x), 20)] += np.random.randn(20) * 3

#filtering
y = median1d(x, 5)

plt.figure(1)
plt.clf()
plt.subplot(2, 1, 1)
plt.plot(x)
plt.ylim([-3, 3])
plt.subplot(2, 1, 2)
plt.plot(y)
plt.ylim([-3, 3])

image.png

Recommended Posts

One-dimensional median filter (median filter)
Median filter using xarray (median filter)
Image processing with Python 100 knock # 10 median filter