Sub topic 6
Sharpening with Unsharp Masking
Assume you know basic Python, NumPy arrays, grayscale images, and OpenCV image loading. You should also understand that a filter applies a kernel to nearby pixels. Sharpening builds on smoothing: it uses a blurred image to find and strengthen fine detail.
What unsharp masking does
Unsharp masking is a sharpening method. Despite its name, it does not make an image less sharp. It creates a blurred copy, subtracts that copy from the original, and adds part of the difference back:
sharpened = original + amount × (original - blurred)
The difference image contains rapid intensity changes, such as object boundaries and small details. Adding it increases contrast around those changes.
A Gaussian blur is commonly used because it removes high-frequency noise while producing smooth transitions.
Applying it in OpenCV
The sigma argument controls the blur radius. A larger value removes broader detail, so the sharpening effect reaches larger structures. The two weights in cv2.addWeighted control the result:
1.5keeps the original image and adds detail.-0.5subtracts part of the blurred image.- Together, these weights implement
1.5 × original - 0.5 × blur.
import cv2
img = cv2.imread("input.jpg")
if img is None:
raise FileNotFoundError("input.jpg could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (0, 0), 3)
sharpened = cv2.addWeighted(gray, 1.5, blur, -0.5, 0)
if not cv2.imwrite("sharpened.jpg", sharpened):
raise IOError("Could not write sharpened.jpg")cv2.addWeighted handles numeric saturation safely for an 8-bit image. Pixel values below 0 become 0, and values above 255 become 255. This avoids the wraparound errors that can occur when subtracting directly in a uint8 NumPy array.
Choosing the amount
A stronger sharpening amount makes edges more visible, but it can create halos. A halo is a bright or dark outline beside a real edge. Try values such as these:
| Original weight | Blur weight | Result |
|---|---|---|
| 1.2 | -0.2 | Mild sharpening |
| 1.5 | -0.5 | Moderate sharpening |
| 2.0 | -1.0 | Strong sharpening with greater halo risk |
Sharpening does not restore information that the camera never captured. It only increases local contrast. It also amplifies sensor noise, JPEG artifacts, and compression blocks. Blur noisy images first, and inspect the result at its actual display size.
For color images, sharpening each BGR channel separately can produce colored halos. A safer approach is to convert the image to a luminance space such as Lab, sharpen only its lightness channel, and convert back.
Exercise
Why does unsharp masking use a blurred copy instead of directly increasing every pixel value?
Show answer
The blurred copy helps isolate local intensity changes, so sharpening increases edge contrast and fine detail rather than simply making the whole image brighter.