clear;
close all;
im=imread('../img/test.bmp');
% 显示原图像
figure(1)
subplot(1,2,1);
imshow(im);
title('原图像');
% 灰度化并显示灰度图
figure(1)
img=rgb2gray(im);
subplot(1,2,2);
imshow(img);
title('灰度图');
% 画灰度直方图
figure(2)
[M,N] = size(im);
[H,x] = imhist(img,256);
stem(x,H/M/N,'.');
title('灰度直方图');
%=============图像分割=============%
% 迭代法自动阈值分割
thres = 0.5*(double(min(img(:)))+double(max(img(:)))); % 初始化阈值
done = false; %结束标志
while ~done
g = img >= thres;
tnext = 0.5*(mean(img(g))+mean(img(~g)));
done = abs(thres-tnext) < 0.5;
thres = tnext;
end;
imgbw = im2bw(img,thres/255); %二值化
% 显示自动阈值分割图
figure(3)
imshow(imgbw);
strcat(tt,'分割阈值为:',num2str(thres));
title(tt);