map1=imread('p.jpg');
[row,col,dep]=size(map1); %行,列,深度值
map=zeros(row,col);
pixsum=row*col; %像素总数
%灰度化
for i=1:row
for j=1:col
map(i,j)=0.11*map1(i,j,1)+0.59*map1(i,j,2)+0.3*map1(i,j,3);
end
end
%灰度化完成,输出灰度图
figure(1)
imshow(map,[])
title('原始灰度图像')
Y=zeros(row,col); %存储输出图像
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5根据通道二值化
for i=1:row
for j=1:col
if map1(i,j,2)>map1(i,j,1)&&map1(i,j,2)>map1(i,j,3)
Y(i,j)=1;
else
Y(i,j)=0;
end
end
end
figure(2)
imshow(Y,[])
title('二值化后图像')
%腐蚀
B=ones(3,3);%腐蚀剂
OUT1=zeros(row,col);%程序中间输出1
OUT2=zeros(row,col);%程序中间输出2
for i=2:row-1
for j=2:col-1
a=sum(sum(Y(i-1:i+1,j-1:j+1).*B));
if a==9
OUT1(i,j)=1;
else
OUT1(i,j)=0;
end
end
end
%腐蚀完成
figure(3)
imshow(OUT1,[])
title('腐蚀后二值图')
figure(4)
imshow(B,[])
title('结构元素')
dOUT1=Y-OUT1;
figure(5)
imshow(dOUT1,[])
title('原二值图减腐蚀后的图')
%对原图膨胀
for i=2:row-1
for j=2:col-1
a=sum(sum(Y(i-1:i+1,j-1:j+1).*B));
if a>=1;
OUT2(i,j)=1;
else
OUT2(i,j)=0;
end
end
end
%膨胀完成
figure(6)
imshow(OUT2,[])
title('膨胀后的图')
dOUT2=Y-OUT2;
figure(7)
imshow(dOUT2,[])
title('原二值图减膨胀后的图')