How can I convert a color image to grayscale in MATLAB?
Asked Answered
E

7

10

I am trying to implement an algorithm in computer vision and I want to try it on a set of pictures. The pictures are all in color, but I don't want to deal with that. I want to convert them to grayscale which is enough for testing the algorithm.

How can I convert a color image to grayscale?

I'm reading it with:

x = imread('bla.jpg');

Is there any argument I can add to imread to read it as grayscale? Is there any way I change x to grayscale after reading it?

Eurythermal answered 22/11, 2009 at 19:12 Comment(0)
D
25

Use rgb2gray to strip hue and saturation (ie, convert to grayscale). Documentation

Disloyalty answered 22/11, 2009 at 19:17 Comment(1)
They really need to stop moving the documentation. :)Disloyalty
P
8
x = imread('bla.jpg');
k = rgb2gray(x);
figure(1),imshow(k);
Plowman answered 27/12, 2009 at 12:5 Comment(1)
>> k = rgb2gray(im); Undefined function 'rgb2gray' for input arguments of type 'uint8'.Roughcast
P
2

I found this link: http://blogs.mathworks.com/steve/2007/07/20/imoverlay-and-imagesc/ it works.

it says:

im=imread('your image');
m=mat2gray(im);
in=gray2ind(m,256);
rgb=ind2rgb(in,hot(256));
imshow(rgb);
Pieria answered 29/6, 2011 at 7:21 Comment(0)
B
2

you can using this code:

im=imread('your image');
k=rgb2gray(im);
imshow(k);

using to matlab

Bielefeld answered 11/11, 2012 at 19:54 Comment(0)
R
1

I=imread('yourimage.jpg');
p=rgb2gray(I)
Rather answered 14/10, 2015 at 12:45 Comment(1)
I know that the answer is simple, but code-only answers are discouraged here. Please add a little context, explain what rgb2gray does and maybe link to the documentation.Marlite
B
1

Use the imread() and rgb2gray() functions to get a gray scale image.

Example:

I = imread('input.jpg');
J = rgb2gray(I);
figure, imshow(I), figure, imshow(J); 

If you have a color-map image, you must do like below:

[X,map] = imread('input.tif');
gm = rgb2gray(map);
imshow(X,gm);

The rgb2gray algorithm for your own implementation is :

f(R,G,B) = (0.2989 * R) + (0.5870 * G) + (0.1140 * B)
Buzzell answered 14/6, 2017 at 14:34 Comment(0)
C
0

Color Image

Color Image

Gray Scale image

Gray Scale image

  bg = imread('C:\Users\Ali Sahzil\Desktop\Media.png');  // Add your image 
  redChannel = bg(:, :, 1);
  greenChannel = bg(:, :, 2);
  blueChannel = bg(:, :, 3);
  grayImage = .299*double(redChannel) + .587*double(greenChannel) 
  +.114*double(blueChannel);
  imshow(grayImage);
Cupronickel answered 12/4, 2021 at 16:44 Comment(2)
Is this a better solution than using the built-in rgb2gray?Eurythermal
Yeah, it is completely fine to use the build-in function but doing thing manual gives you a better understanding of how a grayscale image is generated.Cupronickel

© 2022 - 2024 — McMap. All rights reserved.