im2gray - Convert RGB image to grayscale - MATLAB (original) (raw)

Main Content

Convert RGB image to grayscale

Since R2020b

Syntax

Description

[I](#mw%5F38e7de21-4196-4eeb-b3c3-6aae03b9cb2f) = im2gray([RGB](#mw%5F740e9357-1a33-45fb-a068-e8f7ff38fd3d)) converts the specified truecolor image RGB to a grayscale intensity imageI. The im2gray function accepts grayscale images as inputs and returns them unmodified.

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

example

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 hidden axes object contains an object of type image.

Convert the RGB image into a grayscale image.

Display the converted grayscale image.

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

Input Arguments

collapse all

Truecolor image, specified as an _m_-by-_n_-by-3 numeric array. im2gray also accepts_m_-by-n numeric arrays (grayscale images) and returns them unmodified.

The im2gray function expects truecolor images of data typedouble and single to have values in the range [0, 1]. If an image has values outside the range [0, 1], then you can rescale values to the expected range by using the rescale function.

If you have Parallel Computing Toolbox™ installed, RGB can also be agpuArray object.

Data Types: single | double | uint8 | uint16

Output Arguments

collapse all

Grayscale image, returned as an _m_-by-n numeric array. If the input to im2gray is a grayscale image, the output image I is the same as the input image.

If you have Parallel Computing Toolbox installed, then I can also be agpuArray object.

Tips

Algorithms

The im2gray function converts RGB values to grayscale values by forming a weighted sum of the R, G, and_B_ components:

0.298936021293775 * R + 0.587043074451121 * G + 0.114020904255103 * B

The coefficients used to calculate grayscale values in the im2gray function are identical to those used to calculate 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 this formula:

0.299 * R + 0.587 * G + 0.114 * B

Extended Capabilities

expand all

When generating code, if you choose the genericMATLAB Host Computer target platform, im2gray generates code that uses a precompiled, platform-specific shared library. Use of a shared library preserves performance optimizations but limits the target platforms for which code can be generated.

The im2gray function fully supports GPU arrays. To run the function on a GPU, specify the input data as a gpuArray (Parallel Computing Toolbox). For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Version History

Introduced in R2020b