目录
💥1 概述
📚2 运行结果
🎉3 参考文献
👨💻4 Matlab代码
💥1 概述
本文为Storn和Price制定的著名差分进化计算智能算法的实现。该算法使用Otsu准则作为适应度函数,可用于使用多个阈值对灰度图像进行阈值设置。
该程序旨在生成任何灰度图像的0到255级直方图,然后尝试找到阈值,在该阈值下,图像可以最佳地分离为属于图像前景的像素和属于图像背景的像素。最佳阈值的评估使用Otsu标准进行,阈值的Otsu适应度作为“类间方差”返回。值越高,适合度越好。差分进化保持生成1到256范围内的阈值,并评估图像的阈值的适合性。使用突变和交叉,一代又一代地选择更为理想的阈值。用户可以选择运行多个试验,并选择这些试验中的最佳阈值,并显示分割图像以及直方图和阈值的位置。
📚2 运行结果
🎉3 参考文献
[1]刘波,王凌,金以慧.差分进化算法研究进展[J].控制与决策,2007(07):721-729.DOI:10.13195/j.cd.2007.07.3.liub.001.
👨💻4 Matlab代码
主函数部分代码:
% This is the main file for running Differential Evolution
clc;clear all;close all;
images = {'lena_gray.png', 'barbara_gray.bmp'};
imgName = char(images(1));
infor = imfinfo(imgName);
disp(infor);
[I, colormap] = imread(imgName);
if isempty(colormap), I = rgb2gray(I); else I = ind2gray(I, colormap);end
I = im2uint8(I);
searchSpace = imhist(I);
%-----Control panel
thresh = 8;%the number of thresholds
population = 30;%the number of vectors
masterBeta = 2.0;%beta is real number belongs to [0 -> 2]
cr = 0.3;%crossover probability range [0 -> 1]
generations = 200;
numTrials = 1;
if population < 4, disp('Population should be more than 3');return;end
minThresh = 1; maxThresh = numel(searchSpace);
figNum = 1;
figure(figNum);clf;figNum=figNum+1;imshow(I);title('Original image');
%figure(figNum);clf;figNum=figNum+1;imhist(I);title(strcat('histogram of : ',imgName));
%OtsuThreshold = graythresh(I);II = im2bw(I);imshow(II);title('Otsu thresholded image');
runtime = [];
fitStore = [];
bestThresholdAmongTrials = [];
bestFitnessAmongTrials = 0;
tempBestFitnessAmongTrials = 0;
fastestGenerationForBestFitness = 0;
for aTrial = 1:numTrials
tic;
tempFitStore = [];
vBeta = masterBeta;%variable beta
fprintf('Trial: %d\n', aTrial);
X = floor(minThresh + (maxThresh - minThresh) * rand(thresh, population));
U = X;
generationAtBestFit = [0 0];%stores generation and best fitness
spaceSize = size(searchSpace, 1);
totalPixels = sum(searchSpace);
normProba = searchSpace ./ totalPixels;%normalized probabilities
if thresh < 1 || thresh > spaceSize, disp('Thresholds should be in a range of 1 to 256');return;end
%-----Get an initial Fitness
[fitnessX, X] = OtsuFitness(X, spaceSize, totalPixels, normProba);
[val, fittest] = max(fitnessX);