%迭代阈值选取
clear all;
I=imread('block.jpg');
w=fspecial('average',5); %平滑处理图像
fa=imfilter(I,w,'replicate');
ZMAX=max(max(fa)); %取出最大灰度值
ZMIN=min(min(fa)); %取出最小灰度值
TK=(ZMAX+ZMIN)/2;
bcal=1;
cnt=0;
iForeground=0; %定义前景和背景数
iBackground=0;
ISIZE=size(I); %读出图像大小
while(bcal)
ForegroundSum=0; %定义前景和背景灰度总和
BackgroundSum=0;
for i=1:ISIZE(1) %循环部分求解读下%
for j=1:ISIZE(2)
cnt=cnt+1;
if(cnt==50000) %迭代次数限定
bcal=0;
end
tmp=fa(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(double(TK))));
newI=im2bw(fa,double(TK)/255);
subplot(1,2,1);imshow(I);
xlabel('(a)原始图像');
% subplot(1,3,2);imshow(fa);
% xlabel('(b)平滑处理后图像');
subplot(1,2,2);imshow(newI);
xlabel('(b)迭代法分割效果图')
% I=rgb2gray(I);
% fa=rgb2gray(fa);
%
% subplot(2,3,4);imhist(I);
% xlabel('(a)原始图像直方图');
% subplot(2,3,5);imhist(fa);
% xlabel('(b)平滑处理后图像直方图');
% subplot(2,3,6);imhist(newI);
% xlabel('(c)迭代法分割效果图直方图')