Function to convert RGB to grayscale
2 views (last 30 days)
Show older comments
Silvia Caruso
on 7 Apr 2015
Commented: Image Analyst
on 7 Apr 2015
How can I convert an RGB or indexed images into gray scale without using B=ind2gray(A,map) in matlab? I should create a new function to do it.
5 Comments
Image Analyst
on 7 Apr 2015
Good catch by Geoff about your misuse of the size() function. Steve Eddins has a blog about this common issue with size(): http://blogs.mathworks.com/steve/2011/03/22/too-much-information-about-the-size-function/
Accepted Answer
James Garritano
on 7 Apr 2015
Your code confuses "I" with "RGB" Your code uses "RGB" as one of its inputs, but it refers to "I" as if it were the input instead. Either rename your input to "I" or replace "I" with "RGB."
For example:
R=RGB(:,:,1);
G=RGB(:,:,2);
B=RGB(:,:,3);
size is being used improperly. RGB is a three-dimensional variable, but you are only trying to save two of the dimensions' sizes. In the code you've posted, the variable that you designated as m will have a value equal to product of the number of columns and the number of colors in your image.
If you want to use size, replace your call with this:
[rows,cols,colors]=size(RGB);
You are reversing the convention for rows and columns. Normally, we designate rows as "m" and columns as "n." (e.g., "an m by n matrix") This resulted in an error in your code, but I'd advise either not using those variable names or switching to the m = rows, n = columns convention.
Do not use a for loop for matrix mathematics Your code should be rewritten so you don't use any loops.
Whenever possible, in MATLAB, attempt to remove loops from your code if you can accomplish the same thing with matrix mathematics. If you're dealing a large number of large images, your code will function poorly.
In your example, you can rewrite your loop as an arithmetic statement.
I = 0.2989 *R + 0.5870 * G + 0.1140 * B;
This avoids using the loop. This will make the code perform several thousand times faster. (on my machine, it took around 8.4 seconds to run a loop, but 0.004 seconds to to perform the a matrix addition)
0 Comments
More Answers (1)
Geoff Hayes
on 7 Apr 2015
Edited: Geoff Hayes
on 7 Apr 2015
Silvia - look at the algorithm used by rgb2gray which creates the grayscale value by calculating the weighted sum of the red (R), green (G), and blue (B) channels
0.2989 * R + 0.5870 * G + 0.1140 * B
You could try doing this for your RGB images. If the image is indexed, then see how ind2gray does the same.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!