Main Content

im2gray

Convert RGB image to grayscale

    Description

    example

    I= im2gray(RGB)converts the specified truecolor imageRGBto a grayscale intensity imageI. Theim2grayfunction accepts grayscale images as inputs and returns them unmodified.

    Theim2grayfunction converts RGB images to grayscale by eliminating the hue and saturation information while retaining the luminance.

    Examples

    collapse all

    Read a truecolor (RGB) image into the workspace from a file and display it.

    RGB = imread('example.tif'); imshow(RGB)

    Figure contains an axes object. The axes object contains an object of type image.

    Convert the RGB image into a grayscale image.

    I = im2gray(RGB);

    Display the converted grayscale image.

    imshow(I)

    Figure contains an axes object. The axes object contains an object of type image.

    Input Arguments

    collapse all

    Truecolor image, specified as anm-by-n-by-3 numeric array.im2grayalso acceptsm-by-nnumeric arrays (grayscale images) and returns them unmodified.

    If you have Parallel Computing Toolbox™ installed,RGBcan also be agpuArray.

    Data Types:single|double|uint8|uint16

    Output Arguments

    collapse all

    Grayscale image, returned as anm-by-nnumeric array. If the input toim2grayis a grayscale image, the output imageIis the same as the input image.

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

    Tips

    • Theim2grayfunction is identical torgb2grayexcept that it can accept grayscale images as inputs, returning them unmodified. Thergb2grayfunction returns an error if the input image is a grayscale image. If you use theim2grayfunction, code like this loop is no longer necessary.

      if ndims(I) == 3 I = rgb2gray(I); end
    • Unlike thergb2grayfunction, theim2grayfunction does not accept colormaps as an input. To convert a colormap to grayscale, use thecmap2grayfunction.

    Algorithms

    Theim2grayfunction converts RGB values to grayscale values by forming a weighted sum of theR,G, andBcomponents:

    0.2989 * 0.5870 R + * G + 0.1140 * B

    These are the same weights used by thergb2ntsc(Image Processing Toolbox)function to compute theYcomponent.

    The coefficients used to calculate grayscale values in theim2gray用来计算函数是相同的luminance (E'y) in Rec.ITU-R BT.601-7 after rounding to three decimal places.

    Rec.ITU-R BT.601-7 calculates E'y using the following formula:

    0.299 * R + 0.587 * G + 0.114 * B

    Extended Capabilities

    See Also

    (Image Processing Toolbox)||(Image Processing Toolbox)|(Image Processing Toolbox)||(Image Processing Toolbox)|

    Topics

    Introduced in R2020b