clear all;clc;
x=imread('Lenagray.bmp');%输入原图像
x=mat2gray(x);%对原图像进行灰度化处理
figure;
imshow(x);%显示灰度化处理的图
title('灰度图');
figure;
imhist(x);%获得原始直方图
title('原始直方图');
%后面对直方图进行平滑的时候需要两份数据。
x1=imhist(x);
%x1=double(x1);
x2=imhist(x);
% x2=double(x2);
%计算峰的个数。
count=0;
for i=2:255
if( x1(i-1) < x1(i) && x1(i+1) < x1(i) )
count=count+1;
end
end
%判断是否为双峰直方图?如果是,将谷底对应的灰度级作为阈值;
%如果不是,对直方图进行平滑;
%看是否能够平滑成双峰?如果能,将谷底对应的灰度级作为阈值;
%如果不能,这个方法就不适用。
z=0;
while(count~=2)
x2(1)=( x1(1)+x1(1)+x1(2))/3;
for i=2:255
x2(i)=( x1(i-1)+x1(i)+x1(i+1) )/3;
end
x2(256)=( x1(255)+x1(256)+x1(256) )/3;
x1=x2;
count=0;
for j=2:255
if( x2(j-1) < x2(j) && x2(j+1) < x2(j) )
count=count+1;
end
end
z=z+1;
if(z>=1000)
break
end
end
figure;
i=0:255;
plot(i,x2);
title('平滑后的直方图');
for i=2:255
if( x2(i-1) >= x2(i) && x2(i+1) >= x2(i) )
k=i-1;
end
end
x3=im2bw(x,k/255);
figure;
imshow(x3);
title('二值化图');