Sharpening and Gradient Operators - iffatAGheyas/computer-vision-handbook GitHub Wiki
✨ Sharpening & Gradient Operators
Enhance image detail by emphasising high-frequency components (edges, fine transitions). Sharpening and gradient filters are fundamental for feature detection and image enhancement.
1. What Is Sharpening?
Sharpening makes images look crisper by boosting edges, details and light-dark transitions. It’s the opposite of blurring—amplifying high-frequency content.
How It Works
Apply a kernel that amplifies the centre pixel while subtracting its neighbours, highlighting intensity changes (edges).
Common 3×3 Sharpening Kernel
K = [ [ 0, -1, 0],
[-1, 5, -1],
[ 0, -1, 0] ]
-
Centre weight: 5 boosts the pixel
-
Surround weights: –1 subtract the neighbours
Python Example: Image Sharpening
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load and convert to RGB
img = cv2.imread("bird.jpg")
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Define sharpening kernel
kernel_sharp = np.array([[ 0, -1, 0],
[-1, 5, -1],
[ 0, -1, 0]], dtype=np.float32)
# Apply filter
sharpened = cv2.filter2D(img_rgb, -1, kernel_sharp)
# Display without axes
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.imshow(img_rgb)
plt.title("Original")
plt.axis("off")
plt.subplot(1, 2, 2)
plt.imshow(sharpened)
plt.title("Sharpened")
plt.axis("off")
plt.tight_layout()
plt.show()
2. Gradient Operators
Gradient operators detect directional intensity changes and are often used before sharpening or as part of edge detection.
Common Gradient Operators
Operator | Kernel Example | Detects |
---|---|---|
Sobel X | [-1, 0, 1] |
Vertical edges |
Sobel Y | [-1, -2, -1] |
Horizontal edges |
Laplacian | 2nd derivative | All-direction edges |
Laplacian Example in Code
import cv2
import matplotlib.pyplot as plt
# Convert to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
# Apply Laplacian operator
lap = cv2.Laplacian(img_gray, cv2.CV_64F)
lap = cv2.convertScaleAbs(lap)
# Display without axes
plt.figure(figsize=(6, 4))
plt.imshow(lap, cmap="gray")
plt.title("Laplacian (2nd Derivative)")
plt.axis("off")
plt.show()
🔍 Sharpening vs Gradient Operators
Technique | Purpose | Output |
---|---|---|
Sharpening | Enhance detail and contrast | Crisper, more defined image |
Sobel / Laplacian | Detect edges or texture transitions | Edge maps |
✅ Summary
Tool | Function | Code |
---|---|---|
Sharpening | Highlight detail | cv2.filter2D() |
Sobel Operator | First derivative (edges) | cv2.Sobel() |
Laplacian | Second derivative (edges) | cv2.Laplacian() |