%%利用最佳直方图熵法(KSW熵法)及传统遗传算法实现灰度图像二阈值分割
%%%主程序
%% 初始部分,读取图像及计算相关信息
clear;
close all;
clc;
I=imread('23.jpg');
figure
figure(1),imshow(I);
I=rgb2gray(I);
% I=imread('Lenna.bmp');
hist=imhist(I); %显示图像数据柱状图
total=0;
for i=0:255
total=total+hist(i+1);
end
hist1=hist/total; %求每点的归一化//求像素为i的概率Pi
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 程序主干部分
%种群随机初始化,种群数取20,染色体二进制编码取16位
t0=clock;
population=20;
X00=round(rand(1,population)*255);
X01=round(rand(1,population)*255);
for i=1:population
X0(i,:)=[X00(i) X01(i)];
end
for i=1:population
if X0(i,1)>X0(i,2)
temp=X0(i,1);
X0(i,2)=temp;
X0(i,1)=temp;
else
end
adapt_value0(i)=ksw_2(X0(i,1),X0(i,2),0,255,hist1);
end
adapt_average0=mean(adapt_value0);
X1=X0;
adapt_value1=adapt_value0;
adapt_average1=adapt_average0;
%循环搜索,搜索代数取100
generation=100;
for k=1:generation
s1=select_2d(X1,adapt_value1);
s_code10=dec2bin(s1(:,1),8);
s_code11=dec2bin(s1(:,2),8);
[c10,c11]=cross_2d(s_code10,s_code11);
[v10,v11]=mutation_2d(c10,c11);
X20=(bin2dec(v10))';
X21=(bin2dec(v11))';
for i=1:population
X2(i,:)=[X20(i) X21(i)];
end
for i=1:population
adapt_value2(i)=ksw_2(X2(i,1),X2(i,2),0,255,hist1);
end
adapt_average2=mean(adapt_value2);
if abs(adapt_average2-adapt_average1)<=0.03
break;
else
X1=X2;
adapt_value1=adapt_value2;
adapt_average1=adapt_average2;
end
end
max_value=max(adapt_value2);
number=find(adapt_value2==max_value);
opt=X2(number(1),:);
t1=clock;
search_time=etime(t1,t0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 阈值分割及显示部分
I_temp1=I;
[height,width]=size(I_temp1);
for i=1:height
for j=1:width
if I_temp1(i,j)<opt(1);
I_temp1(i,j)=0;
else if I_temp1(i,j)>opt(2);
I_temp1(i,j)=255;
else I_temp1(i,j)=180;
end
end
end
end
I1= I_temp1;
disp('灰度图像阈值分割的效果如图所示:');
disp('源图为:Fifure No.1');
disp('最佳直方图熵法及传统遗传算法阈二值分割后的图像为:Fifure No.2');
figure(2);
imshow(I);
title('源图');
figure(3);
imshow(I1);
title('最佳直方图熵法及传统遗传算法阈二值分割后的图像');
disp('最佳直方图熵法及传统遗传算法二阈值为(s,t):');
disp(opt(1));
disp(opt(2));
disp('最佳直方图熵法及传统遗传算法二阈值搜索所用时间(s):');
disp(search_time);
%% 程序结束
评论0