rgb2gray

Convert RGB image or colormap to grayscale

Syntax

Description

example

I = rgb2gray(RGB) converts the truecolor image RGB to the grayscale intensity image I. The rgb2gray function converts RGB images to grayscale by eliminating the hue and saturation information while retaining the luminance. If you have Parallel Computing Toolbox™ installed, rgb2gray can perform this conversion on a GPU.

example

newmap = rgb2gray(map) returns a grayscale colormap equivalent to map.

Examples

expand all

Convert RGB Image to Grayscale Image

Read and display an RGB image, and then convert it to grayscale.

Read the sample file, peppers.png, and display the RGB image.

RGB = imread('peppers.png');
imshow(RGB)

Convert the RGB image to a grayscale image and display it.

I = rgb2gray(RGB);
figure
imshow(I)

Convert RGB Colormap to Grayscale Colormap

Read an indexed image with an RGB colormap. Then, covert the colormap to grayscale.

Read the sample file, corn.tif, which is an indexed image with an RGB colormap.

[X,map] = imread('corn.tif');

Display the image.

imshow(X,map)

Convert the RGB colormap to a grayscale colormap and redisplay the image.

newmap = rgb2gray(map);
imshow(X,newmap)

Input Arguments

expand all

RGB — Truecolor image3-D numeric array

Truecolor image, specified as 3-D numeric array.

If you have Parallel Computing Toolbox installed, RGB can also be a gpuArray.

Data Types: single | double | uint8 | uint16

map — Colormapm-by-3 numeric array

Colormap, specified as an m-by-3 numeric array.

If you have Parallel Computing Toolbox installed, map can also be a gpuArray.

Data Types: double

Output Arguments

expand all

I — grayscale imagenumeric array

Grayscale image, returned as a numeric array.

If you have Parallel Computing Toolbox installed, then I can also be a gpuArray.

newmap — grayscale color mapm-by-3 numeric array

Grayscale colormap, returned as an m-by-3 numeric array.

If you have Parallel Computing Toolbox installed, then newmap can also be a gpuArray.

More About

expand all

Tips

  • rgb2gray supports the generation of C code using MATLAB® Coder™.

Algorithms

rgb2gray converts RGB values to grayscale values by forming a weighted sum of the R, G, and B components:

0.2989 * R + 0.5870 * G + 0.1140 * B 

These are the same weights used by the rgb2ntsc function to compute the Y component.

Was this topic helpful?