TExcelTAD
Home › MATLAB / Octave › Image Processing Basics

Image Processing Basics

To MATLAB, a picture is just a matrix. Each element is a pixel, and its value is a brightness. That simple idea means everything you already know about arrays (indexing, logical masks, element-wise maths, sums) works on images too. This lesson builds small images in code, so every example runs anywhere, and then shows the Image Processing Toolbox functions you would use on real photos.

Image kind Array shape Typical class Value range
Grayscale rows x cols uint8 0 (black) to 255 (white)
Grayscale rows x cols double 0.0 to 1.0
Truecolor (RGB) rows x cols x 3 uint8 or double one page each for red, green, blue
Binary (mask) rows x cols logical false / true

The first index is the row (counting down from the top), the second is the column (counting right). So img(1, end) is the top-right pixel, which is the opposite of the usual (x, y) order in maths.

Building an image in code

meshgrid gives every pixel its column number X and row number Y. With those, a gradient is a formula, and a shape is a logical condition:

matlab · try it yourself
[X, Y] = meshgrid(1:24, 1:12);
img = 40 + 5 * X;                                   % background: dark-to-light gradient
disk = (X - 7).^2 / 25 + (Y - 6.5).^2 / 16 <= 1;    % logical mask of a disk
img(disk) = 250;                                    % paint it almost white
img(3:10, 15:21) = 10;                              % a dark rectangle
img = uint8(img);

pic = repmat('.', size(img));     % a text "rendering" of the image
pic(img > 200) = '#';
pic(img < 30)  = 'o';
disp(pic)
fprintf('%dx%d %s image, values %d..%d\n', size(img), class(img), min(img(:)), max(img(:)));
........................
........................
....#####.....ooooooo...
...#######....ooooooo...
..#########...ooooooo...
..#########...ooooooo...
..#########...ooooooo...
..#########...ooooooo...
...#######....ooooooo...
....#####.....ooooooo...
........................
........................
12x24 uint8 image, values 10..250

To look at the real thing, display it with a gray colormap (see Images & Colormaps):

matlab
imagesc(img); colormap(gray); axis image off   % or imshow(img) for uint8 data

Cropping, flipping and rotating are plain array operations: img(3:10, 15:21) crops, fliplr(img) mirrors left-right, flipud(img) upside down, rot90(img) rotates by 90 degrees, and img(1:2:end, 1:2:end) halves the resolution by keeping every second row and column.

uint8 arithmetic saturates

Photos are usually stored as uint8 to save memory (one byte per pixel). Integer arithmetic in MATLAB saturates: results are rounded and clipped to the range of the type instead of wrapping around. That is handy for brightening, but it also silently loses information, so convert to double for any serious calculation:

matlab · try it yourself
a = uint8(200) + 100       % clipped at 255
b = uint8(10) - 50         % clipped at 0
c = uint8(7) / 2           % rounded: 3.5 -> 4
img = uint8([0 64 128 255]);
d = double(img) / 255      % what im2double(img) returns
a = 255
b = 0
c = 4
d =

        0   0.2510   0.5020   1.0000

im2double converts any image to double in [0, 1], whatever its original class. It is part of core MATLAB and of Octave; im2uint8 goes the other way (Image Processing Toolbox in MATLAB, image package in Octave), or use uint8(255 * d).

Color images and grayscale

A truecolor image has three pages: rgb(:, :, 1) is red, (:, :, 2) green and (:, :, 3) blue. Converting to grayscale is a weighted sum, because the eye is far more sensitive to green than to blue. rgb2gray uses exactly these weights (it is in core MATLAB since R2014b and in core Octave):

matlab · try it yourself
rgb = zeros(2, 2, 3);
rgb(1, 1, :) = [1 0 0];        % red
rgb(1, 2, :) = [0 1 0];        % green
rgb(2, 1, :) = [0 0 1];        % blue
rgb(2, 2, :) = [1 1 1];        % white
disp(size(rgb))
gray = 0.2989 * rgb(:, :, 1) + 0.5870 * rgb(:, :, 2) + 0.1140 * rgb(:, :, 3)
g2 = rgb2gray(rgb);
fprintf('largest difference from rgb2gray: %.4f\n', max(abs(g2(:) - gray(:))));
   2   2   3
gray =

   0.2989   0.5870
   0.1140   0.9999

largest difference from rgb2gray: 0.0001

Pure green comes out almost twice as bright as pure red, and pure blue is nearly black. (The tiny difference is because rgb2gray uses more digits for the weights.)

Thresholding

Thresholding turns a grayscale image into a binary mask: bw = img > t. The hard part is choosing t. A classic automatic method (the "isodata" or iterative mean method) starts with a guess, splits the pixels into dark and bright groups, moves t to the midpoint of the two group means, and repeats until it stops moving:

matlab · try it yourself
[X, Y] = meshgrid(1:24, 1:12);
img = 40 + 5 * X;
img((X - 7).^2 / 25 + (Y - 6.5).^2 / 16 <= 1) = 250;
img(3:10, 15:21) = 10;

t = 128;
for it = 1:20
    tNew = (mean(img(img <= t)) + mean(img(img > t))) / 2;
    fprintf('iteration %d: t = %.2f\n', it, tNew);
    if abs(tNew - t) < 0.5, break; end
    t = tNew;
end
bw = img > t;
fprintf('%d of %d pixels are foreground\n', nnz(bw), numel(bw));
iteration 1: t = 131.58
iteration 2: t = 133.72
iteration 3: t = 133.72
108 of 288 pixels are foreground

The Image Processing Toolbox does this job with graythresh (Otsu's method, which maximises the separation between the two groups) and imbinarize. In Octave, graythresh and im2bw come with the image package.

Filtering with convolution kernels

Many filters replace each pixel with a weighted sum of its neighbours. The weights form a small matrix called a kernel, and sliding it over the image is a 2-D convolution, conv2 in core MATLAB and Octave. The option 'same' keeps the output the size of the input (pixels outside the border count as 0).

A 3x3 kernel of ninths is a box blur: every pixel becomes the average of its 3x3 neighbourhood.

matlab · try it yourself
img = zeros(7);
img(3:5, 3:5) = 90;            % a bright square on black
soft = conv2(img, ones(3) / 9, 'same')
soft =

    0    0    0    0    0    0    0
    0   10   20   30   20   10    0
    0   20   40   60   40   20    0
    0   30   60   90   60   30    0
    0   20   40   60   40   20    0
    0   10   20   30   20   10    0
    0    0    0    0    0    0    0

A Gaussian kernel blurs more naturally, weighting near neighbours more than far ones. Normalise it so the weights sum to 1, otherwise the image gets brighter or darker:

matlab · try it yourself
[x, y] = meshgrid(-2:2);
g = exp(-(x.^2 + y.^2) / 2);    % sigma = 1
g = g / sum(g(:));
disp(round(1000 * g))           % weights in thousandths
fprintf('kernel sums to %.4f\n', sum(g(:)));
     3    13    22    13     3
    13    60    98    60    13
    22    98   162    98    22
    13    60    98    60    13
     3    13    22    13     3
kernel sums to 1.0000

Edge detection

Edges are where brightness changes quickly. A difference kernel measures that change. The Sobel kernels estimate the horizontal and vertical gradients, and their combined magnitude is large on the outline of an object:

matlab · try it yourself
img = zeros(7);
img(3:5, 3:5) = 90;
sx = [1 0 -1; 2 0 -2; 1 0 -1];     % horizontal change
gx = conv2(img, sx, 'same');
gy = conv2(img, sx', 'same');      % the transpose detects vertical change
mag = round(sqrt(gx.^2 + gy.^2));
edges = mag >= 0.5 * max(mag(:))
edges =

  0  0  0  0  0  0  0
  0  0  1  1  1  0  0
  0  1  1  1  1  1  0
  0  1  1  0  1  1  0
  0  1  1  1  1  1  0
  0  0  1  1  1  0  0
  0  0  0  0  0  0  0

The flat centre of the square has zero gradient, so only its outline survives.

Note: Convolution flips the kernel before sliding it; correlation (filter2 in core MATLAB/Octave, and imfilter's default) does not. For symmetric kernels like the blur they agree. For a difference kernel the sign changes:

matlab · try it yourself
x = [0 0 0 9 9 9; 0 0 0 9 9 9];    % dark-to-bright step
k = [1 0 -1];
c = conv2(x, k, 'same')
f = filter2(k, x)
c =

   0   0   9   9   0  -9
   0   0   9   9   0  -9

f =

   0   0  -9  -9   0   9
   0   0  -9  -9   0   9

Both find the step in columns 3-4. The value in the last column is an artefact of the zero padding at the border; toolbox functions offer other border rules (such as 'replicate') to avoid it.

Histograms of pixel values

An image histogram counts how many pixels have each brightness. It tells you at a glance whether a photo is too dark (counts piled up on the left), washed out (on the right) or low-contrast (a narrow hump). accumarray builds it from bin numbers; here 4 bins of width 64:

matlab · try it yourself
[X, Y] = meshgrid(1:24, 1:12);
img = 40 + 5 * X;
img((X - 7).^2 / 25 + (Y - 6.5).^2 / 16 <= 1) = 250;
img(3:10, 15:21) = 10;
img = uint8(img);

bin = floor(double(img(:)) / 64) + 1;         % 0-63 -> 1, 64-127 -> 2, ...
counts = accumarray(bin, 1, [4 1])';
fprintf('%3d-%3d: %3d pixels\n', [0:64:192; 63:64:255; counts]);

% contrast stretch: map the darkest pixel to 0 and the brightest to 255
d = double(img);
stretched = uint8(255 * (d - min(d(:))) / (max(d(:)) - min(d(:))));
fprintf('after stretching: %d..%d\n', min(stretched(:)), max(stretched(:)));
  0- 63:  94 pixels
 64-127:  82 pixels
128-191:  52 pixels
192-255:  60 pixels
after stretching: 0..255

To draw it, use bar(counts), or imhist(img) with the toolbox (256 bins by default):

matlab
bar(counts); set(gca, 'XTickLabel', {'0-63', '64-127', '128-191', '192-255'})
xlabel('Pixel value'); ylabel('Pixels')

The Image Processing Toolbox

For real photos you read a file, process it with ready-made functions and display the result. These need the Image Processing Toolbox in MATLAB, or the free image package in Octave (pkg install -forge image once, then pkg load image in each session). imread, imwrite and imshow are core in both.

matlab
img  = imread('street.jpg');          % uint8, rows x cols x 3
gray = rgb2gray(img);
gray = imresize(gray, 0.5);           % half size
h    = fspecial('gaussian', 7, 1.5);  % 7x7 Gaussian kernel
soft = imfilter(gray, h, 'replicate');
bw   = edge(soft, 'canny');           % logical edge map
imshow(bw)
imwrite(bw, 'street_edges.png')
Task Toolbox function Core equivalent used above
Read / write / show imread, imwrite, imshow (core)
Blur, sharpen imfilter, fspecial, imgaussfilt conv2, filter2
Edges edge (Sobel, Canny, ...) Sobel kernels + conv2
Threshold graythresh, imbinarize iterative mean method
Histogram imhist, histeq accumarray, hist
Resize, rotate imresize, imrotate indexing, rot90
Shapes in masks bwlabel, regionprops, imdilate, imerode (loops or conv2 on masks)

Understanding the matrix versions makes the toolbox functions much less magical: imfilter is a correlation with smart border handling, and edge is gradients plus thresholding plus some clean-up.

Learn more: Images & Colormaps, Logical Arrays & find, Fourier Transform & Signals for filtering in the frequency domain, and Toolboxes.

Test yourself

What is uint8(250) + 10?

  1. 260
  2. 4 (it wraps around)
  3. 255
  4. An error

What does conv2(img, ones(3) / 9, 'same') do to an image?

  1. Detects edges
  2. Replaces each pixel by the average of its 3x3 neighbourhood (a blur)
  3. Makes the image 9 times darker
  4. Crops it to 3x3

For a truecolor image rgb, what is rgb(:, :, 2)?

  1. The second row
  2. The green channel
  3. The second pixel
  4. The grayscale version