Convert Image Graphic or Data Type

Converting between data types changes the interpretation of the image data. If you want the resulting array to be interpreted properly as image data, rescale or offset the data when you convert it. (See the earlier sections Image Types and Indexed Images for more information about offsets.)

For certain operations, it is helpful to convert an image to a different image type. For example, to filter a color image that is stored as an indexed image, first convert it to RGB format. To do this efficiently, use the ind2rgb function. When you apply the filter to the RGB image, the intensity values in the image are filtered, as is appropriate. If you attempt to filter the indexed image, the filter is applied to the indices in the indexed image matrix, and the results may not be meaningful.

You can also perform certain conversions just using MATLAB® syntax. For example, to convert a grayscale image to RGB, concatenate three copies of the original matrix along the third dimension:

RGB = cat(3,I,I,I);

The resulting RGB image has identical matrices for the red, green, and blue planes, so the image appears as shades of gray.

Changing the graphics format of an image, perhaps for compatibility with another software product, is very straightforward. For example, to convert an image from a BMP to a PNG, load the BMP using imread, set the data type to uint8, uint16, or double, and then save the image using imwrite, with 'PNG' specified as your target format. See imread and imwrite for the specifics of which bit depths are supported for the different graphics formats, and for how to specify the format type when writing an image to file.

Was this topic helpful?