I want convert my color image to grayscale and avoid to use rgb2gray
command.

- 218,885
- 19
- 262
- 358

- 1,006
- 4
- 14
- 38
3 Answers
So then:
I_grey = mean(I_colour, 3);
It's possible you then might need to cast it to a uint8
before you can view it:
I_grey = uint8(mean(I_colour, 3));
Or if you want to be really accurate you should actually be finding a weighted average. See the answer to this question for weighting options: Formula to determine brightness of RGB color
Here is an example of this:
W = permute([0.3086, 0.6094, 0.0820], [3,1,2]);
I_grey = uint8(sum(bsxfun(@times, double(I_colour), W),3));
-
I'm new in MATLAB and this command is complex for me can u use more simple? – Mohammad Farahi Feb 25 '14 at 07:44
-
more simple than one single function? what?? – Dan Feb 25 '14 at 07:45
-
i used that and i faced a blank image !!! – Mohammad Farahi Feb 25 '14 at 07:46
-
If your original image was uint8 then you might have to typecast back to that. I'll edit. – Dan Feb 25 '14 at 07:47
-
What is that error related to? Error using bsxfun Mixed integer class inputs are not supported. – Mohammad Farahi Feb 25 '14 at 08:10
-
@MohammadFarahi you have to cast `I_colour` to a double first, see my edit. Also please read up on typecasting. This is a good starting point: http://www.mathworks.com/matlabcentral/answers/22785-double-and-uint8 – Dan Feb 25 '14 at 08:25
Here's some edits to Dan's answer and additional stuffs to answer your question.
Code -
%// Load image
I_colour = imread('pic1.jpg');
%// Dan's method with the correct (correct if you can rely on MATLAB's paramters,
%// otherwise Dan's mentioned paramters could be correct, but I couuldn't verify)
%// parameters** as listed also in RGB2GRAY documentation and at -
%// http://www.mathworks.com/matlabcentral/answers/99136
W = permute([0.2989, 0.5870, 0.1140], [3,1,2]);
I_grey = sum(bsxfun(@times, double(I_colour), W),3);
%// MATLAB's in-built function
I_grey2 = double(rgb2gray(I_colour));
%// Error checking between our and MATLAB's methods
error = rms(abs(I_grey(:)-I_grey2(:)))
figure,
subplot(211),imshow(uint8(I_grey));
subplot(212),imshow(uint8(I_grey2));
Mathworks guys have beautifully answered this with simple to understand code at - http://www.mathworks.com/matlabcentral/answers/99136

- 218,885
- 19
- 262
- 358
The function rgb2gray
eliminates hue and saturation and retains the information about luminance(brightness).
So, you can convert a pixel located at i and j into grayscale by using following formula.
Formula
grayScaleImage(i,j) = 0.298*img(i,j,1)+0.587*img(i,j,2)+0.114*img(i,j,3)
img(i,j,1) is value of RED pixel.
img(i,j,2) is value of GREEN pixel.
img(i,j,3) is value of BLUE pixel.
grayScaleImage(i,j) is value of the pixel in grayscale in range[0..255]
Psuedo Code
img = imread('example.jpg');
[r c colormap] = size(img);
for i=1:r
for j=1:c
grayScaleImg(i,j) = 0.298*img(i,j,1)+0.587*img(i,j,2)+0.114*img(i,j,3);
end
end
imshow(grayScaleImg);

- 298
- 4
- 10