image=imread('se026.png');
%gray_image=rgb2gray(image);
subplot(1,2,1);
imshow(image);
%subplot(1,2,2);
%imhist(gray_image);
%image=double(image);
t=mean(image(:));
is_done=false;
count=0;
while ~is_done
r1=find(image<=t);
r2=find(image>t);
temp1=mean(block(r1)); %求r1区域均值
if isnan(temp1); %保证结果非NaN
temp1=0;
end
temp2=mean(block(r2)); %求r2区域均值
if isnan(temp2) %保证结果非NaN
temp2=0;
end
t_new=(temp1+temp2)/2;
is_done=abs(t_new-t)<1;
t=t_new;
count=count+1;
if count>=1000
Error='Error:Cannot find the ideal threshold.'
return
end
end
count %输出迭代次数
t %输出阈值计算结果
[m,n]=size(gray_image);
result=zeros(m,n);
result(r1)=255; %图像二值化
resule(r2)=0;
result=uint8(result);
figure
imshow(result);
%gray_image=rgb2gray(image);
subplot(1,2,1);
imshow(image);
%subplot(1,2,2);
%imhist(gray_image);
%image=double(image);
t=mean(image(:));
is_done=false;
count=0;
while ~is_done
r1=find(image<=t);
r2=find(image>t);
temp1=mean(block(r1)); %求r1区域均值
if isnan(temp1); %保证结果非NaN
temp1=0;
end
temp2=mean(block(r2)); %求r2区域均值
if isnan(temp2) %保证结果非NaN
temp2=0;
end
t_new=(temp1+temp2)/2;
is_done=abs(t_new-t)<1;
t=t_new;
count=count+1;
if count>=1000
Error='Error:Cannot find the ideal threshold.'
return
end
end
count %输出迭代次数
t %输出阈值计算结果
[m,n]=size(gray_image);
result=zeros(m,n);
result(r1)=255; %图像二值化
resule(r2)=0;
result=uint8(result);
figure
imshow(result);