Skip to main content

Section 26.1 Working with images in Matlab

An image is loaded into Matlab with a command like im = imread('filename.jpg'). Try this using, for example, the winter scene (first save the file in Matlab/Octave current directory). There are several things to learn about this im object:

  • size(im) shows its size (dimensions) as 462×692×3. This is a three-dimensional array, where the last index means the color channel: Red, Green, Blue. The first two indices are rows and columns. One can access individual channels with im(:, :, 1) (for red). Matlab can also work with grayscale images which have just one channel for brightness; such images are represented by matrices which makes them easier to work with.
  • class(im) says “uint8”. All other Matlab objects we encountered so far have class double meaning they contain floating-point numbers with double-precision, able to store about 16 decimal digits. But uint8 is different: it is an unsigned 8-bit integer, with possible values 0, 1, …, 255. This reflects the image format: in each channel, the brightness of each pixel ranges from 0 to 255. (How many possible colors does this create?) Since 8 bits form a byte, the data in our image requires \(462 \times 692 \times 3 = 959112\) bytes for storage. But the JPEG file with this image is much smaller, due to built-in compression which will be described later.

The command imshow(im) displays the image. An image (an array of numbers) can be transformed in multiple ways and then either saved as a file with imwrite or just displayed with imshow; we will do the latter, which is simpler. Try the following and observe the effects:

  • Remove one of colors entirely, for example im(:, :, 3) = 0;
  • Set all pixels darker than some level to black (0) with im(im < 128) = 0;
  • Set the intensity of some color to some specific value, for example im(:, :, 2) = 64;

If you do something that causes the array to lose its class “uint8”, that can usually be fixed with the command uint8(...).