How to Import and Export Images with MATLAB

By Jim Sizemore, John Paul Mueller

You will need to know a few things before you work with images in MATLAB. Images are more complex than text files because they use binary data that isn’t easy for humans to understand, and the format of that data is intricate. Small, hard-to-diagnose errors can cause the entire image to fail. However, the process of exporting and importing images is relatively straightforward.

Exporting images

Before you can export an image, you need an image to export.

image0.jpg

Before you export the image, you must decide on the parameters for the output. The most important parameter is the output type. Because Joint Photographic Experts Group (.jpeg) files are common on most platforms, the example uses a .jpeg.

After you decide on an export format, you can use the saveas() function to perform the task. In this case, you type saveas(gcf(), ‘Bar1.jpeg’, ‘jpg’) and press Enter. MATLAB exports the figure using whatever resolution is currently set for the figure. Remember that the gcf() function obtains the handle for the current figure. Here is the plot in Windows Photo Viewer as Bar1.jpeg.

image1.jpg

Use the saveas() function to save MATLAB objects, such as plots. However, when working with actual images, use the imwrite() function instead. The imwrite() function works essentially the same way that saveas() does, but it works directly with image files.

Importing images

MATLAB can also work with images that you import from other sources. The basic method of importing an image is to use imread(). For example, to import Bar1.jpeg, you type ImportedImage = imread(‘Bar1.jpeg’); and press Enter. What you see as output is a matrix that has the same dimensions as the image.

If the image has a resolution of 900 ×1200, the matrix will also be 900 ×1200. However, a third dimension is involved — the color depth. It takes red, green, and blue values to create a color image. So the resulting matrix is actually 900 ×1200 ×3.

This is one of those situations in which the semicolon is absolutely essential at the end of the command. Otherwise, you may as well go get a cup of coffee as you wait for the numbers to scroll by. If you accidentally issue the command without the semicolon, you can always stop it by pressing Ctrl+C.

To display your image, you use the image() function. For example, to display the image you just imported, you type image(ImportedImage) and press Enter. You see the original plot, but in image form.

image2.jpg