今天,我们来讲解Matlab中把彩色图片转换为黑白图片的函数rgb2gray,即图像灰度转换函数rgb2gray。这也是图像处理中比较重要的一环,因此也要讲解其用法。其实,可以理解为一张图片是一个三维矩阵(rgb分别为三个二维矩阵,合成一个三维矩阵),然后利用rgb2gray转换为一个二维矩阵,方便后期图像处理。

其实,就是这个RGB三维矩阵拆分为三个二维矩阵,然后相同位置处的元素值通过一个关系式,计算得到一个新的值,这样就可以转换为一个二维矩阵。我们直到RGB三维矩阵中,每个值的范围都在0-255之间。只要这个转换关系式的系数和为1,我们就可以得到一个二维矩阵,且每个值得范围也在0-255之间。
官方给得关系式大致为0.299 * R + 0.587 * G + 0.114 * B,其中0.299+0.587+0.114=1。比如一个颜色代码为#483D8B,对应得rgb为72,61,139。然后使用上述关系式,可以得到一个灰度值为73.181,取整为73。这时,如果你要将得到得灰度矩阵,以图片方式显示。那么,该rgb即为73,73,73,对应颜色代码为#494949。

下面,我们接着以上一篇关于Matlab图像读取函数imread的文章为例子,讲解该灰度转换函数rgb2gray的实际效果。
%% %清理工作区与命令区 clc clear close all %% %图片读取 I1 = imread('0827.jpg'); figure(1) imshow(I1) I2 = rgb2gray(I1); figure(2) imshow(I2)

大致的用法就是上面了,关于rgb2gray函数的更多介绍,可以参考官方文档,具体如下:
>> help rgb2gray rgb2gray Convert RGB image or colormap to grayscale. rgb2gray converts RGB images to grayscale by eliminating the hue and saturation information while retaining the luminance. I = rgb2gray(RGB) converts the truecolor image RGB to the grayscale intensity image I. NEWMAP = rgb2gray(MAP) returns a grayscale colormap equivalent to MAP. Class Support ------------- If the input is an RGB image, it can be uint8, uint16, double, or single. The output image I has the same class as the input image. If the input is a colormap, the input and output colormaps are both of class double. Notes ----- rgb2gray converts RGB values to grayscale values by forming a weighted sum of the R, G, and B components: 0.2989 * R + 0.5870 * G + 0.1140 * B The coefficients used to calculate grayscale values in rgb2gray are identical to those used to calculate luminance (E'y) in Rec.ITU-R BT.601-7 after rounding to 3 decimal places. Rec.ITU-R BT.601-7 calculates E'y using the following formula: 0.299 * R + 0.587 * G + 0.114 * B Example ------- I = imread('example.tif'); J = rgb2gray(I); figure, imshow(I), figure, imshow(J); indImage = load('clown'); gmap = rgb2gray(indImage.map); figure, imshow(indImage.X,indImage.map), figure, imshow(indImage.X,gmap); See also rgb2ind. rgb2gray 的参考页 名为 rgb2gray 的其他函数
原创文章,作者:古哥,如若转载,请注明出处:https://iymark.com/program/matlab-pic-rgb2gray.html