CONVERTING RGB (COLOR) IMAGE TO GRAY SCALE IMAGE IN MATLAB

Photo of author

By Jackson Taylor

Home » Data Analysis » CONVERTING RGB (COLOR) IMAGE TO GRAY SCALE IMAGE IN MATLAB

Converting a color (RGB) image to a grayscale image is one of the first steps in many image processing tasks. A grayscale image holds one brightness value per pixel instead of three color values, so it is smaller to store and faster to process. This guide shows how to do the conversion in MATLAB, both with the built-in function and by hand, so you understand what is happening to the pixels.

You can watch the video demonstration below, then follow the written steps and code.

DOWNLOAD FILES
MORE EXAMPLES

What is the difference between an RGB and a grayscale image?

An RGB image is stored as a three-dimensional array. The first two dimensions are the rows and columns of pixels, and the third dimension holds three layers: red, green and blue. Each pixel therefore has three numbers.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video

A grayscale image is a two-dimensional array. Each pixel has a single number that represents brightness, from black at the lowest value to white at the highest. For an 8-bit image (class uint8) the range is 0 to 255.

Why convert an image to grayscale?

  • Less data: one channel instead of three means less memory and faster calculations.
  • Simpler algorithms: many methods, such as edge detection, thresholding and histogram analysis, work on intensity rather than color.
  • Focus on structure: when color does not matter, grayscale makes shapes and textures easier to analyze.
  • Preparation for other steps: converting to grayscale is often done before turning an image into a black and white (binary) image.

Method 1: Use rgb2gray

The simplest way is the rgb2gray function. It is normally provided by the Image Processing Toolbox. Newer MATLAB releases also include im2gray, which accepts both RGB and images that are already grayscale.

  1. Read the image. Use imread and give it a file name. MATLAB ships with sample images such as peppers.png, which is handy for testing.
  2. Convert it. Pass the RGB array to rgb2gray.
  3. Display the result. Use imshow to view the image.
  4. Save it if needed. Use imwrite to write the grayscale image to a file.
See also
PLOTTING DATA ON INTERNET USING PYTHON AND THINGSSPEAK.COM

The code looks like this:

rgbImage = imread(‘peppers.png’);

grayImage = rgb2gray(rgbImage);

imshow(grayImage);

imwrite(grayImage, ‘gray_peppers.png’);

If you have not yet shown an image in MATLAB, our guide on displaying an image in MATLAB covers imshow and related options in more detail.

Check the result

Use the size function to confirm the conversion worked:

size(rgbImage)

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

size(grayImage)

The first call returns three numbers (rows, columns and 3). The second returns only two (rows and columns). The image dimensions stay the same, but the color dimension is gone.

Method 2: Convert manually with a weighted sum

It helps to know what rgb2gray does behind the scenes. It does not simply average the three channels. It calculates a weighted sum, because the human eye is most sensitive to green, less to red and least to blue. The commonly used weights are:

gray = 0.2989 × R + 0.5870 × G + 0.1140 × B

You can reproduce this in MATLAB by splitting the channels:

rgbImage = imread(‘peppers.png’);

R = double(rgbImage(:,:,1));

G = double(rgbImage(:,:,2));

B = double(rgbImage(:,:,3));

grayManual = uint8(0.2989*R + 0.5870*G + 0.1140*B);

imshow(grayManual);

The double calls matter. Arithmetic on uint8 values can saturate or round at each step, which gives poor results. Converting to double first, then back to uint8 at the end, keeps the calculation accurate.

Simple average versus weighted sum

You could also compute (R + G + B) / 3. It works and is easy to explain, but the result often looks flatter or less natural, since a pure green and a pure blue would end up with the same brightness. The weighted version matches how we perceive brightness more closely.

Working with your own images

To use your own picture, place it in the current MATLAB folder or give the full path:

The Ultimate Money-Saving DIY Skill

From power tools and solar banks to your car, batteries are the most expensive part of your gear. Master the step-by-step DIY system to bring dead batteries back to life.

Get the Step-by-Step Guide

rgbImage = imread(‘C:\\images\\photo.jpg’);

The image does not have to come from a file. If you want to capture an image with a USB webcam, you can pass the captured frame directly to rgb2gray in the same way.

See also
NEGATIVE VOLTAGE TO POSITIVE VOLTAGE BOOST CONVERTER- SIMULATION IN MATLAB (-12V DC TO +48V DC)

MATLAB is not the only option. If you also work in Python, see our article on opening an image in Python, which covers the first step of a similar workflow.

Common problems and tips

  • The image is already grayscale. Some files have only one channel. In older releases, calling rgb2gray on them causes an error. Check with size first: if there is no third dimension, no conversion is needed.
  • The file is not found. Make sure the file name, extension and folder are correct, and that MATLAB can see the folder (current folder or added to the path).
  • Indexed images. Some PNG and GIF files are indexed images with a colormap. Convert them to RGB first with ind2rgb, or use ind2gray.
  • The result looks too dark or too bright. Check the data type. Mixing uint8 and double values can cause display problems, because imshow expects doubles in the range 0 to 1 and uint8 values from 0 to 255.
  • Saving the image. A format like PNG keeps the data without loss. JPEG compresses the image and changes pixel values slightly.

What to do after converting to grayscale

Once you have a grayscale image you can move on to other operations, such as adjusting contrast, applying filters, detecting edges or converting to a binary image with a threshold. The download files and the additional examples linked above are a good place to continue.

FAQ

Which function converts an RGB image to grayscale in MATLAB?

Use rgb2gray. It takes an RGB image and returns a grayscale image of the same height and width. In newer releases, im2gray does the same job and also accepts images that are already grayscale.

Does rgb2gray need a toolbox?

It has traditionally been part of the Image Processing Toolbox. If you do not have the toolbox, you can use the manual weighted-sum method shown above, which only needs basic MATLAB.

See also
how to capture an image using usb webcamera in matlab

Why is the grayscale image sometimes not an exact average of R, G and B?

Because rgb2gray weights the channels by how bright each color appears to the human eye. Green contributes most, then red, then blue.

How do I save the grayscale image?

Use imwrite(grayImage, ‘filename.png’). Choose PNG if you want to keep the pixel values exactly as they are.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works