Spatial Filters Averaging filter and Median filter in Image Processing (original) (raw)

Last Updated : 15 Jun, 2026

Spatial filtering is an image processing technique that modifies pixel values using information from neighboring pixels. It is commonly used to reduce noise, smooth images and improve overall image quality.

Working of Spatial Filtering

Spatial filtering processes an image by applying a filter kernel to a small neighborhood of pixels. The following steps illustrate the process

**1. Select a Neighborhood: Consider the following 3 × 3 pixel neighborhood. Here, 20 is the center pixel.

12 15 18

14 20 22

16 19 24

**2. Apply the Filter Kernel: A filter kernel examines the center pixel and its neighboring pixels. Depending on the filter type, it performs a calculation such as computing the average or median value.

**3. Replace the Center Pixel: The calculated value replaces the original center pixel value (20).

**4. Repeat Across the Image: The kernel moves across the image and repeats the same process for every pixel, producing a new filtered image.

Image Smoothing Using Spatial Filters

1. Averaging Filter (Mean Filter)

**Implementation

import cv2 import matplotlib.pyplot as plt

image = cv2.imread('image path') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

filtered_image = cv2.blur(image, (5, 5))

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1) plt.imshow(image) plt.title("Original Image") plt.axis('off')

plt.subplot(1, 2, 2) plt.imshow(filtered_image) plt.title("Averaging Filter") plt.axis('off')

plt.show()

`

**Output:

Average-filter

Average Filter

2. Median Filter

**Implementation

import cv2 import matplotlib.pyplot as plt

image = cv2.imread('image path') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

filtered_image = cv2.medianBlur(image, 5)

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1) plt.imshow(image) plt.title("Original Image") plt.axis('off')

plt.subplot(1, 2, 2) plt.imshow(filtered_image) plt.title("Median Filter") plt.axis('off')

plt.show()

`

**Output:

Median-Filter

Median Filter

You can download full code from here

Feature Averaging Filter Median Filter
Filter Type Linear filter that uses arithmetic averaging. Non linear filter that uses median values.
Operation Replaces the center pixel with the average of neighboring pixels. Replaces the center pixel with the median of neighboring pixels.
Image Quality Produces a smoother image with some loss of detail. Reduces noise while maintaining image details.
Processing Speed Computationally simpler and generally faster. Slightly more computationally intensive and slower.

Applications

Advantages

Limitations