Sub topic 2
Sharpening with unsharp masking
Prerequisites
This chapter assumes you know basic Python, NumPy array indexing, cv2.imread, and cv2.cvtColor. It also assumes you can tell grayscale images from color images. All examples use 8-bit grayscale images.
Sharpening with unsharp masking
Unsharp masking subtracts a blurred copy from the original to isolate fine detail, then adds that detail back. The weights are 1.5 * image - 0.5 * blur. cv2.addWeighted clips results to 0 to 255, so you do not need manual clipping.
Finding intensity changes with Sobel and Scharr
A gradient measures how quickly intensity changes between neighboring pixels. cv2.Sobel applies a 3x3 derivative kernel along x or y. Request cv2.CV_32F output so negative gradients survive. cv2.Scharr uses a 3x3 kernel with weights chosen for better rotational accuracy.
> Note: The default 8-bit output of cv2.Sobel clips negative gradients to zero. Dark-to-light edges then vanish from the result.
Gradient magnitude and direction
cv2.cartToPolar converts the x and y gradients into a magnitude, sqrt(gx² + gy²), and an angle. Normalize the magnitude before converting it to uint8 for display.
import cv2
import numpy as np
img = cv2.imread("input.jpg")
if img is None:
raise FileNotFoundError("input.jpg could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Unsharp masking
blur = cv2.GaussianBlur(gray, (0, 0), 3)
sharpened = cv2.addWeighted(gray, 1.5, blur, -0.5, 0)
# Sobel gradients in float32, then magnitude and direction
smooth = cv2.GaussianBlur(gray, (5, 5), 0)
gx = cv2.Sobel(smooth, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(smooth, cv2.CV_32F, 0, 1, ksize=3)
mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True)
mag8 = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
# Laplacian in float64 keeps the sign
lap = cv2.Laplacian(smooth, cv2.CV_64F)
lap8 = cv2.convertScaleAbs(lap)
# Canny with low and high hysteresis thresholds
edges = cv2.Canny(smooth, 50, 150)
# Global threshold at 127
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
print(sharpened.shape, mag8.dtype, angle.shape, lap8.dtype, edges.dtype, binary.dtype)The Laplacian and zero-crossing edges
cv2.Laplacian computes the second derivative of intensity. An edge appears where the output changes sign, which is a zero crossing. Use a signed output depth such as cv2.CV_64F. The Laplacian amplifies noise, so blur the image first.
Canny edge detection and hysteresis thresholds
cv2.Canny computes gradients, thins edges to one-pixel ridges, and applies two thresholds. A pixel above the high threshold starts an edge. A pixel between the thresholds is kept only when it connects to a strong edge. Pick a high value about two to three times the low value. Pre-blurring suppresses edges caused by noise. cv2.Canny expects a single-channel 8-bit image.
Global thresholding and the threshold types
cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) sets pixels above 127 to 255 and all others to 0. It returns the threshold value and the output image. THRESH_BINARY_INV reverses the output. THRESH_TRUNC caps values at 127. THRESH_TOZERO zeros values at or below 127. One fixed value fails when lighting varies across the image.
Exercise
Why does cv2.Sobel with the default 8-bit output lose dark-to-light edges, and which output depth fixes it?
Show answer
Negative gradient values are clipped to 0 when stored as unsigned 8-bit. Use cv2.CV32F or cv2.CV64F so signed values survive.