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)
Best Answer