0
0
Computer-visionHow-ToBeginner ยท 3 min read

How to Blur Image Using OpenCV in Computer Vision

To blur an image in OpenCV, use the cv2.GaussianBlur() function which applies a Gaussian filter to smooth the image. You provide the image, kernel size, and standard deviation to control the blur effect.
๐Ÿ“

Syntax

The main function to blur images in OpenCV is cv2.GaussianBlur(). It takes three key arguments:

  • src: The input image to blur.
  • ksize: The size of the Gaussian kernel as a tuple (width, height). Both must be positive odd numbers.
  • sigmaX: Standard deviation in the X direction; controls the blur strength.

Optionally, you can specify sigmaY (default is 0, which means same as sigmaX).

python
blurred_image = cv2.GaussianBlur(src=image, ksize=(5, 5), sigmaX=0)
๐Ÿ’ป

Example

This example loads an image, applies Gaussian blur with a 7x7 kernel, and shows the original and blurred images side by side.

python
import cv2
import numpy as np

# Load image from file
image = cv2.imread('input.jpg')

# Check if image loaded
if image is None:
    raise ValueError('Image not found or path is incorrect')

# Apply Gaussian blur with 7x7 kernel
blurred = cv2.GaussianBlur(image, (7, 7), sigmaX=0)

# Stack images horizontally for comparison
combined = np.hstack((image, blurred))

# Show the images
cv2.imshow('Original (Left) vs Blurred (Right)', combined)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
A window opens showing the original image on the left and the blurred image on the right.
โš ๏ธ

Common Pitfalls

  • Using an even number for ksize will cause an error; kernel size must be odd and positive.
  • Setting sigmaX too low (like 0) lets OpenCV calculate it automatically, but very small kernels may produce little blur.
  • Not checking if the image loaded correctly can cause crashes.
  • Using cv2.blur() applies a simple average blur, which is less smooth than Gaussian blur.
python
import cv2

# Wrong: even kernel size causes error
# blurred = cv2.GaussianBlur(image, (4, 4), 0)  # This will raise an error

# Correct: odd kernel size
blurred = cv2.GaussianBlur(image, (5, 5), 0)
๐Ÿ“Š

Quick Reference

FunctionPurposeKey Parameters
cv2.GaussianBlur()Applies Gaussian blur to smooth imagesrc, ksize (odd tuple), sigmaX
cv2.blur()Applies average blur (box filter)src, ksize
cv2.medianBlur()Applies median blur to reduce noisesrc, ksize (odd integer)
โœ…

Key Takeaways

Use cv2.GaussianBlur() with an odd-sized kernel to blur images smoothly.
Kernel size controls blur strength; larger kernels produce more blur.
Always check if the image loaded correctly before processing.
Avoid even kernel sizes to prevent errors in GaussianBlur.
cv2.blur() is simpler but less smooth than GaussianBlur.