mtalab 彩色转黑白

%str0='C:\Users\Administrator\Pictures\Camera Roll\'

MyYuanLaiPic = imread('C:\Users\Administrator\Pictures\Camera Roll\lena.jpg');%读取RGB格式的图像
MyFirstGrayPic = rgb2gray(MyYuanLaiPic);%用已有的函数进行RGB到灰度图像的转换

[rows , cols , colors] = size(MyYuanLaiPic);%得到原来图像的矩阵的参数
MidGrayPic = zeros(rows , cols);%用得到的参数创建一个全零的矩阵,这个矩阵用来存储用下面的方法产生的灰度图像
OldGrayPic = zeros(rows , cols);
OldGrayPic = uint8(OldGrayPic);
MidGrayPic = uint8(MidGrayPic);%将创建的全零矩阵转化为uint8格式,因为用上面的语句创建之后图像是double型的
%uint8是指0~2^8-1 = 255数据类型
for i = 1:rows 
    for j = 1:cols
        sum = 0;
        sumold = 0;
        for k = 1:colors
              sumold = sumold + MyYuanLaiPic(i , j , k) / 3;%进行转化的关键公式,sum每次都因为后面的数字而不能超过255
                switch k
                    case{1}
                            m = 0.299;
                    case{2}
                            m = 0.587;
                    case{3}
                            m = 0.114;
                end
                sum = sum + MyYuanLaiPic(i , j , k)*m;
        end
        MidGrayPic(i , j) = sum;
        OldGrayPic(i , j) = sumold;
    end
end
%imwrite(MidGrayPic , 'E:/image/matlab/DarkMouseGray.png' , 'png');
imwrite(MidGrayPic , 'DarkMouseGray.png' , 'png');
imwrite(OldGrayPic , 'OldGray.png' , 'png');
%显示原来的RGB图像
figure(1);
imshow(MyYuanLaiPic);

%显示经过系统函数运算过的灰度图像
figure(2);
imshow(MyFirstGrayPic);
%显示经过其他人设计的函数运算过的灰度图像
figure(3);
imshow(OldGrayPic);
%显示自制的转化之后的灰度图像
figure(4);
imshow(MidGrayPic);

 

你可能感兴趣的:(mtalab 彩色转黑白)