Blurring and smoothing help reduce noise and details in images. This makes images easier to analyze or look nicer.
Blurring and smoothing (Gaussian, median, bilateral) in 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).
blurred = cv2.GaussianBlur(image, (5, 5), 0)
median = cv2.medianBlur(image, 3)bilateral = cv2.bilateralFilter(image, 9, 75, 75)
This code creates a noisy image and applies three types of blurring. It prints the average pixel brightness to show smoothing effects.
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}")
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.
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.