CS Fundamentals Trainer · Guides

Image enhancement recipes: shading, contrast, sharpening and noise

Five worked recipes with symptom, steps, parameters and failure modes: uneven illumination (divide by a Gaussian estimate), dark or low-contrast images, soft photographs (unsharp masking and its halos), noisy medical images (Laplacian masked by a smoothed gradient), and specks on a scan (median). Two runnable code samples.

9 min read

Knowing the individual operations is not the same as knowing how to fix a picture. Real problems need two or three steps in the right order, with parameters tied to what is in the image. This guide gives five recipes. Each one has the symptom, the steps, how to pick the numbers, how to check the result and what usually goes wrong. The two code samples were run and give the numbers quoted. Every parameter here is a starting point: the right values depend on the image content, the noise, the resolution and the implementation, so always look at the output.

Recipe 1: uneven illumination (shading)

Symptom. One side of the image is darker, for example a scanned page or a microscope slide lit from one side, and automatic measurements or thresholds fail because the same object has different grey values in different places.

Idea. Illumination varies slowly, objects vary quickly. A very strong lowpass keeps only the slow part, which is an estimate of the shading. Dividing the image by that estimate removes it.

Steps.

  1. Pick the spread of the Gaussian, σ, from the size of the objects, and then a kernel size that holds enough of it. They are two different numbers. In the classic example the checkerboard squares are 128 pixels wide and σ = 128 (equal to a square). The textbook used a 512 × 512 kernel, which is only about 4σ wide: it cuts the Gaussian off at about ±2σ, and that was enough to blur the squares out of a smooth shading estimate (a kernel three times the square size, 384, was too small). The safer rule is a support of ⌈6σ⌉, which is 769 pixels for σ = 128, rounded up to an odd size.
  2. Filter the image with it. The result is the shading estimate.
  3. Divide the image by the estimate, and multiply by the estimate's mean so the overall brightness does not change.
import numpy as np
from scipy import ndimage as ndi

def flat_field(img, feature_px):
    f = img.astype(float)
    est = ndi.gaussian_filter(f, sigma=feature_px, mode="reflect")
    return f / est * est.mean()

On a synthetic 50/150 checkerboard with squares of 32 pixels and a shading ramp from 0.5 to 1.0 across the image, the mean of three vertical strips, 32 pixels wide and taken over the same rows, was 57.0, 74.2 and 94.6 before and 74.3, 75.0 and 75.4 after, using feature_px=32.

Parameters. σ about the size of the largest object (not the smallest), and a kernel support of ⌈6σ⌉ when you want the full Gaussian; a shorter support such as 4σ is common in libraries (SciPy's default cuts at ±4σ, so about 8σ wide) and a very short one distorts the estimate. The separable Gaussian is essential here: a 512 × 512 kernel costs 256 times more when applied directly (30 s versus about 2 hours in the textbook's example), and a 769 × 769 one about 385 times more.

Goes wrong when. σ is too small (the estimate follows the objects and divides them out too), when the image has very large uniform objects (the estimate then sees them as shading), and at the border if you zero-pad (use mirror padding).

Recipe 2: dark or low-contrast image

Symptom. The histogram is crowded at one end or in a narrow band.

Steps.

  1. Look at the histogram first. A narrow band in the middle needs a contrast stretch; crowding at the dark end needs gamma below 1 or a log; the whole range being used but badly distributed is the job of histogram equalization.
  2. Apply the point operation. For gamma, normalise to 0 to 1, raise to the power, and scale back: with γ = 0.5 an input of 64 becomes 255 × (64/255)^0.5 ≈ 128.
  3. If different regions need different treatment, use local (adaptive) equalization with a contrast limit.

Choosing between them. Global equalization spreads the whole histogram flat and can leave bright areas washed out or "overexposed", since it also stretches the ends that were fine. Gamma keeps the shape of the histogram and only moves the dark levels, so the result looks more natural. The rule-based fuzzy approach (dark pixels darker, grey pixels grey, bright pixels brighter) keeps the shape of the histogram too, at the price of more processing.

Goes wrong when. The dark region is noisy, because the operations that stretch the dark levels (a slope above 1) make the noise there more visible; a point operation cannot tell noise from detail (see the point-versus-neighbourhood guide: denoise first). It also goes wrong if you equalize an image with large dark and large bright parts: the result can look unnatural, and gamma with a hand-chosen exponent is often better.

Recipe 3: a soft photograph

Symptom. Edges are there but lack bite, as in a slightly defocused or resized picture.

Idea. Unsharp masking: blur the image, subtract the blur to get the mask (the detail that blurring removed), and add k times the mask back.

Steps and the numbers behind them.

  1. Pick σ for the scale of the blur you are undoing. A larger σ sharpens broader features.
  2. Pick k: 1 is plain unsharp masking, above 1 is highboost, below 1 is gentler. Try 0.5 to 2.
  3. Compute f + k(f − blur) and clip to the valid range.
def unsharp(img, sigma, k):
    f = img.astype(float)
    blur = ndi.gaussian_filter(f, sigma=sigma, mode="reflect")
    return np.clip(f + k * (f - blur), 0, 255)

Check for halos. On a step from 60 to 160, σ = 2 and k = 1.5, the output around the edge reads 60, 58, 54, 45, 26, 0, 220, 194, 175, 166, 162, 160. The edge now overshoots on both sides: the dark side dips to 0 (clipped, it would have been negative) and the bright side peaks at 220. That is a visible dark and bright halo. Lower k or σ until the overshoot is small, or limit the boost where the local contrast is already high.

Goes wrong when. k is large, the image has noise (the mask contains noise, which is amplified), or the image is a JPEG with block artefacts (they are sharpened too). For noisy photographs smooth lightly first, or use a threshold so that the boost only applies where the mask is larger than the noise.

Recipe 4: a noisy medical image with faint detail

Symptom. A whole-body bone scan or an X-ray: a wide range of intensities, much of it dark, noisy, with important detail that is faint.

Idea. The Laplacian is the best at fine detail but is very sensitive to noise. The Sobel gradient is less sensitive to noise. Smooth it, and use it as a mask that keeps the Laplacian only where there are strong edges.

Steps.

  1. Compute the Laplacian of the original (note its sign convention).
  2. Compute the Sobel gradient magnitude of the original.
  3. Smooth the gradient with a 5 × 5 box filter. This is the mask.
  4. Multiply the Laplacian by the smoothed gradient, pixel by pixel. Strong edges keep their detail; flat noisy areas are quieted.
  5. Add the product to the original.
  6. The sharpened image has about the same dynamic range as the original, so finish with a power law with γ < 1 (0.5 in the example) to spread the dark levels. Histogram equalization is not a good choice for images whose histograms have separate dark and bright components.

Goes wrong when. The sign of the Laplacian is wrong (edges dim), when the gamma step is skipped (the dark detail stays invisible) and when the final gamma is pushed too far, since it also enhances noise.

Enhancement is not diagnosis. This pipeline makes a picture easier to look at. It is a technique example, not a clinical method. Sharpening, masking and a power law can hide real features, exaggerate faint ones, create halos at edges and turn noise into structures that look real. The parameters in the textbook example (a 5 × 5 box and γ = 0.5) were found by trial on one image and do not transfer. Any use on medical images must keep the original, follow the validated and approved processing of the application, and leave the interpretation to qualified readers looking at the unprocessed data as well.

Recipe 5: scanned page with specks

Symptom. Black and white dots over a scanned document or a picture, a few pixels each.

Steps.

  1. Median filter with a 3 × 3 window. It removes dots that are one or two pixels across and keeps the text edges. If the dots are bigger, use 5 × 5, but that starts to remove thin strokes.
  2. If the text looks soft after the median, apply a mild unsharp mask (σ about 1, k about 1).

Why not a Gaussian. Averaging spreads each speck into a grey blotch and also blurs the text. A median removes the speck outright because a speck is an outlier in its window; it survives only if more than half of the window is corrupted.

Goes wrong when. The window is wider than the thinnest strokes you want to keep (they are removed) or the specks cover a large share of the page.

A general routine for any new image

  1. Look at the image and its histogram. Name the problem in one sentence.
  2. As a starting point, fix the biggest, lowest-frequency problem first (shading), then noise, then tone, then detail; if your data says otherwise, follow the data.
  3. Choose sizes from the image: kernel larger than what you remove, smaller than what you keep, and scaled if the resolution changes.
  4. Choose padding (mirror unless you have a reason).
  5. Check a flat area, an edge and a dark area on the output, and compare against the input side by side.
  6. Keep the original and record the parameters. A pipeline you cannot reproduce cannot be improved.

Further reading

Practise this topic: Computer Vision

More guides