Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

OpenCV Python Image Filtering Tutorial: Blur, Gaussian, Median & Sharpening Explained

OpenCV Python – Image Filtering

Image filtering is an important technique in OpenCV used to improve image quality, remove noise, and enhance features. Filters are widely used in image processing, computer vision, and AI applications.

In this tutorial, you will learn different types of image filters using OpenCV Python.


1. What is Image Filtering?

Image filtering is the process of modifying an image to:

  • Remove noise
  • Enhance edges
  • Smooth details
  • Improve visual quality

It works by applying a kernel (matrix) over an image.


2. Import OpenCV

import cv2

3. Read an Image

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

cv2.imshow("Original Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

4. Average Blur Filter

Syntax:

cv2.blur(image, (kernel_size, kernel_size))

Example:

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

cv2.imshow("Average Blur", blur)
cv2.waitKey(0)
cv2.destroyAllWindows()

5. Gaussian Blur

Gaussian blur is more natural and widely used.

gaussian = cv2.GaussianBlur(img, (5, 5), 0)

cv2.imshow("Gaussian Blur", gaussian)
cv2.waitKey(0)
cv2.destroyAllWindows()

6. Median Blur

Best for removing salt-and-pepper noise.

median = cv2.medianBlur(img, 5)

cv2.imshow("Median Blur", median)
cv2.waitKey(0)
cv2.destroyAllWindows()

7. Bilateral Filter

Preserves edges while smoothing the image.

bilateral = cv2.bilateralFilter(img, 9, 75, 75)

cv2.imshow("Bilateral Filter", bilateral)
cv2.waitKey(0)
cv2.destroyAllWindows()

8. Image Sharpening

Sharpening enhances edges and details.

import numpy as np

kernel = np.array([[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]])

sharpened = cv2.filter2D(img, -1, kernel)

cv2.imshow("Sharpened Image", sharpened)
cv2.waitKey(0)
cv2.destroyAllWindows()

9. Custom Kernel Filtering

You can define your own filter:

kernel = np.ones((3,3), np.float32) / 9

filtered = cv2.filter2D(img, -1, kernel)

10. Why Image Filtering is Important

Image filtering is used in:

  • Noise reduction
  • Image enhancement
  • Object detection preprocessing
  • Medical image processing
  • Computer vision pipelines

11. Common Mistakes

❌ Wrong kernel size

✔ Solution:

  • Use odd values like 3, 5, 7

❌ Over-blurring image

✔ Solution:

  • Reduce kernel size for better results

12. Conclusion

Image filtering in OpenCV Python is essential for improving image quality and preparing images for advanced computer vision tasks. From blur to sharpening, filters help control image clarity and detail.

Once you master filtering, you can move to edge detection and feature extraction.




Post a Comment

0 Comments