%迭代法
%迭代式阈值选择算法是对双峰法的改进,它首先选择一个近似阈值T,将图像分割成两部分:R1和R2,然后计算区域R1和R2的均值u1和u2,并选择新的分割阈值T=(u1+u2)/2,重复上述步骤直到u1和u2不再变化为止。
%迭代法是基于逼近的思想,其步骤如下:
%(1)求出图像的最大灰度值和最小灰度值,分别记为ZMAX和ZMIN,令初始阈值T0=(ZMAX+ZMIN)/2。
%(2)根据阈值T将图像分割为前景和背景分别求出两者的平均灰度值ZO和ZB。
%(3)求出新阈值T=(ZO+ZB)/2。
%(4)若两个平均灰度值ZO和ZB不再变化(或T不再变化),则T即为阈值;否则转步骤(2),迭代计算。
clear all;
close all;
clc;
B=imread('picture.jpg');
I=rgb2gray(B);
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(121),imshow(I)
subplot(122),imshow(newI)
评论1