(2) 根据阈值T将图像分割为前景和背景,分别求出两者的平均灰度值ZO和ZB;
(3) 求出新阈值T=(ZO+ZB)/2;
(4) 若两个平均灰度值ZO和ZB不再变化,即T为阈值,否则转2.迭代计算。
实现如下:
I=imread('gaoshanbei01.jpg');
>> 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)
因篇幅问题不能全部显示,请点此查看更多更全内容