TExcelTAD
Home › MATLAB / Octave › Images & Colormaps

Images & Colormaps

To MATLAB, an image is just a matrix whose elements are drawn as coloured squares (pixels). That works in both directions: photos load as ordinary arrays you can compute with, and any matrix of numbers, such as a temperature grid, a correlation matrix or a game board, can be displayed as an image. The link between numbers and colours is the colormap.

Three kinds of image data

Kind Array Values How colour is chosen
Intensity / scaled m-by-n Any numbers Scaled to the colormap range (imagesc)
Indexed m-by-n Integers 1…k Each value is a row number in a k-by-3 colormap (image)
Truecolor (RGB) m-by-n-by-3 double 0–1 or uint8 0–255 Red, green and blue given directly per pixel

The display functions:

Function What it does
imagesc(C) Scales the data so the smallest value gets the first colormap colour and the largest the last
image(C) Uses values as direct colormap indices (or as RGB if C is m-by-n-by-3)
imshow(I) Shows an image with square pixels, no axes ticks (Image Processing Toolbox in MATLAB; built into Octave)
colorbar Shows the colour scale beside the axes
axis image Square pixels and limits that fit the image exactly

Row 1 of the matrix is drawn at the top, like a picture (the y-axis points down). That's the opposite of plot; use axis xy to flip it when the rows represent increasing y.

Displaying a matrix with imagesc

matlab
[X, Y] = meshgrid(1:6, 1:4);
M = X .* Y;                      % a small multiplication table
imagesc(M)
colorbar
axis image
title('imagesc of a 4-by-6 matrix')

How does imagesc decide the colour of each cell? With a colormap of m colours and colour limits [cmin cmax] (by default the minimum and maximum of the data), a value v gets row fix((v - cmin) / (cmax - cmin) * m) + 1 of the colormap, clipped to the range 1…m. Computing it by hand for an 8-colour map shows which cells share a colour:

matlab · try it yourself
[X, Y] = meshgrid(1:6, 1:4);
M = X .* Y
m = 8;
cmin = min(M(:));  cmax = max(M(:));
idx = fix((M - cmin) / (cmax - cmin) * m) + 1;
idx = min(max(idx, 1), m)        % colormap row used for each cell
M =

    1    2    3    4    5    6
    2    4    6    8   10   12
    3    6    9   12   15   18
    4    8   12   16   20   24

idx =

   1   1   1   2   2   2
   1   2   2   3   4   4
   1   2   3   4   5   6
   2   3   4   6   7   8

clim([cmin cmax]) (MATLAB R2022a and later, and Octave 11) or the older caxis([cmin cmax]) (both programs) sets the colour limits yourself. That matters when you compare several images: give them all the same limits, or the same colour will mean different values in each one. Values outside the limits get the end colours.

Colormaps

A colormap is an ordinary m-by-3 matrix of RGB values between 0 and 1, one row per colour. Built-in functions create the common ones, and take the number of colours as input:

Colormap Character
parula MATLAB's default since R2014b; perceptually ordered blue → yellow. Octave 11 doesn't have it
viridis Octave's default; similar purpose and look. MATLAB doesn't ship it
turbo A smoother rainbow (MATLAB R2020b+, Octave)
jet The old rainbow default; vivid but can create false boundaries
hot, gray, bone, copper Black → colour → white ramps
cool, spring, hsv, lines Others; hsv wraps around, good for angles
matlab · try it yourself
g = gray(5)                      % 5 shades from black to white
j = jet(4)                       % 4 colours of the jet rainbow
g =

        0        0        0
   0.2500   0.2500   0.2500
   0.5000   0.5000   0.5000
   0.7500   0.7500   0.7500
   1.0000   1.0000   1.0000

j =

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

Because a colormap is just a matrix, you can make your own. colormap(M) installs it for the current figure (or colormap(ax, M) for one axes):

matlab · try it yourself
k = 4;
white_to_red = [ones(k, 1), linspace(1, 0.1, k)', linspace(1, 0.1, k)']
fprintf('%d colours, first [%g %g %g], last [%g %g %g]\n', ...
        size(white_to_red, 1), white_to_red(1, :), white_to_red(end, :));
% colormap(white_to_red)
white_to_red =

   1.0000   1.0000   1.0000
   1.0000   0.7000   0.7000
   1.0000   0.4000   0.4000
   1.0000   0.1000   0.1000

4 colours, first [1 1 1], last [1 0.1 0.1]

Pick colormaps by what the data means. Sequential data (from low to high, like temperature) suits a one-directional map such as parula, viridis or hot. Diverging data (deviations from zero, correlations) needs a map that is neutral in the middle, like the white-to-red example extended with a blue half, plus symmetric limits such as clim([-1 1]). Avoid jet for quantitative work: its bright yellow and cyan bands make some values look more important than others.

Truecolor (RGB) images

A truecolor image stores the three colour channels as "pages" of a 3-D array: rgb(:,:,1) is red, rgb(:,:,2) green and rgb(:,:,3) blue. Here red grows from left to right, blue fades from top to bottom, and a white square sits in the middle:

matlab
rgb = zeros(100, 160, 3);
rgb(:, :, 1) = repmat(linspace(0, 1, 160), 100, 1);    % red: left to right
rgb(:, :, 3) = repmat(linspace(1, 0, 100)', 1, 160);   % blue: top to bottom
rgb(40:60, 70:90, :) = 1;                               % white square
image(rgb)
axis image

The colormap is ignored for RGB data. What matters is the class: double images use 0 to 1, uint8 images 0 to 255. Mixing them up is the most common image bug: double(photo) without dividing by 255 gives values far above 1, and the image shows as almost pure white. Convert explicitly:

matlab · try it yourself
rgb = zeros(100, 160, 3);
rgb(:, :, 1) = repmat(linspace(0, 1, 160), 100, 1);
rgb(:, :, 3) = repmat(linspace(1, 0, 100)', 1, 160);
rgb(40:60, 70:90, :) = 1;
fprintf('size %s, class %s\n', mat2str(size(rgb)), class(rgb));
img8 = uint8(round(255 * rgb));                 % double 0-1 -> uint8 0-255
fprintf('pixel (50,80) as uint8: %s\n', mat2str(squeeze(img8(50, 80, :))'));
fprintf('top-left pixel as uint8: %s\n', mat2str(squeeze(img8(1, 1, :))'));
gray_img = 0.2989 * rgb(:,:,1) + 0.5870 * rgb(:,:,2) + 0.1140 * rgb(:,:,3);
fprintf('grey version: %s, values %.3f to %.3f\n', mat2str(size(gray_img)), min(gray_img(:)), max(gray_img(:)));
size [100 160 3], class double
pixel (50,80) as uint8: [255 255 255]
top-left pixel as uint8: [0 0 255]
grey version: [100 160], values 0.000 to 1.000

The weights 0.2989, 0.5870 and 0.1140 are the ones rgb2gray uses: the eye is most sensitive to green, so green counts most.

Reading and writing image files

imwrite(A, filename) saves an array as PNG, JPEG, TIFF, GIF or BMP (chosen by the extension) and imread(filename) loads it back. This example writes a small image, then inspects the file:

matlab · try it yourself
A = uint8([0 64 128 255; 255 128 64 0; 0 0 255 255]);   % a 3-by-4 greyscale image
imwrite(A, 'tiny.png');
B = imread('tiny.png');
fprintf('read back: %s %s, identical: %d\n', mat2str(size(B)), class(B), isequal(A, B));
info = imfinfo('tiny.png');
fprintf('%d x %d pixels, %d bits per pixel\n', info.Width, info.Height, info.BitDepth);
read back: [3 4] uint8, identical: 1
4 x 3 pixels, 8 bits per pixel

PNG is lossless, so the data comes back exactly; JPEG is lossy and changes pixel values slightly. Convert to uint8 before writing: given a double RGB array, MATLAB writes an 8-bit PNG but Octave writes a 16-bit one, which then reads back as uint16. With uint8 input, both write and read the same 8-bit file. For an indexed image, pass the colormap too: imwrite(idx, map, 'out.png'). ind2rgb(idx, map) converts an indexed image to truecolor.

Filtering, edge detection and other operations on photos are covered in Image Processing Basics.

Summary

  • imagesc scales data into the colormap; image uses values as indices (or RGB); axis image gives square pixels; row 1 is at the top.
  • Colour limits (clim/caxis) control the scaling; share them when comparing images.
  • A colormap is an m-by-3 matrix: use built-ins like parula, viridis, gray, or build your own.
  • Truecolor images are m-by-n-by-3: double in 0–1 or uint8 in 0–255. Convert explicitly before imwrite.

Next: Saving & Exporting Figures. Learn more: Matplotlib heatmaps and colours.

Test yourself

What is the difference between imagesc(C) and image(C) for a matrix C?

  1. imagesc is faster
  2. imagesc scales the data to the whole colormap; image uses the values directly as colormap indices
  3. image only works on uint8 data
  4. There is no difference

What is size(rgb) for a truecolor image 480 pixels high and 640 wide?

  1. [640 480]
  2. [480 640]
  3. [480 640 3]
  4. [3 480 640]

After D = double(photo) (photo is uint8), image(D) shows almost pure white. Why?

  1. uint8 images can't be displayed
  2. Double images use 0–1, so values like 120 or 200 are all above 1 and clip to white
  3. The colormap is wrong
  4. uint8 stores only black and white