% ----------------------- README ------------------------------------------
%% 清空环境
clc
clear
close all
%% 载入图像及其计算
I = imread('KimSoHyun.jpg');
% I=imread('Barbara.tif');
% I=imread('lena.bmp');
[~,~,n] = size(I);
if n==3 % 彩色灰度化
I = rgb2gray(I);
end
garynum = 255; % 灰度级为255
hist = imhist(I);
total = 0;
for i=0:255
total = total+hist(i+1);
end
hist1 = hist/total;
HT = 0;
for i=0:255
if hist1(i+1)==0
temp = 0;
else
temp = hist1(i+1)*log(1/hist1(i+1));
end
HT = HT+temp;
end
tic
%% 遗传算法参数
maxgen=500; %进化代数
sizepop=500; %种群规模
pcross=[0.9]; %交叉概率
pmutation=[0.2]; %变异概率
eps=1; % 二进制个数需要
bound=[0 255]; %变量范围
NC = size(bound,1);
num=max(ceil(log2((bound(2)-bound(1))/eps + 1)));
lenchrom=NC*num; %变量字串长度
trace=[];
%% 个体初始化
individuals=struct('fitness',zeros(1,sizepop), 'chrom',[]); %种群结构体
avgfitness=[]; %种群平均适应度
bestfitness=[]; %种群最佳适应度
bestchrom=[]; %适应度最好染色体
% 初始化种群
for i=1:sizepop
individuals.chrom(i,:)=Code(lenchrom,bound); %随机产生个体
x=individuals.chrom(i,:);
individuals.fitness(i)=fun(x,I,bound,lenchrom,hist1,HT); %个体适应度
end
%找最好的染色体
[bestfitness bestindex]=max(individuals.fitness);
bestchrom=individuals.chrom(bestindex,:); %最好的染色体
avgfitness=sum(individuals.fitness)/sizepop; %染色体的平均适应度
% 记录每一代进化中最好的适应度和平均适应度
chrom = [];
%% 进化开始
for i=1:maxgen
% 选择操作
individuals=Select(individuals,sizepop);
avgfitness=sum(individuals.fitness)/sizepop;
% 交叉操作
individuals.chrom=Cross(pcross,lenchrom,individuals.chrom,sizepop,bound);
% 变异操作
individuals.chrom=Mutation(pmutation,lenchrom,individuals.chrom,sizepop,bound);
% 计算适应度
for j=1:sizepop
x=individuals.chrom(j,:);
individuals.fitness(j)=fun(x,I,bound,lenchrom,hist1,HT);
end
%找到最小和最大适应度的染色体及它们在种群中的位置
[newbestfitness,newbestindex]=max(individuals.fitness);
[worestfitness,worestindex]=min(individuals.fitness);
% 代替上一次进化中最好的染色体
if bestfitness<newbestfitness
bestfitness=newbestfitness;
bestchrom=individuals.chrom(newbestindex,:);
end
individuals.chrom(worestindex,:)=bestchrom;
individuals.fitness(worestindex)=bestfitness;
avgfitness=sum(individuals.fitness)/sizepop;
chrom = [chrom;bestchrom];
% trace=[trace;avgfitness bestfitness]; %记录每一代进化中最好的适应度和平均适应度
trace(i) = bestfitness;
end
%进化结束
toc
%% 结果显示
[r ~]=size(trace);
gen = 1:maxgen;
plot(gen,trace(1,:),'Color','#1A3B30','LineWidth',3);
% hold on
% plot(gen,trace(2,:),'-.','Color','#509579','LineWidth',3);
% plot(gen,trace(3,:),'--','Color','#99BDBD','LineWidth',3);
% plot(gen,trace(4,:),':','Color','#C6E3D8','LineWidth',3);
xlabel('Generation','FontName','Times New Roman','FontSize',12);
ylabel('Fitness Value','FontName','Times New Roman','FontSize',12);
title('SGA','FontName','Times New Roman','FontSize',12);
% legend('1','2','3','4','FontName','Times New Roman','FontSize',11)
[x,y] = size(I);
img = zeros(x,y);
bestchrom=Dec1(bestchrom,bound(1),bound(2),lenchrom);
bestchrom
for i=1:x
for j=1:y
if I(i,j)<bestchrom
img(i,j) = 0;
else
img(i,j) = 255;
end
end
end
figure
subplot(121)
imshow(I);
subplot(122)
imshow(img)