clc; clear;
I=imread('d:\\1.jpg');
subplot(221);imshow(I);title('原图像'); I1=rgb2gray(I);
%双峰法
newI=im2bw(I1,150/255);
subplot(222),imshow(newI);title('双峰法阈值分割后的图像');
%迭代法阈值分割 ZMax=max(max(I)); ZMin=min(min(I)); TK=(ZMax+ZMin)/2; bCal=1;
iSize=size(I); while(bCal)
iForeground=0; iBackground=0; ForegroundSum=0; BackgroundSum=0; for i=1:iSize(1)
for j=1:iSize(2) tmp=I(i,j); if(tmp>=TK)
iForeground=iForeground+1;
ForegroundSum=ForegroundSum+double(tmp); else
iBackground=iBackground+1;
BackgroundSum=BackgroundSum+double(tmp); end end end
ZO=ForegroundSum/iForeground; ZB=BackgroundSum/iBackground; TKTmp=uint8((ZO+ZB)/2); if(TKTmp==TK) bCal=0; else
TK=TKTmp; end end
disp(strcat('迭代后的阈值:',num2str(TK))); newI=im2bw(I,double(TK)/255);
subplot(223),imshow(newI);title('迭代法阈值分割后的图像')
% 大律法
level=graythresh(I1); BW=im2bw(I,level);
subplot(224),imshow(BW);title('大律法计算阈值')
disp(strcat('大律法计算灰度阈值:',num2str(uint8(level*255))))