フィルターのクリア

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.
  1 件のコメント
Silvia Caruso
Silvia Caruso 2015 年 4 月 7 日
thank you

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeConvert Image Type についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by