rgb2gray是matlab内部一种处理图像的函数,通过消除图像色调和饱和度信息同时保留亮度实现将将RGB图像或彩色图转换为灰度图像,即灰度化处理的功能,调用这个功能的格式是I = rgb2gray(RGB),意思是将真彩色图像RGB转换为灰度强度图像I 。 灰度化处理有多种处理方式:分量法 最大法 平均法 加权平均法。这里,Matlab的rgb2gray函数采用的是对R、G、B分量进行加权平均的算法:
0.2989R+ 0.5870G + 0.1140B
验证程序如下(为了便于观察,实验时应选用一个RGB各分量较为明显的图像):
clear all;clc;close all;
img = imread('test3.jpg');
% 提取RGB分量
img_r = img(:,:,1);
img_g = img(:,:,2);
img_b = img(:,:,3);
figure;
subplot(2,3,1),imshow(img), title('原图');
subplot(2,3,4),imshow(img_r), title('R分量');
subplot(2,3,5),imshow(img_g), title('G分量');
subplot(2,3,6),imshow(img_b), title('B分量');
% 灰度变换,公式:f(x,y)=0.2989R+ 0.5870G + 0.1140B
img_gray1 = img(:,:,1)*0.2989+ img(:,:,2)*0.5870+ img(:,:,3)*0.1140;
subplot(2,3,2),imshow(img_gray1), title('由公式变换');
% 灰度变换,rgb2gray()函数
img_gray2 = rgb2gray(img);
subplot(2,3,3),imshow(img_gray2), title('rgb2gray变换');
上图可以看出,对于R分量图,由于G、B分量的灰度值均为0,因此G、B区域灰度值为0即为黑色区域,R分量区域灰度值均为255即为白色圆区域;同理可解释G、B分量图。