0
0
Computer Visionml~5 mins

Blurring and smoothing (Gaussian, median, bilateral) in Computer Vision

Choose your learning style9 modes available
Introduction

Blurring and smoothing help reduce noise and details in images. This makes images easier to analyze or look nicer.

To remove small spots or noise from photos taken in low light.
To prepare images before detecting edges or shapes.
To smooth skin in portrait photos for a softer look.
To reduce detail before compressing images to save space.
Syntax
Computer Vision
cv2.GaussianBlur(src, ksize, sigmaX)
cv2.medianBlur(src, ksize)
cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace)

src is the input image.

ksize is the size of the filter window (must be odd number).

d is the diameter of each pixel neighborhood used during filtering (for bilateralFilter).

sigmaColor is filter sigma in the color space (for bilateralFilter).

sigmaSpace is filter sigma in the coordinate space (for bilateralFilter).

Examples
Applies Gaussian blur with a 5x5 window and automatic sigma.
Computer Vision
blurred = cv2.GaussianBlur(image, (5, 5), 0)
Applies median blur with a 3x3 window to remove salt-and-pepper noise.
Computer Vision
median = cv2.medianBlur(image, 3)
Applies bilateral filter preserving edges while smoothing.
Computer Vision
bilateral = cv2.bilateralFilter(image, 9, 75, 75)
Sample Model

This code creates a noisy image and applies three types of blurring. It prints the average pixel brightness to show smoothing effects.

Computer Vision
import cv2
import numpy as np

# Create a noisy image (black with white noise)
image = np.random.randint(0, 256, (100, 100), dtype=np.uint8)

# Apply Gaussian blur
gaussian = cv2.GaussianBlur(image, (5, 5), 0)

# Apply Median blur
median = cv2.medianBlur(image, 5)

# Apply Bilateral filter
bilateral = cv2.bilateralFilter(image, 9, 75, 75)

# Calculate mean pixel values to compare smoothing effect
print(f"Original mean: {np.mean(image):.2f}")
print(f"Gaussian mean: {np.mean(gaussian):.2f}")
print(f"Median mean: {np.mean(median):.2f}")
print(f"Bilateral mean: {np.mean(bilateral):.2f}")
OutputSuccess
Important Notes

Gaussian blur uses a weighted average giving more importance to nearby pixels.

Median blur replaces each pixel with the median of neighbors, good for salt-and-pepper noise.

Bilateral filter smooths while keeping edges sharp, useful for photos.

Summary

Blurring reduces noise and detail in images.

Gaussian, median, and bilateral filters each smooth images differently.

Choose the filter based on the noise type and whether you want to keep edges.