Python Median Filter for 1D numpy array

29,415

Based on this post, we could create sliding windows to get a 2D array of such windows being set as rows in it. These windows would merely be views into the data array, so no memory consumption and thus would be pretty efficient. Then, we would simply use those ufuncs along each row axis=1.

Thus, for example sliding-median` could be computed like so -

np.median(strided_app(data, window_len,1),axis=1)

For the other ufuncs, just use the respective ufunc names there : np.min, np.max & np.mean. Please note this is meant to give a generic solution to use ufunc supported functionality.

For the best performance, one must still look into specific functions that are built for those purposes. For the four requested functions, we have the builtins, like so -

Median : scipy.signal.medfilt.

Max : scipy.ndimage.filters.maximum_filter1d.

Min : scipy.ndimage.filters.minimum_filter1d.

Mean : scipy.ndimage.filters.uniform_filter1d

Share:
29,415
l.l.
Author by

l.l.

Updated on July 09, 2022

Comments

  • l.l.
    l.l. almost 2 years

    I have a numpy.array with a dimension dim_array. I'm looking forward to obtain a median filter like scipy.signal.medfilt(data, window_len).

    This in fact doesn't work with numpy.array may be because the dimension is (dim_array, 1) and not (dim_array, ).

    How to obtain such filter?

    Next, another question, how can I obtain other filter, i.e., min, max, mean?