function [threshold, thresholds, t, max_fitness, max_fitnesses] = get_threshold(image, N, Pc, Pm, epsilon, stop)
% 利用遗传算法计算分割阈值
% image 输入灰度图像; N 种群规模; eplison 最大换代数;
% Pc 交叉率; Pm 变异率; stop 最大适应度停止次数
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 设置默认值
scale = 255; % 灰度值范围[0,255]
L = 256; % 索引最大值256,和灰度值范围相差1
t = 1; % 记录迭代次数
S = zeros(1,N); % 根据种群规模构建种群,默认值灰度值是0
t_stop = 0; % 种群连续多次未进化停止算法
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 灰度直方图分布信息
[p, u] = image_hist(image);
%随机产生N个0到255之间的整数作为灰度值,构建种群S
for i=1:N
S(i) = randi(L)-1; % 产生0到255的随机整数
end
%计算适应度
fitnesses = get_fitness(S, p, u, scale, L);
max_fitness = max(fitnesses);
max_fitnesses(t) = max_fitness;
for i=1:size(fitnesses,2)
if fitnesses(i) == max_fitness
break;
end
end
thresholds(t) = S(i);
%开始迭代
%迭代条件 1.总迭代次数不到上上限。 2.停止次数没到阈值。
while t <= epsilon && t_stop <= stop
%概率选择
indecs = probility_seletion(N, fitnesses);
%产生新的种群
S1 = S(indecs);
%交叉
crossover();
%变异
mutation();
%此时的S1就是变异后的种群
%计算适应度
new_fitness = get_fitness(S1, p, u, scale,L);
new_max_fitness = max(new_fitness);
if new_max_fitness > max_fitness
%进化成功
S = S1;
max_fitness = new_max_fitness;
fitnesses = new_fitness;
t_stop = 1;
else
t_stop = t_stop+1;
end
t = t+1;
max_fitnesses(t) = max_fitness;
for i=1:size(fitnesses,2)
if fitnesses(i) == max_fitness
break;
end
end
thresholds(t) = S(i);
end
threshold = thresholds(t);
%交叉 对S1进行交叉
function crossover()
%需要参与交换的染色体数目
c_count = int8(N * Pc);
%交换前cross_length位
cross_length = size(dec2bin(S1(1)),2)/2;
for i = 1:2:c_count
if i+1 <= c_count
bin1 = dec2bin(S1(i),8);
bin2 = dec2bin(S1(i+1),8);
top_bin1 = bin1(1:int8(cross_length));
top_bin2 = bin2(1:int8(cross_length));
bin1(1:int8(cross_length)) = top_bin2;
bin2(1:int8(cross_length)) = top_bin1;
S1(i) = bin2dec(bin1);
S1(i+1) = bin2dec(bin2);
end
end
end
%变异 对S1进行变异
function mutation()
for i=1:N
rand_n = rand;
if(rand_n <= Pm)
%变异 决定变异位置
bin_m = dec2bin(S1(i));
index_m = randi(size(bin_m,2));
if(bin_m(index_m) == '1')
bin_m(index_m) = '0';
else
bin_m(index_m) = '1';
end
S1(i) = bin2dec(bin_m);
end
end
end
end