clear;
clc;
pathname1 = uigetdir(cd,'请选择文件夹');%pathname为文件夹路径
if pathname1==0
msgbox('请重选文件夹')
return
end
pathname=strcat(pathname1,'\');
AuImgList =dir(fullfile(pathname,'*.jpg'));
k =length(AuImgList);
dir=strcat(pathname,'gray','');
mkdir(dir); % create folder for saving picture
for m=1:1:k
fileName=strcat(pathname,AuImgList(m).name); %获取图像文件的绝对路径
AuImage_data{m}=imread(fileName); %读图像文件
image_size=size(AuImage_data{m});
dimension=numel(image_size);
if dimension==3
AuImageGray_data{m} = rgb2gray(AuImage_data{m});%用已有的函数进行RGB到灰度图像的转换
[rows , cols , colors] = size(AuImage_data{m});%得到原来图像的矩阵的参数
MidGrayPic = zeros(rows , cols);%用得到的参数创建一个全零的矩阵,这个矩阵用来存储用下面的方法产生的灰度图像
MidGrayPic = uint8(MidGrayPic);%将创建的全零矩阵转化为uint8格式,因为用上面的语句创建之后图像是double型的
for i = 1:rows
for j = 1:cols
sum = 0;
for k = 1:colors
sum = sum + AuImage_data{m}(i , j , k) / 3;%进行转化的关键公式,sum每次都因为后面的数字而不能超过255
end
MidGrayPic(i , j) = sum;
end
end
str= strcat (dir,'\',AuImgList(m).name(1:end-4) , '.jpg') ; % 连接字符串形成生成的灰度图像的文件名,1:end-4去掉原来文件的后缀名
imwrite(MidGrayPic , str, 'jpg'); %写文件
end
end