Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 45 ยท Real-World Projects

Project: Enhance an Image

Improve a dull synthetic image in MATLAB and Octave with histogram equalization, conv2 blur and sharpen kernels and a Sobel edge map, with NumPy stand-ins.

A grayscale image is just a matrix of brightness values, so everything you know about matrices applies to photographs. In this project you take a dull, low-contrast picture and improve it step by step: stretch its contrast with histogram equalization, smooth it with a blur, bring back detail with a sharpening filter and finally draw an edge map. Each step is a few lines of matrix code.

To keep everything self-contained the image is synthetic: a matrix built from a gradient, a bright disc, a dark square and some noise. MATLAB and Octave do not run in your browser here, so the MATLAB code is read-only. The core operations (conv2, indexing, cumsum) exist in both MATLAB and Octave; histeq, imfilter and edge come from the Image Processing Toolbox (Octave: the image package, loaded with pkg load image). Each step has a runnable NumPy and SciPy stand-in. For the basics, see Image Processing Basics.

From dull to sharp

Low contrast Brightness squeezed into a narrow band.
Equalize Spread the brightness values out.
Blur and sharpen Kernels slide over the image.
Edges Find where brightness jumps.
1 / 2

Step 1: a synthetic, low-contrast image

Create a 128-by-128 matrix of doubles between 0 and 1, then squeeze it into a narrow range so that the picture looks washed out. Indexing with ranges and meshgrid (see Ranges and Special Matrices) does the drawing:

MATLAB
[X, Y] = meshgrid(1:128, 1:128);

img = X / 128 * 0.5;                              % horizontal gradient
img(((X-45).^2 + (Y-50).^2) < 20^2) = 0.9;        % bright disc
img(80:110, 70:115) = 0.1;                        % dark square

rng(3)
img = img + 0.03*randn(size(img));
img = min(max(img, 0), 1);                        % clamp to [0, 1]

dull = 0.35 + 0.3*img;                            % squeeze into 0.35 ... 0.65
imshow(dull, [0 1])

Passing [0 1] to imshow fixes the display range. Without it, MATLAB would stretch the display range to the data and you would not see the problem. The line with min(max(...)) is the classic way to clamp values into a range.

Python Build and show the dull image

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note the index shift: MATLAB's img(80:110, 70:115) is Python's img[79:110, 69:115], because MATLAB counts from 1 and includes both ends.

Step 2: histogram equalization

A histogram counts how many pixels have each brightness. The dull image uses only a thin slice of the available range. Equalization remaps brightness so that the counts spread out evenly, using the cumulative distribution: if 30 percent of the pixels are darker than a value v, then v is mapped to 0.3.

With the toolbox, the whole job is histeq(dull). In core MATLAB and Octave you can do it with a few lines on an 8-bit version of the image:

MATLAB
g = uint8(round(dull * 255));            % 8-bit image, values 0 ... 255
counts = accumarray(double(g(:)) + 1, 1, [256 1]);   % histogram, 256 bins
cdf = cumsum(counts) / numel(g);         % fraction of pixels at or below each level
lut = uint8(round(255 * cdf));           % look-up table: old level -> new level
eq  = lut(double(g) + 1);                % indexing with a matrix applies the table

The last line is the trick worth remembering: a vector used as a look-up table, indexed by a whole matrix, remaps every pixel in one vectorized step, with no loop. The + 1 converts brightness 0-255 into 1-based indices.

Python Equalize the histogram with a look-up table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The equalized image uses the full range from black to white, so the disc and the square stand out. Equalization cannot create information, though: the number of distinct levels does not grow (it went from 62 to 52 in the stand-in run, because neighbouring levels merge), and noise is amplified along with the signal.

Step 3: blur with conv2

A kernel is a small matrix of weights. conv2(img, kernel, 'same') slides it over the image, replacing each pixel by the weighted sum of its neighbourhood, and the 'same' option returns a result as large as the input. A blur uses weights that add up to 1, so overall brightness stays the same:

MATLAB
box = ones(5) / 25;                       % 5x5 average
blurred = conv2(double(eq)/255, box, 'same');

A Gaussian kernel weighs the centre more heavily than the edges and blurs more gracefully. Build one by hand, or with fspecial('gaussian', 7, 1.5) in the toolbox:

MATLAB
k = -3:3;
g1 = exp(-k.^2 / (2*1.5^2));              % 1-D bell curve
gauss = g1' * g1;                         % outer product: 7x7 kernel
gauss = gauss / sum(gauss(:));            % weights sum to 1

Blurring suppresses noise at the price of sharpness, the same trade-off as the moving average in Project: Denoise a Signal, now in two dimensions.

Step 4: sharpen with an unsharp mask

To sharpen, subtract a blurred copy: img - blurred keeps only the fine detail (edges and texture), and adding a multiple of it back makes the details stronger. This is the unsharp mask:

MATLAB
detail  = img - blurred;
amount  = 1.5;
sharp   = min(max(img + amount*detail, 0), 1);

Larger amount gives crisper results until halos appear around edges and noise becomes distracting. The same idea fits one kernel: [0 -1 0; -1 5 -1; 0 -1 0] sharpens in a single conv2 call, because its weights add up to 1 and it subtracts the neighbours from an amplified centre.

Python Blur and sharpen with convolution

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The printed numbers measure the variation in a nearly flat patch of the picture (about 0.056 equalized, 0.034 blurred, 0.113 sharpened in the stand-in run): blurring lowers it, sharpening raises it again. That is the whole trade-off in one line: a sharper image is always a noisier image.

Step 5: an edge map

An edge is a place where brightness changes quickly, so edge detection means estimating the gradient. The Sobel kernels are two 3-by-3 matrices, one measuring the change from left to right and one from top to bottom. The edge strength is the length of the gradient vector:

MATLAB
sx = [-1 0 1; -2 0 2; -1 0 1];
sy = sx';
gx = conv2(blurred, sx, 'same');
gy = conv2(blurred, sy, 'same');
mag = sqrt(gx.^2 + gy.^2);               % edge strength
edges = mag > 0.5 * max(mag(:));         % logical mask of strong edges
imshow(edges)

Blur before you detect edges: derivatives amplify noise (see Integration, Differentiation and ODEs), and without smoothing the edge map would be speckled with noise. With the toolbox, edge(img, 'sobel') or edge(img, 'canny') does all of this, including thinning and thresholds.

Python Sobel edge map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You should see the outlines of the disc and the square. In a patch with no real edge, the mean edge strength is about 0.13 without blurring and 0.04 with it, which is why you blur first.

Putting it together

The whole pipeline is short: clamp, equalize through a look-up table, blur with a convolution, add back the detail, then detect edges. Wrap the steps in functions (see Scripts and Functions) and a new image costs one call. A natural next step is a real photograph: imread loads it as a uint8 matrix, rgb2gray makes it gray, and every step above works unchanged.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does histogram equalization do to a low-contrast image?

    It maps each brightness through the cumulative distribution, so crowded levels are spread apart and the full black-to-white range is used. It does not remove noise.
  2. 2. Why does the look-up-table line lut(double(g) + 1) add 1?

    A pixel of brightness 0 must pick the first table entry, so the value is shifted by 1 to become a valid 1-based index.
  3. 3. What is true of a blur kernel whose weights sum to 1?

    Weights summing to 1 form a weighted average, so flat areas keep their value and only changes between neighbours are smoothed.
  4. 4. How does an unsharp mask sharpen?

    Subtracting the blurred copy leaves the fine detail. Adding that detail back, scaled, makes edges and texture stronger.
  5. 5. Why blur before computing Sobel edges?

    A derivative responds to every small random change. Smoothing first suppresses noise so that only real brightness steps stand out.

Summary

  • A grayscale image is a matrix; indexing, masks and min(max(...)) clamping edit it directly.
  • Equalization builds a histogram with accumarray, takes cumsum, and applies the result as a look-up table by indexing with the whole image.
  • conv2(img, kernel, 'same') applies any kernel; blur kernels sum to 1, and an unsharp mask adds back img - blurred.
  • Sobel kernels give horizontal and vertical gradients; combine with sqrt(gx.^2 + gy.^2), blur first, and threshold into a logical mask.
  • histeq, imfilter, fspecial and edge are toolbox shortcuts; the NumPy and SciPy stand-ins reproduce the same matrix steps.

Next, try random simulation in Project: Monte Carlo Estimates.