clc;clear all;close all;
I=imread('szu.jpg');
I=rgb2gray(I);
L=256;
p=normalize(I,L); %归一化
indnum=20; %个体数量
pc=0.9; %交叉概率
pm=0.2; %变异概率
%种群初始化
pop=zeros(1,indnum);
for i=1:indnum
pop(i)=ceil(L*rand);
end
gen=200; %遗传代数
x=1:L;y=otsu(x,L,p);
for a=1:gen
%计算个体适应值
fitness=otsu(pop,L,p);
if a==1||a==20||a==40||a==70||a==90
figure;
plot(x,y);
hold on;plot(pop,fitness,'ro');
end
%优胜劣汰
pop=select(pop,fitness,indnum);
%交叉
pop=cross(pop,pc);
%变异
pop=mutate(pop,pm);
end
fitness=otsu(pop,L,p);
figure;
plot(x,y);hold on;plot(pop,fitness,'ro');
figure;
subplot(221),imshow(I);
subplot(222),imhist(I);
T=find(fitness==max(fitness));
T=pop(T(1));
[li,ri]=size(I);
J=I;
for i=1:li
for j=1:ri
if I(i,j)<=T
J(i,j)=0;
else
J(i,j)=L-1;
end
end
end
subplot(223),imshow(J);
subplot(224),imhist(J);
评论1