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
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);
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));
So then:
It's possible you then might need to cast it to a
uint8
before you can view it: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:
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
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
Here's some edits to Dan's answer and additional stuffs to answer your question.
Code -
Mathworks guys have beautifully answered this with simple to understand code at - http://www.mathworks.com/matlabcentral/answers/99136