Kahibaro
Discord Login Register

Reading, Displaying, and Writing Images

Working with Image Files in MATLAB

In this chapter you work with actual image files in MATLAB. You learn how to read images from disk into MATLAB variables, display them on the screen, inspect some basic properties, and write modified images back to files.

You do not need image processing theory here. The focus is simply on moving image data between files, MATLAB variables, and figures.

Reading Images from Files

To read an image file into MATLAB you typically use the function imread. This function reads many common formats such as PNG, JPEG, TIFF, BMP, and GIF.

The basic form is

matlab
img = imread('peppers.png');

Here img becomes an array that contains the image data. For a typical color image, img is a 3D array of size height × width × 3. For a grayscale image, img is usually a 2D array of size height × width.

You can check the size of the image array using

matlab
size(img)

If the image file is not in your current folder, you must provide a relative or absolute path, for example

matlab
img = imread('images/photo.jpg');        % relative path
img = imread('C:\data\experiment1.png'); % Windows absolute path
img = imread('/home/user/pic.tif');      % Linux or macOS absolute path

If the filename contains spaces, keep it inside the quotes as usual, such as 'my picture.png'.

Some image formats can store more than one image inside a single file, for example multi-page TIFF files. In that case you can read a specific image by an index:

matlab
img1 = imread('stack.tif', 1);
img2 = imread('stack.tif', 2);

This additional argument selects which image to load from the file.

Understanding Basic Image Data Types

When you use imread, MATLAB chooses the array class based on the file contents. Common cases are:

matlab
img = imread('peppers.png');
class(img)

The output might be 'uint8', 'uint16', or 'logical'. For color images, a 'uint8' image uses integers between 0 and 255 for each color channel. For grayscale 'uint16' images, values can go up to 65535.

Sometimes you want to convert the image to floating point for processing. A common convention in many image functions is to represent pixel values as double in the range from 0 to 1. You can convert with

matlab
imgDouble = im2double(img);

and convert back if needed with functions such as im2uint8 or im2uint16. These conversion functions preserve the dynamic range correctly, unlike a direct cast with double(img) which only changes the type but not the scale.

For simple viewing and saving, you often do not need to convert types at all, but it is useful to know what you are working with.

Displaying Images

To display images in a figure window you use either imshow or image combined with colormaps, but for simple usage imshow is the most convenient.

The simplest form is

matlab
img = imread('peppers.png');
imshow(img);

This opens a figure window and shows the image with the correct aspect ratio and color interpretation. If you call imshow again it replaces the image in the current axes, so you still use plotting concepts from earlier chapters.

By default, imshow scales the display based on the image class. For uint8, the value 0 appears as black and 255 as white or full color. For images in double with values between 0 and 1, 0 appears as black and 1 as white or full color.

If you have a grayscale image stored as a 2D array, you can still use imshow in the same way:

matlab
grayImg = imread('cameraman.tif');
imshow(grayImg);

If you need to display an image in an existing figure with subplots or other plots, combine imshow with subplot:

matlab
img1 = imread('cameraman.tif');
img2 = imread('peppers.png');
subplot(1, 2, 1);
imshow(img1);
title('Grayscale image');
subplot(1, 2, 2);
imshow(img2);
title('Color image');

This allows you to compare images side by side.

Sometimes you want to visualize the intensity range of an image stored as double with arbitrary limits, not just [0, 1]. In that case you can ask imshow to scale based on the minimum and maximum values:

matlab
imshow(imgDouble, []);

The empty brackets tell imshow to map the smallest value in imgDouble to black and the largest to white.

Basic Image Inspection

Before processing or saving an image it is often helpful to inspect a few properties in the command window. You already saw size and class. Another common function is whos:

matlab
im = imread('peppers.png');
whos im

This displays the variable name, size, bytes, and class.

You can also check whether an image is grayscale or color from its dimensions:

If ndims(im) == 2, the image is usually grayscale.

If ndims(im) == 3 and the third dimension has size 3, that is size(im, 3) == 3, the image is usually RGB color.

You can access individual color channels using indexing. For example, to extract the red channel from an RGB image:

matlab
redChannel = im(:, :, 1);
imshow(redChannel);

You see that this uses ordinary MATLAB array indexing, and you only use the third dimension to select the channel.

Writing Images to Files

To save an image array from MATLAB to a file you use imwrite. The basic form is

matlab
imwrite(img, 'output.png');

This writes the variable img to a new file named output.png in the current folder. The file format is chosen from the extension in the filename. You can save the same image to different formats by changing the extension:

matlab
imwrite(img, 'output.jpg');  % JPEG
imwrite(img, 'output.tif');  % TIFF
imwrite(img, 'output.bmp');  % BMP

If the file already exists, imwrite overwrites it without asking, so be careful with filenames.

For grayscale images stored as 2D arrays, imwrite uses the pixel values and the class to decide how to encode them. For example, a uint8 grayscale image uses values 0 to 255. For double images, you should keep values in the range from 0 to 1 before writing. Values outside this range are usually clipped.

Here is an example of a simple workflow that reads an image, converts it to grayscale, and saves it. The conversion step uses a common function from the Image Processing Toolbox, but the key point here is how imread and imwrite are used:

matlab
rgb = imread('peppers.png');         % read color image
gray = rgb2gray(rgb);                % convert to grayscale (toolbox function)
imwrite(gray, 'peppers_gray.png');   % write grayscale image

By changing the filename in imwrite you can keep multiple versions of the same image.

Controlling Output Quality and Options

Some image formats support additional options such as compression level, quality, or color depth. imwrite allows you to specify these options as name value pairs after the filename.

For example, for JPEG images you can set the quality between 0 and 100:

matlab
imwrite(img, 'low_quality.jpg', 'Quality', 30);
imwrite(img, 'high_quality.jpg', 'Quality', 95);

Lower quality creates smaller files but more visible compression artifacts. Higher quality preserves more detail and uses larger files.

For PNG images you can control the compression level:

matlab
imwrite(img, 'compressed.png', 'BitDepth', 8);

The exact options depend on the file format. You can see supported parameters in the documentation by typing

matlab
doc imwrite

and checking the section for your chosen format.

Using the Current Folder with Images

Since image files are regular files on disk, the current folder that you use throughout MATLAB also matters here. If imread or imwrite cannot find or create a file, check:

The current folder in the Current Folder browser.

The path you passed to imread or imwrite.

You can use pwd to see the current folder and cd to change it:

matlab
pwd
cd('C:\myimages');
img = imread('photo.png');

Alternatively you can avoid changing the current folder by always using full or relative paths when reading and writing images.

Simple Read Display Write Workflow

Putting all the pieces together, a minimal image workflow in MATLAB looks like this:

matlab
% 1. Read an image from a file
img = imread('peppers.png');
% 2. Display it
imshow(img);
title('Original image');
% 3. Do some simple operation (example: darken the image)
imgDark = im2uint8(0.5 * im2double(img));
% 4. Display the result
figure;
imshow(imgDark);
title('Darker image');
% 5. Save the result to a new file
imwrite(imgDark, 'peppers_darker.png');

This script reads an image, displays it, modifies the pixel values with ordinary MATLAB arithmetic on arrays, displays the modified image, and writes the modified image to a new file. More advanced processing steps fit into the same pattern, but the fundamental way to read, display, and write images remains the same.

Important things to remember:
Use imread to load images from files into MATLAB variables.
Use imshow to display images, and combine it with subplot or figure if needed.
Check image size and class with size, ndims, and class to understand the data you are working with.
Use imwrite to save image arrays, and control the output format through the file extension and optional name value pairs.
Be careful with the current folder and file paths so imread and imwrite can find and create the correct files.

Views: 3

Comments

Please login to add a comment.

Don't have an account? Register now!