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

Answer from Divakar on Stack Overflow
Top answer
1 of 2
9

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

2 of 2
1

The fact that applying of a median filter with the window size 1 will not change the array gives us a freedom to apply the median filter row-wise or column-wise.

For example, this code

from scipy.ndimage import median_filter
import numpy as np

arr = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])
median_filter(arr, size=3, cval=0, mode='constant')
#with cval=0, mode='constant' we set that input array is extended with zeros 
#when window overlaps edges, just for visibility and ease of calculation

outputs an expected filtered with window (3, 3) array

array([[0., 2., 0.],
       [2., 5., 3.],
       [0., 5., 0.]])

because median_filter automatically extends the size to all dimensions, so the same effect we can get with:

median_filter(arr, size=(3, 3), cval=0, mode='constant')

Now, we can also apply median_filter row-wise with setting 1 to the first element of size

median_filter(arr, size=(1, 3), cval=0, mode='constant')

Output:

array([[1., 2., 2.],
       [4., 5., 5.],
       [7., 8., 8.]])

And column-wise with the same logic

median_filter(arr, size=(3, 1), cval=0, mode='constant')

Output:

array([[1., 2., 3.],
       [4., 5., 6.],
       [4., 5., 6.]])
🌐
SciPy
docs.scipy.org › doc › scipy › reference › generated › scipy.ndimage.median_filter.html
median_filter — SciPy v1.17.0 Manual
Note that this differs from the conventional definition of the median when n is even. Also, this function does not support the float16 dtype, behavior in the presence of NaNs is undefined, and memory consumption scales with n**4. For float16 support, greater control over the definition of the filter, and to limit memory usage, consider using vectorized_filter with NumPy functions np.median or np.nanmedian.
🌐
SciPy
docs.scipy.org › doc › scipy › reference › generated › scipy.signal.medfilt2d.html
medfilt2d — SciPy v1.17.0 Manual
Apply a median filter to the input array using a local window-size given by kernel_size (must be odd).
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.median.html
numpy.median — NumPy v2.4 Manual
Compute the median along the specified axis · Returns the median of the array elements
🌐
Codepointtech
codepointtech.com › home › numpy median filter: smooth data & images in python
NumPy Median Filter: Smooth Data & Images in Python - codepointtech.com
January 18, 2026 - While educational, it”s not optimized for performance, especially for large 2D images. For practical applications, especially with images, SciPy”s ndimage module provides highly optimized functions. The scipy.ndimage.median_filter is the go-to for this task. import numpy as np from scipy import ndimage import matplotlib.pyplot as plt # Create a sample noisy image (or array) image = np.array([ [10, 20, 30, 40, 50], [15, 25, 150, 45, 55], [20, 180, 35, 60, 65], [25, 30, 40, 70, 75], [30, 35, 45, 80, 90] ], dtype=np.uint8) # Apply the median filter # kernel_size can be a scalar (for square) o
🌐
Stack Overflow
stackoverflow.com › questions › 49740518 › python-median-filter-applied-to-3d-array-to-produce-2d-result
Python median filter applied to 3D array to produce 2D result - Stack Overflow
I have a 3D array of dimension ... a median filter to result in a 2D array (12000x10000). For this, each median calculation should consider a fixed neighborhood window (usually 100x100) and all z-axis values. There are some zero values in the matrix and they should not be considered for the calculation of the median. To proccessing real data, I am using numpy.mem...
Find elsewhere
🌐
NVIDIA
docs.nvidia.com › vpi › algo_median_filter.html
VPI - Vision Programming Interface: Median Filter
March 18, 2026 - The median filter algorithm performs a two dimensional (2D) filter operation on the input image with the provided 2D kernel. The kernel defines the pixel neighborhood for the filtering operation. The filter performs a non linear operation where the pixel it is working on is replaced by the ...
Top answer
1 of 2
2

It looks like you're trying to implement a two-dimensional median filter. The straightforward way to implement such a filter is to have four nested loops: two outer loops over the x and y coordinates of the whole image, and two inner loops over the neighborhood of the center pixel.

It's perhaps easier to describe this in code than in text, so here's some Python-esque pseudocode to illustrate:

# assumptions:
#  * image is a height x width array containing source pixel values
#  * filtered is a height x width array to store result pixel values in
#  * size is an odd number giving the diameter of the filter region

radius = (size - 1) / 2   # size = 3 -> radius = 1

for y from 0 to height-1:
    top = max(y - radius, 0)
    bottom = min(y + radius, height-1)

    for x from 0 to width-1:
        left = max(x - radius, 0)
        right = min(x + radius, width-1) 
        values = new list

        for v from top to bottom:
            for u from left to right:
                add image[v][u] to values

        filtered[y][x] = median(values)

Translating this code into C is left as an exercise.

It's also possible to optimize this code by noting that the neighborhoods of adjacent array cells overlap significantly, so that the values of those neighboring cells can be reused across successive iterations of the outer loops. Since the performance of this algorithm on modern CPUs is essentially limited by RAM access latency, such reuse can provide a significant speedup, especially for large filter sizes.

2 of 2
0

this:

for(i=0;i<size_filter;i++)
for(j=0;j<size_filter;j++)
      temp[i][j]=a[i][j];

is a good starting point. You just iterating over every pixel of your input array, determine the median of the neighborhood and write it to an output array. So instead of temp[i][j]=a[i][j]; you need some WhatEverType calcMedianAt(const WhatEverType a[100][100], int r, int c, int size); function.

So you can call temp[i][j]=calcMedianAt(a, i,j, 3);

the function itself has to extract the value to a list (do proper border handling) and find the median in that list (for example by calling some median function WhatEverType calcMedian(const WhatEverType* data, int len); and return it.

🌐
GitHub
github.com › scipy › scipy › issues › 13509
signal.medfilt2d vs ndimage.median_filter · Issue #13509 · scipy/scipy
February 5, 2021 - So the speed improvement of median_filter still holds for 2D filtering. However with medfilt2d instead of medfilt: import numpy as np from scipy.signal import medfilt2d from scipy.ndimage.filters import median_filter from timeit import Timer sig = np.random.random((362, 362)) t_signal = Timer(lambda: medfilt2d(sig, (9,9))) t_ndimage = Timer(lambda: median_filter(sig, (9,9), mode='constant')) print (t_signal.timeit(number=100)) print (t_ndimage.timeit(number=100)) # both give the same result print(np.allclose(medfilt2d(sig, (9,9)),median_filter(sig, (9,9), mode='constant')))
Author   scipy
🌐
TutorialsPoint
tutorialspoint.com › scipy › scipy_median_filter.htm
SciPy - Median Filter
Following is an example shows how to apply a simple Median Filter on a 2D image or array to remove noise with the help of scipy.ndimage.median_filter() function − · import numpy as np import matplotlib.pyplot as plt from scipy import ndimage ...
🌐
SciPy Lecture Notes
scipy-lectures.org › advanced › image_processing › auto_examples › plot_denoising.html
2.6.8.15. Denoising an image with the median filter — Scipy lecture notes
import numpy as np · from scipy import ndimage · import matplotlib.pyplot as plt · im = np.zeros((20, 20)) im[5:-5, 5:-5] = 1 · im = ndimage.distance_transform_bf(im) im_noise = im + 0.2*np.random.randn(*im.shape) im_med = ndimage.median_filter(im_noise, 3) plt.figure(figsize=(16, 5)) plt.subplot(141) plt.imshow(im, interpolation='nearest') plt.axis('off') plt.title('Original image', fontsize=20) plt.subplot(142) plt.imshow(im_noise, interpolation='nearest', vmin=0, vmax=5) plt.axis('off') plt.title('Noisy image', fontsize=20) plt.subplot(143) plt.imshow(im_med, interpolation='nearest', vm
🌐
Stack Overflow
stackoverflow.com › questions › 48523663 › filter-the-columns-of-a-2d-numpy-array-by-only-one-line › 48524020
python - Filter the columns of a 2d numpy array by only one line - Stack Overflow
I mean I could iterate over each column, make the comparison and then concatenate the column to another 2d numpy array, but that somehow does not feel very ellegant. ... Use np.median to find the median and then np.wheres to find where the indices are bigger than said value.
🌐
machinelearning1
machinelearning1.wordpress.com › 2014 › 07 › 13 › signal-processing-apply-median-filters-python
Signal Processing – Apply Median Filters (Python) | machinelearning1
July 13, 2014 - import numpy as np import scipy as sp import matplotlib.pyplot as plt from scipy import signal t = np.linspace(0,10,200) # create a time signal x1 = np.sin(t) # create a simple sine wave x2 = x1 + np.random.rand(200) # add noise to the signal y1 = sp.signal.medfilt(x2,21) # add noise to the signal # plot the results plt.subplot(2,1,1) plt.plot(t,x2,'yo-') plt.title('input wave') plt.xlabel('time') plt.subplot(2,1,2) plt.plot(range(200),y1,'yo-') plt.title('filtered wave') plt.xlabel('time') plt.show()
🌐
GitHub
gist.github.com › bhawkins › 3535131
1D median filter using numpy · GitHub
1D median filter using numpy. GitHub Gist: instantly share code, notes, and snippets.