0
0
SciPydata~5 mins

Median and uniform filters in SciPy

Choose your learning style9 modes available
Introduction

Median and uniform filters help clean noisy data by smoothing values. They make data easier to understand and analyze.

Removing salt-and-pepper noise from images or signals
Smoothing sensor data to reduce random fluctuations
Preparing data for better pattern detection
Reducing noise in time series data before forecasting
Syntax
SciPy
from scipy.ndimage import median_filter, uniform_filter

median_filter(input_array, size)
uniform_filter(input_array, size)

input_array is your data, like a list or array of numbers.

size controls how many neighbors to include when filtering.

Examples
Applies median filter with window size 3 to smooth out the large spike (80).
SciPy
median_filter([1, 2, 80, 4, 5], size=3)
Applies uniform filter averaging neighbors to smooth data.
SciPy
uniform_filter([1, 2, 80, 4, 5], size=3)
Median filter on 2D data with window size 2.
SciPy
median_filter([[10, 200], [30, 40]], size=2)
Sample Program

This code shows how median and uniform filters smooth noisy 1D data. The median filter removes spikes by picking the middle value in each window. The uniform filter averages neighbors to smooth values.

SciPy
import numpy as np
from scipy.ndimage import median_filter, uniform_filter

# Create noisy data
data = np.array([1, 2, 80, 4, 5, 100, 6, 7, 8])

# Apply median filter with window size 3
median_result = median_filter(data, size=3)

# Apply uniform filter with window size 3
uniform_result = uniform_filter(data, size=3)

print("Original data:", data)
print("Median filter result:", median_result)
print("Uniform filter result:", uniform_result)
OutputSuccess
Important Notes

The median filter is good at removing sudden spikes without blurring edges too much.

The uniform filter smooths by averaging, which can blur sharp changes.

Choose the filter and window size based on your data and noise type.

Summary

Median and uniform filters help reduce noise in data.

Median filter picks the middle value in a window to remove spikes.

Uniform filter averages values in a window to smooth data.