Skip to content
OpenCV

Blur and Filter

Smooth and sharpen images with kernels.

By EZ4Code Team
blurfilterkernel

Code

import cv2
import numpy as np

img = cv2.imread("input.jpg")

# Box blur
blur = cv2.blur(img, (5, 5))

# Gaussian blur (most common)
gauss = cv2.GaussianBlur(img, (5, 5), sigmaX=1.0)

# Median blur (great for salt-and-pepper noise)
median = cv2.medianBlur(img, 5)

# Bilateral filter (edge-preserving)
bilateral = cv2.bilateralFilter(img, d=9, sigmaColor=75, sigmaSpace=75)

# Sharpen with a custom kernel
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
sharpened = cv2.filter2D(img, -1, kernel)

cv2.imwrite("sharpened.jpg", sharpened)

Explanation

Blur variants trade off speed and edge preservation: box and Gaussian are fast and simple, median removes impulse noise, and bilateral smooths while keeping edges. filter2D applies any custom kernel, so a center-positive Laplacian kernel sharpens the image. Kernel size must usually be odd.

More OpenCV Snippets