马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册
x
function yz=threshold(imgr)
c=zeros(1,256);
omega0=zeros(1,256);
omega1=zeros(1,256);
mu_0=zeros(1,256);
mu_1=zeros(1,256);
delta=zeros(1,256);
g=0;
[m, n]=size(imgr);
yz=zeros(m, n);
c=imhist(imgr);
%% Frequency of every gray level
for i=1:256
p(i)=c(i)/(m*n); % frequency
end
p1=sum(p(1:256)); % 概率和为1
%% the average of the image
for i=1:256
mu=(i-1)*p(i)+g;
g=mu;
end
g=0;
%% the minimum of the gray level
for i=1:256
if c(i)~=0
min=i-1;
break
end
end
%% the maximum of the gray level
for i=256:-1:1
if c(i)~=0
maxi=i-1;
break
end
end
%% the probablity of every part in the image
for th=min+2:maxi
for i=min:th-1
omega0(th)=p(i)+g; % the probablity of part1 in the image
g=omega0(th);
end
g=0;
for i=min:th-1
mu_0(th)=(i-1)*p(i)/omega0(th)+g; % the average of gray level in the part1
g=mu_0(th);
end
g=0;
for j=th:maxi
omega1(th)=p(j)+g; % the probablity of part2 in the image
g=omega1(th);
end
g=0;
for j=th:maxi
mu_1(th)=(j-1)*p(j)/omega1(th)+g; % the average of gray level in the part2
g=mu_1(th);
end
g=0;
end
%% the maximum of variance between part1 and part2
for th=min:maxi
delta(th)=omega0(th)*(mu-mu_0(th))^2+omega1(th)*(mu-mu_1(th))^2;
end
%% 求方差最大值对应的阈值
max=delta(min);
level=min;
for th=min:maxi
if max<delta(th)
max=delta(th);
level=th;
end
end
% [~, level]=max(delta); % 求得最佳阈值
for i=1:m
for j=1:n
if imgr(i,j)>=level
yz(i,j)=255;
else
yz(i,j)=0;
end
end
end |