Sub topic 6
Sharpening with Unsharp Masking
This chapter assumes you can read an image with cv2.imread, that you know NumPy array shapes and dtypes, and that you have seen cv2.GaussianBlur from the smoothing chapters. It covers how unsharp masking works, how to control it, and where it fails.
The idea: add back the detail that blurring removes
Sharpening makes edges look crisper by boosting the fine detail in an image. Unsharp masking does this in three steps:
- Blur the image. The blur keeps broad shapes and removes fine detail.
- Subtract the blur from the original. The result is the fine detail, often called the detail layer or mask.
- Add some multiple of that detail back to the original.
The name comes from darkroom photography, where a blurred ("unsharp") negative was used as a mask. The digital version is a formula:
sharpened = original + amount * (original - blurred)Rearranging gives an equivalent form with two weights:
sharpened = (1 + amount) * original - amount * blurredThis second form is what cv2.addWeighted computes. With amount = 0.5, the weights are 1.5 on the original and -0.5 on the blurred copy. The weights sum to 1, so flat regions keep their brightness. Only places where the original and the blur differ, which are edges and texture, change.
A first implementation
import cv2
import numpy as np
img = cv2.imread("input.jpg") # BGR, uint8
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)Three details matter here.
- Kernel size
(0, 0). When you pass(0, 0)as the kernel size, OpenCV computes the size fromsigmaX. HeresigmaXis 3, so you set the blur scale directly and OpenCV picks a kernel wide enough to hold it. - The weights.
addWeighted(src1, alpha, src2, beta, gamma)computessrc1*alpha + src2*beta + gamma. A negativebetasubtracts the blur. - Saturation. For
uint8images,addWeightedrounds the result and clamps it to the range 0 to 255. Without this, a pixel that should be 270 would wrap around to 14 if you did the arithmetic in raw NumPyuint8. That wrap-around would produce bright specks turning dark.
The three controls
Unsharp masking has three parameters. Each one changes the result in a different way.
| Parameter | What it controls | Too low | Too high |
|---|---|---|---|
| Blur sigma (radius) | Size of the detail that gets boosted | Only the finest grain is boosted, so the effect is hard to see | Large halos around edges, and broad tonal contrast changes |
| Amount | Strength of the boost | No visible change | Overshoot, clipped highlights and shadows, harsh edges |
| Threshold (optional) | Minimum difference that counts as detail | Noise is boosted along with real edges | Soft edges are left unsharpened |
The first two are built into the addWeighted call. The threshold is not, and you have to add it yourself.
Sigma sets which detail you boost
A small sigma such as 1 produces a blur that differs from the original only at the finest scale, so you boost pixel-level texture. A large sigma such as 5 or 10 means the difference includes bigger structures, so you boost local contrast across whole regions. For crisp edges on a typical photo, a sigma between 1 and 3 is a common starting range. Treat these numbers as starting points, since the right value depends on image resolution.
Amount sets how hard you push
Write the formula with a variable so you can try several strengths on the same image:
def unsharp(gray, sigma=3.0, amount=0.5):
blur = cv2.GaussianBlur(gray, (0, 0), sigma)
return cv2.addWeighted(gray, 1.0 + amount, blur, -amount, 0)
mild = unsharp(gray, sigma=2.0, amount=0.5)
strong = unsharp(gray, sigma=2.0, amount=1.5)This function accepts a uint8 image and returns one. It works on a single channel, so a BGR image needs the handling described later in this chapter.
Threshold stops noise from being boosted
Plain unsharp masking boosts every difference between the image and its blur. In a flat but noisy region, those differences are noise, so the noise gets stronger. A threshold fixes this by applying the boost only where the difference is large enough to be an edge:
def unsharp_threshold(gray, sigma=3.0, amount=1.0, threshold=5):
blur = cv2.GaussianBlur(gray, (0, 0), sigma)
# Work in float32 so the difference can be negative.
g = gray.astype(np.float32)
b = blur.astype(np.float32)
detail = g - b
# Keep detail only where its size passes the threshold.
mask = np.abs(detail) >= threshold
out = g + amount * detail * mask
return np.clip(out, 0, 255).astype(np.uint8)
result = unsharp_threshold(gray, sigma=2.0, amount=1.0, threshold=5)The mask is a boolean array. Multiplying by it turns it into 0 and 1, so pixels with a small difference receive no boost. The hard cutoff can leave visible steps where a gradual edge crosses the threshold. If that matters, smooth the mask with a small blur before using it.
Why sharpening creates halos
Unsharp masking pushes pixels on the dark side of an edge darker and pixels on the bright side brighter. Near an edge this produces a thin dark band and a thin bright band, which are called halos or overshoot. A mild amount reads as crispness. A strong amount shows a visible outline around objects.
Clipping makes the problem worse. Where the boost pushes a pixel past 255 or below 0, the value is cut off and detail inside very bright or very dark areas is lost. If your image already has many pixels near 0 or 255, use a lower amount.
Sharpening color images
You have two practical options.
- Sharpen each channel. Apply the function to B, G and R separately. This is simple, but boosting each channel independently can shift colors slightly along edges.
- Sharpen only the brightness. Convert to a color space that separates brightness from color, sharpen that channel, and convert back. This keeps color stable.
def unsharp_color(bgr, sigma=2.0, amount=1.0):
lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
blur = cv2.GaussianBlur(l, (0, 0), sigma)
l_sharp = cv2.addWeighted(l, 1.0 + amount, blur, -amount, 0)
out = cv2.merge((l_sharp, a, b))
return cv2.cvtColor(out, cv2.COLOR_LAB2BGR)
color_sharp = unsharp_color(img, sigma=2.0, amount=1.0)For uint8 input, OpenCV scales the L channel of LAB to 0 to 255, so addWeighted on it behaves just as it does on a grayscale image.
Alternatives and gotchas
You can also sharpen with a single kernel through cv2.filter2D. A common 3x3 example is:
kernel = np.array([[ 0, -1, 0],
[-1, 5, -1],
[ 0, -1, 0]], dtype=np.float32)
sharp_kernel = cv2.filter2D(gray, -1, kernel)The kernel sums to 1, so brightness is preserved, and it boosts the 4-neighbor difference. It is fast and has no parameters, but it is fixed at one scale and has no amount control. Unsharp masking is more flexible because sigma and amount are separate.
Keep these points in mind:
- Sharpening cannot recover lost detail. It increases the contrast of edges that already exist. A badly out-of-focus image does not become sharp.
- Denoise first, lightly. Sharpening amplifies noise. If the image is noisy, use a median or bilateral filter before sharpening, or use the threshold variant above.
- Sharpen last in a display pipeline, and not before edge detection. Sharpening before Sobel or Canny raises the noise in the gradients. Those detectors work better on a smoothed image.
- Watch the dtype. Float images in the range 0 to 1 need
gamma, clipping and the final conversion handled in a matching range.
Exercise
A grayscale uint8 image is sharpened with cv2.addWeighted(gray, 2.0, blur, -1.0, 0), where blur is a Gaussian blur of gray. What amount does this correspond to in the formula original + amount * (original - blurred), and why is a pixel with original value 200 and blurred value 230 set to 170?
Show answer
The weights are 1 + amount and -amount, so 1 + amount = 2.0 and the amount is 1.0. For the pixel, 2.0 200 - 1.0 230 = 170. The original is darker than its blur, so the boost pushes it darker still. This is the dark side of an edge, and it is where dark halos come from.
Exercise
You apply unsharp masking to a noisy, mostly flat photo and the grain becomes much more visible. Name two changes that reduce this problem.
Show answer
Add a threshold so that only differences above a minimum size are boosted, and denoise lightly with a median or bilateral filter before sharpening. Lowering the amount also helps.