📌 What is a Filter / Kernel / Mask?
- A filter (also called a kernel or mask) is a small matrix of numbers used to transform an image.
- Purpose: Emphasize features like edges, textures, or smooth out noise.
- Filters are applied via convolution or correlation.
- In convolution, the filter “slides” over the image and computes a weighted sum of the neighborhood pixels.
🔍 Types of Filters and Their Effects
- Common uses:
- Smoothing / Blurring: Reduces noise and softens details.
- Sharpening: Enhances edges and contrast.
- Edge Detection: Identifies boundaries of regions in an image.
- Typical filter sizes: \( 3 \times 3 \), \( 5 \times 5 \), \( 7 \times 7 \)
- Each filter value is a weight that controls the influence of surrounding pixels.
🧮 Mathematics of Convolution
The convolution of an image \( I \) with a filter \( K \) is defined as:
\[
(I * K)(x, y) = \sum_{i} \sum_{j} I(x+i, y+j) \cdot K(i, j)
\]
Where:
- \( I \): input image
- \( K \): filter (kernel/mask)
- \( (x, y) \): coordinates of the output pixel
- \( (i, j) \): filter index offsets
- Place the filter on the image patch.
- Multiply overlapping values.
- Sum results and assign to the output.
- Move the filter and repeat for the entire image.
🧪 Example: 3×3 Mean Filter on Image Patch
Image patch:
\[
I = \begin{bmatrix}
10 & 20 & 30 \\
40 & 50 & 60 \\
70 & 80 & 90
\end{bmatrix}
\]
Mean filter kernel:
\[
K = \frac{1}{9}
\begin{bmatrix}
1 & 1 & 1 \\
1 & 1 & 1 \\
1 & 1 & 1
\end{bmatrix}
\]
Convolution result at center pixel (2,2):
\[
(I * K)(2,2) = \frac{1}{9}(10 + 20 + 30 + 40 + 50 + 60 + 70 + 80 + 90) = 50
\]
🔧 Common Filter Kernels
Sobel X (Edge Detection):
\[
\begin{bmatrix}
-1 & 0 & 1 \\
-2 & 0 & 2 \\
-1 & 0 & 1
\end{bmatrix}
\]
Sobel Y (Edge Detection):
\[
\begin{bmatrix}
-1 & -2 & -1 \\
0 & 0 & 0 \\
1 & 2 & 1
\end{bmatrix}
\]
Sharpening Filter:
\[
\begin{bmatrix}
0 & -1 & 0 \\
-1 & 5 & -1 \\
0 & -1 & 0
\end{bmatrix}
\]
🐍 Python Hands-on: Manual Convolution
import numpy as np
# Image patch
I = np.array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
# 3x3 mean filter
K = np.ones((3, 3)) / 9
# Manual convolution (center pixel)
center_pixel = np.sum(I * K)
print("Center pixel value:", center_pixel)
📸 Apply Kernel to a Real Image (OpenCV)
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Load grayscale image
img = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE)
# Define 3x3 mean kernel
K = np.ones((3, 3), np.float32) / 9
# Apply convolution
filtered = cv2.filter2D(img, -1, K)
# Display images
plt.subplot(1,2,1), plt.imshow(img, cmap='gray'), plt.title('Original')
plt.subplot(1,2,2), plt.imshow(filtered, cmap='gray'), plt.title('Filtered')
plt.show()
Video
📡 Follow PostNetwork Academy
- 🌐 Website: www.postnetwork.co
- 🎥 YouTube: YouTube Channel
- 📘 Facebook: Facebook Page
- 💼 LinkedIn: LinkedIn Page
- 💻 GitHub: GitHub Repositories
🙏 Thank You!
We hope this article helped you understand filters, kernels, and convolution in image processing. Stay tuned for more!