Learning/IVP/Session 05
Session 05🔲

Spatial Filtering

Convolution-based filters for noise reduction, subsampling, and image smoothing.


Learning Objectives

  • Apply simple linear filters via convolution
  • Subsample images using filter matrices
  • Reduce Gaussian noise with mean filters
  • Handle salt-and-pepper noise with min/max filters

Convolution with Simple Filters

Convolution slides a kernel over the image and computes a weighted sum at each position. Common kernels include box (average), sharpening, and edge detection filters. scipy.signal.convolve2d or cv2.filter2D perform this.

Ex5_1 — Apply simple filtersPython
import cv2
import numpy as np
from scipy.signal import convolve2d

img = cv2.imread('noisy.jpg', cv2.IMREAD_GRAYSCALE).astype(np.float64) / 255.0

# Simple 3x3 averaging (box) filter
box_filter = np.ones((3, 3)) / 9.0

# Simple identity
identity = np.array([[0,0,0],[0,1,0],[0,0,0]], dtype=np.float64)

# Sharpening filter
sharpen = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]], dtype=np.float64)

result_box = convolve2d(img, box_filter, mode='same', boundary='symm')

Subsampling Using Filters

Subsampling reduces image resolution by keeping only every n-th pixel. Using a filter to average before downsampling avoids aliasing. A 2:1 ratio cuts width and height in half.

Ex5_2 — Subsample with filter matricesPython
# Subsample 2:1 with row filter
H, W = img.shape

row_filter = np.zeros((1, W))
row_filter[0, ::2] = 1  # keep every other column

col_filter = np.zeros((H, 1))
col_filter[::2, 0] = 1  # keep every other row

# Apply via convolution then extract non-zero rows/cols
sub_img = img[::2, ::2]   # simple decimation

Noise Reduction with Mean Filter

Gaussian noise can be reduced by averaging neighboring pixels. A larger kernel = more smoothing but more blurring. The mean filter computes the average of a neighborhood. cv2.blur() or cv2.GaussianBlur() implement this.

Ex5_3 — Mean filter for Gaussian noisePython
# Add Gaussian noise
noise = np.random.normal(0, 0.05, img.shape)
noisy_img = np.clip(img + noise, 0, 1)

# 3x3 mean filter
mean_3 = cv2.blur((noisy_img * 255).astype(np.uint8), (3, 3))

# 7x7 mean filter
mean_7 = cv2.blur((noisy_img * 255).astype(np.uint8), (7, 7))

Salt & Pepper Noise with Min/Max Filter

Salt (white) and pepper (black) noise are isolated pixels at extreme intensity values. Min filter removes salt noise (replaces with neighborhood minimum). Max filter removes pepper noise (replaces with neighborhood maximum). Median filter handles both at once.

Ex5_4 — Min/Max filter for salt & pepperPython
from scipy.ndimage import minimum_filter, maximum_filter, median_filter

# Salt noise (white dots) → use min filter
result_min = minimum_filter(img_salt, size=5)

# Pepper noise (black dots) → use max filter
result_max = maximum_filter(img_pepper, size=5)

# Both → median filter
result_median = median_filter(img_noisy, size=5)