Convert a color image to grayscale in MATLAB witho

2019-03-03 17:30发布

This question already has an answer here:

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

3条回答
我只想做你的唯一
2楼-- · 2019-03-03 17:47

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));
查看更多
贼婆χ
3楼-- · 2019-03-03 17:47

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);
查看更多
手持菜刀,她持情操
4楼-- · 2019-03-03 17:51

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

查看更多
登录 后发表回答