Sitemap
Chandu Vengala

Chandu Vengala

BLURRING

6 min readOct 23, 2025

--

What is Mean (Average) Blurring?

Mean blurring (often called average blur or box blur) replaces each pixel by the average of the pixels in a neighbourhood (kernel) around it. It’s a simple low-pass filter that smooths an image by removing high-frequency noise and small details.

Intuition: for each pixel you look at a k×k window centered on that pixel, compute the mean of all pixel values inside that window, and set the center pixel to that mean.

Mathematical definition (per-channel)

For a grayscale image I, the mean-blurred output J at pixel (x,y) with kernel size k×k:

J(x,y) = \frac{1}{k^2} \sum_{i=-r}^{r}\sum_{j=-r}^{r} I(x+i, y+j)

where r = (k-1)/2. For color images, apply per channel (B, G, R).

Example for k=3 (3×3 kernel): the center pixel becomes the average of those 9 neighboring values.

OpenCV functions you can use

1. cv2.blur() — simple average filter

dst = cv2.blur(src, ksize, anchor=(-1,-1), borderType=cv2.BORDER_DEFAULT)

ksize is (kwidth, kheight) (e.g., (5,5)).

anchor default centers the kernel.

borderType controls how border pixels are handled.

2. cv2.boxFilter() — more flexible box filter

dst = cv2.boxFilter(src, ddepth, ksize, normalize=True, anchor=(-1,-1), borderType=cv2.BORDER_DEFAULT)

If normalize=True it behaves like cv2.blur() (averaging).

If normalize=False it computes the sum over the window (useful in some algorithms).

ddepth usually -1 to keep same depth (uint8 → uint8).

When to use Mean Blurring

  • Simple noise smoothing when you don’t care about preserving edges.
  • Preprocessing to reduce tiny speckle noise.
  • Fast approximations of more complex blurs in low-cost applications or when you need uniform smoothing.

Performance & optimization tips

cv2.blur() and cv2.boxFilter() are optimized C implementations — use them, not manual Python loops.

For large kernels, cv2.boxFilter() internally uses fast algorithms (sometimes separable or integral-image optimizations).

You can apply separable filters with cv2.sepFilter2D() by doing 1D horizontal and 1D vertical convolution — this reduces complexity from O(k^2) to O(k) per dimension.

For real-time or large images, choose smaller kernels or GPU-accelerated implementations.

Pros

  • Very simple and fast.
  • Easy to implement and understand.
  • Good for quick smoothing and removing weak high-frequency noise.

Cons

  • Does not preserve edges (blurs across edges).
  • Produces uniform blur that can look unnatural.
  • Not good for impulse noise (salt-and-pepper) — median blur is better.

What is Median Blurring?

Median blurring replaces each pixel with the median value of the neighboring pixels within a kernel window.
Unlike mean blur (which averages values), the median filter preserves edges and removes impulse noise (salt-and-pepper noise) very effectively.

Intuition: sort all pixel values under the kernel and pick the middle value (median).
This makes it resistant to extreme outliers (noisy pixels with very high or low intensity).

Mathematical definition

For each pixel (x, y):

J(x,y) = \text{median}{ I(x+i, y+j) \mid i,j \in [-r, r] }

where the kernel size is k×k and r = (k-1)/2.

OpenCV function

cv2.medianBlur()

dst = cv2.medianBlur(src, ksize)

src: input image (8-bit or floating-point)

ksize: aperture linear size — must be odd and > 1 (e.g., 3, 5, 7…)

When to use Median Blurring

  • When your image contains salt-and-pepper noise (random black and white dots).
  • When you want to smooth without blurring edges.
  • Useful in preprocessing before contour detection or thresholding.

Pros:

  • Excellent at removing impulse noise.
  • Preserves edges much better than mean blur.
  • Easy to use, only one parameter (ksize).

Cons:

  • Slower for large kernels.
  • May slightly distort thin lines or small details.

Press enter or click to view image in full size

Press enter or click to view image in full size

Press enter or click to view image in full size

what is Gaussian Blurring?

Gaussian Blurring is a technique used to smooth images and reduce noise by averaging pixel values with a Gaussian-weighted kernel.

Unlike Mean Blur, which gives equal weight to all pixels in the kernel, Gaussian Blur gives higher weight to the center pixels and less to the surrounding pixels — resulting in a more natural and soft blur.

It is one of the most commonly used filters in computer vision for noise reduction and preprocessing before operations like edge detection.

Mathematical Definition

Get Chandu Vengala’s stories in your inbox

Join Medium for free to get updates from this writer.

The 2D Gaussian function is defined as:

G(x, y) = \frac{1}{2\pi\sigma²} e^{-\frac{x² + y²}{2\sigma²}}

σ (sigma) controls how much smoothing occurs.

Small σ → less blur

Large σ → stronger blur

The kernel size k×k is usually chosen based on σ (e.g., k ≈ 6σ + 1).

Each pixel in the output image is computed by convolving the input image with this Gaussian kernel.

J(x,y) = \sum_{i=-r}^{r} \sum_{j=-r}^{r} G(i,j) \cdot I(x+i, y+j)

OpenCV Function

cv2.GaussianBlur()

dst = cv2.GaussianBlur(src, ksize, sigmaX, sigmaY=0, borderType=cv2.BORDER_DEFAULT)

Parameters:

Parameter Description src Input image ksize Kernel size (width, height) — must be odd (e.g., (3,3), (5,5)) sigmaX Standard deviation in X direction sigmaY Standard deviation in Y direction (if 0, uses sigmaX) borderType Specifies how image borders are handled

If both sigmaX and sigmaY are 0, OpenCV automatically calculates them based on the kernel size.

When to Use Gaussian Blur

  • Before edge detection (e.g., Canny or Sobel)
  • To remove Gaussian noise
  • To create a smooth background
  • As a preprocessing step for object detection, thresholding, or contour detection

Pros

  • Produces natural, smooth blurring
  • Reduces Gaussian-type noise
  • Preserves edges better than mean blur
  • Widely used and mathematically stable

Cons

  • Slightly slower than mean blur
  • Can still blur edges slightly
  • Requires careful choice of σ and kernel size
import cv2
import numpy as np
# Read the image
img = cv2.imread('cats_dogs.jpg')
# - - Mean (Average) Blur - -
mean_blur = cv2.blur(img, (5, 5))
# - - Gaussian Blur - -
gaussian_blur = cv2.GaussianBlur(img, (5, 5), 0)
# - - Median Blur - -
median_blur = cv2.medianBlur(img, 5)
# Show all images
cv2.imshow('Original Image', img)
cv2.imshow('Mean Blur', mean_blur)
cv2.imshow('Gaussian Blur', gaussian_blur)
cv2.imshow('Median Blur', median_blur)
# Wait until a key is pressed, then close all windows
cv2.waitKey(0)
cv2.destroyAllWindows()

Notes:

  • (5,5) → blur kernel size.
  • larger = more blur.
  • In median blur, kernel size must be an odd number (e.g., 3, 5, 7).
  • cv2.waitKey(0) keeps the image windows open until you press any key.

Press enter or click to view image in full sizefect 👍 — here’s a clear, compact explanation of Grayscaling of Images using OpenCV — simplified and formatted for easy learning (like your other OpenCV notes).

Grayscaling of Images

Definition:
Grayscaling is the process of converting a color image (RGB/BGR) into shades of gray — from black (0) to white (255).
Each pixel now carries only intensity information, not color.

Why Grayscale?

  • Fewer dimensions: RGB has 3 channels; grayscale has only 1.
  • Simpler & faster: Reduces data for processing or ML models.
  • Essential step: Many image processing algorithms (e.g., edge detection, thresholding) require grayscale input.

Methods to Convert Image to Grayscale

Method 1: Using cv2.cvtColor()

import cv2
# Read the image in color (default)
image = cv2.imread('tomatoes.jpg')
# Convert to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Display result
cv2.imshow('Grayscale', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation:

cv2.imread() → reads image (BGR by default).

cv2.cvtColor() → converts color spaces.

cv2.COLOR_BGR2GRAY → transforms 3 channels → 1 channel (intensity).

Method 2: Directly load image in grayscale using flag = 0

import cv2
# Directly load in grayscale
img = cv2.imread('tomatoes.jpg', 0)
cv2.imshow('Grayscale Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation:The flag 0 in cv2.imread() loads the image directly in grayscale mode.

Method 3.1: Weighted Method (Realistic Conversion)

This method mimics human eye perception, which is more sensitive to green and less to blue.
Gray = 0.2989R + 0.5870G + 0.1140B

import cv2
img = cv2.imread('tomatoes.jpg')
rows, cols = img.shape[:2]
for i in range(rows):
for j in range(cols):
gray = 0.2989 * img[i, j][2] + 0.5870 * img[i, j][1] + 0.1140 * img[i, j][0]
img[i, j] = [gray, gray, gray]
cv2.imshow('Weighted Grayscale', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation:

  • Access each pixel and compute weighted average.
  • [2]=R, [1]=G, [0]=B in OpenCV’s BGR order.
  • Assign [gray, gray, gray] to keep 3-channel display compatibility.
  • Produces realistic grayscale (but slower than OpenCV’s built-in method).

Method 3.2: Average Method (Simple but less accurate)

This takes a simple mean of RGB values.

import cv2
img = cv2.imread('tomatoes.jpg')
rows, cols = img.shape[:2]
for i in range(rows):
for j in range(cols):
gray = (img[i, j, 0] + img[i, j, 1] + img[i, j, 2]) / 3
img[i, j] = [gray, gray, gray]
cv2.imshow('Average Grayscale', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation:

  • Simple averaging: (B + G + R) / 3.
  • Faster to understand, but not visually accurate (ignores eye sensitivity).

Quick Tip:

If you just need grayscale for any processing, always prefer:

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

--

--