필터 지우기
필터 지우기

Function to convert RGB to grayscale

조회 수: 2 (최근 30일)
Silvia Caruso
Silvia Caruso 2015년 4월 7일
댓글: Image Analyst 2015년 4월 7일
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
Silvia Caruso
Silvia Caruso 2015년 4월 7일
thank you
Image Analyst
Image Analyst 2015년 4월 7일
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/

댓글을 달려면 로그인하십시오.

채택된 답변

James Garritano
James Garritano 2015년 4월 7일
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)

추가 답변 (1개)

Geoff Hayes
Geoff Hayes 2015년 4월 7일
편집: Geoff Hayes 2015년 4월 7일
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.

카테고리

Help CenterFile Exchange에서 Convert Image Type에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by