Bird
Raised Fist0
SciPydata~10 mins

Median and uniform filters in SciPy - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Median and uniform filters
Start with input data array
Choose filter type: median or uniform
Apply filter over sliding window
For each window position:
Median filter
Sort values in window
Pick middle value
Replace center element with filtered value
Move window to next position
Repeat until entire array filtered
Output filtered array
The filter slides a window over data. Median filter picks the middle value in the window. Uniform filter replaces with the average. This smooths or cleans data.
Execution Sample
SciPy
import numpy as np
from scipy.ndimage import median_filter, uniform_filter

arr = np.array([1, 2, 80, 4, 5])
med = median_filter(arr, size=3, mode='nearest')
uni = uniform_filter(arr, size=3, mode='nearest')
This code applies median and uniform filters with window size 3 on a 1D array.
Execution Table
StepWindow PositionWindow ValuesMedian Filter OutputUniform Filter Output
1Indices 0-2[1, 2, 80]227.6667
2Indices 1-3[2, 80, 4]428.6667
3Indices 2-4[80, 4, 5]529.6667
4Edges handled by paddingN/A1 (left), 5 (right)1.3333 (left), 4.6667 (right)
5Final filtered arraysN/A[1, 2, 4, 5, 5][1.3333, 27.6667, 28.6667, 29.6667, 4.6667]
💡 All window positions processed; edges handled by padding; final filtered arrays produced.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
arr[1, 2, 80, 4, 5][1, 2, 80, 4, 5][1, 2, 80, 4, 5][1, 2, 80, 4, 5][1, 2, 80, 4, 5]
median_filter outputN/A[?, 2, ?, ?, ?][?, 2, 4, ?, ?][?, 2, 4, 5, ?][1, 2, 4, 5, 5]
uniform_filter outputN/A[?, 27.6667, ?, ?, ?][?, 27.6667, 28.6667, ?, ?][?, 27.6667, 28.6667, 29.6667, ?][1.3333, 27.6667, 28.6667, 29.6667, 4.6667]
Key Moments - 2 Insights
Why does the median filter output at the edges differ from the middle?
Edges have fewer neighbors, so padding is used. This means the window includes repeated edge values, affecting the median. See execution_table row 4.
Why is the uniform filter output a decimal while the median filter output is an integer?
Uniform filter calculates the average, which can be a decimal. Median filter picks a middle value from the window, which is an existing integer from the array. See execution_table rows 1-3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the median filter output at window position indices 1-3?
A2
B4
C5
D80
💡 Hint
Check execution_table row 2 under 'Median Filter Output'
At which step does the uniform filter output first include the value 28.6667?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at execution_table rows 1-3 under 'Uniform Filter Output'
If the window size changes from 3 to 5, how would the median filter output change?
AIt would use a larger window, so median values might smooth more
BIt would produce the same output as size 3
CIt would only affect uniform filter, not median
DIt would cause an error
💡 Hint
Window size controls how many neighbors are considered, see concept_flow
Concept Snapshot
Median and uniform filters smooth data by sliding a window.
Median filter picks the middle value in the window.
Uniform filter replaces with the average of values.
Edges are handled by padding.
Window size controls smoothing strength.
Full Transcript
Median and uniform filters work by sliding a window over data. For each window, median filter sorts values and picks the middle one, while uniform filter calculates the average. This helps reduce noise or smooth data. Edges are handled by padding to keep window size consistent. The example code applies both filters on a small array with window size 3. The execution table shows how the window moves, what values it sees, and what outputs it produces. Median filter outputs integers from the data, uniform filter outputs averages which can be decimals. Beginners often wonder why edges differ and why outputs differ in type; this is due to padding and calculation methods. Changing window size changes smoothing effect. This visual trace helps understand step-by-step how these filters work.

Practice

(1/5)
1. What is the main purpose of applying a median filter to a dataset?
easy
A. To find the maximum value in the dataset
B. To calculate the average of all values in the dataset
C. To remove noise by replacing each value with the middle value in its neighborhood
D. To sort the dataset in ascending order

Solution

  1. Step 1: Understand median filter function

    A median filter replaces each data point with the median (middle) value of its neighbors, reducing spikes and noise.
  2. Step 2: Compare options with median filter purpose

    Only To remove noise by replacing each value with the middle value in its neighborhood describes replacing values with the middle value in a neighborhood, which matches the median filter's role.
  3. Final Answer:

    To remove noise by replacing each value with the middle value in its neighborhood -> Option C
  4. Quick Check:

    Median filter = middle value replacement [OK]
Hint: Median filter picks middle value to reduce spikes [OK]
Common Mistakes:
  • Confusing median filter with averaging
  • Thinking median filter sorts entire dataset
  • Assuming median filter finds max or min values
2. Which of the following is the correct way to import the median filter function from scipy?
easy
A. from scipy.ndimage import median_filter
B. import scipy.median_filter
C. from scipy import median_filter
D. import median_filter from scipy

Solution

  1. Step 1: Recall scipy median filter import syntax

    The median_filter function is in scipy.ndimage module, so it is imported as from scipy.ndimage import median_filter.
  2. Step 2: Check each option's correctness

    from scipy.ndimage import median_filter matches the correct syntax. The other options are invalid Python import statements.
  3. Final Answer:

    from scipy.ndimage import median_filter -> Option A
  4. Quick Check:

    Correct import = from scipy.ndimage import median_filter [OK]
Hint: Import median_filter from scipy.ndimage module [OK]
Common Mistakes:
  • Trying to import median_filter directly from scipy
  • Using invalid import syntax
  • Confusing module names
3. What is the output of this code snippet?
import numpy as np
from scipy.ndimage import uniform_filter

arr = np.array([1, 2, 3, 4, 5])
result = uniform_filter(arr, size=3)
print(result)
medium
A. [1 2 3 4 5]
B. [1.66666667 2. 3. 4. 4.33333333]
C. [1 2 3 3 3 3]
D. [1 2 2 3 4]

Solution

  1. Step 1: Understand uniform_filter with size=3

    The uniform_filter computes the average over a sliding window of size 3. For edges, it uses 'reflect' mode by default.
  2. Step 2: Calculate each element in result

    Using reflect padding:
    - index 0: [2, 1, 2] avg = 1.66666667
    - index 1: [1, 2, 3] avg = 2.0
    - index 2: [2, 3, 4] avg = 3.0
    - index 3: [3, 4, 5] avg = 4.0
    - index 4: [4, 5, 4] avg = 4.33333333
    print(result) shows [1.66666667 2. 3. 4. 4.33333333]
  3. Final Answer:

    [1.66666667 2. 3. 4. 4.33333333] -> Option B
  4. Quick Check:

    Uniform filter smooths values with reflect padding [OK]
Hint: Uniform filter averages neighbors in window size [OK]
Common Mistakes:
  • Confusing median_filter output with uniform_filter
  • Ignoring edge effects in uniform_filter
  • Expecting original array unchanged
4. Identify the error in this code that applies a median filter:
import numpy as np
from scipy.ndimage import median_filter

arr = np.array([1, 2, 100, 4, 5])
filtered = median_filter(arr, size=0)
print(filtered)
medium
A. missing import for numpy
B. median_filter requires 2D arrays only
C. numpy array must be float type
D. size parameter cannot be zero

Solution

  1. Step 1: Check median_filter size parameter

    The size parameter defines the window size and must be a positive integer. Zero is invalid and causes an error.
  2. Step 2: Verify other code parts

    Array is 1D which is allowed. numpy is imported. Data type can be int. So only size=0 is wrong.
  3. Final Answer:

    size parameter cannot be zero -> Option D
  4. Quick Check:

    Window size > 0 for median_filter [OK]
Hint: Window size must be positive integer [OK]
Common Mistakes:
  • Using zero or negative size values
  • Assuming median_filter only works on 2D arrays
  • Forgetting to import numpy
5. You have a noisy 2D image array with salt-and-pepper noise. Which filter and parameters would best reduce noise while preserving edges?
import numpy as np
from scipy.ndimage import median_filter, uniform_filter

image = np.array([[10, 10, 10, 10],
                  [10, 255, 10, 10],
                  [10, 10, 10, 10],
                  [10, 10, 10, 10]])
hard
A. Use median_filter with size=3 to remove salt-and-pepper noise
B. Use uniform_filter with size=3 to blur the image
C. Use median_filter with size=1 to keep image unchanged
D. Use uniform_filter with size=1 to sharpen edges

Solution

  1. Step 1: Understand noise type and filter effects

    Salt-and-pepper noise is best removed by median filters because they replace each pixel with the median of neighbors, preserving edges.
  2. Step 2: Evaluate filter choices and parameters

    Median_filter with size=3 covers neighbors and removes noise spikes. Uniform_filter averages and blurs edges, not ideal here. Size=1 means no change.
  3. Final Answer:

    Use median_filter with size=3 to remove salt-and-pepper noise -> Option A
  4. Quick Check:

    Median filter + size=3 removes salt-and-pepper noise [OK]
Hint: Median filter removes salt-and-pepper noise best [OK]
Common Mistakes:
  • Using uniform filter which blurs edges
  • Using size=1 which does nothing
  • Confusing noise types and filter effects