%主函数%
clear all
clc
generatesample('sample.mat');
gaP=[100 0.00001];
bpP=[500 0.00001];
load('sample.mat');
gabptrain(gaP,bpP,p,t)
load('net.mat');
img=imread('a.bmp');
bw=segment(net,img);
figure;
subplot(1,2,1);
imshow(img);
title('分割前二值图像对比图')
subplot(1,2,2);
imshow(bw);![图片说明](https://img-ask.csdn.net/upload/201904/21/1555831878_32610.png)
title('分割后二值图像对比图')
%传统BP训练
epochs=200;
goal=0.0001;
net=newcf([0 255],[7 1],{'tansig' 'purelin'});
net.trainParam.epochs;
net.trainParam.goal=goal;
load('sample.mat');
net=train(net,p,t);
%遗传BP训练
gaP=[100 0.00001];
bpP=[500 0.00001];
gabptrain(gaP,bpP,p,t);
%子程序%
function []=generatesample(path)
p=[0:1:255];
t=zeros(1,256);
t(82:256)=1;
save(path,'p','t');
function [net]=gabptrain(gaP,bpP,P,T)
[W1,B1,W2,B2]=getWBbyga(gaP);
net=initnet(W1,B1,W2,B2,bpP);
net=train(net,P,T);
function [net]=initnet(W1,B1,W2,B2,paraments)
epochs=500;
goal=0.01;
if(nargin>4)
epochs=paraments(1);
goal=paraments(2);
end
net=newcf([0 255],[6 1],{'tansig','purelin'});
net.trainParam.epochs=epochs;
net.trainParam.goal=goal;
net.iw{1}=W1;
net.iw{2}=W2;
net.b{1}=B1;
net.b{2}=B2;
function [W1,B1,W2,B2]=getWBbyga(paraments)
Generation=100;
fitnesslimit=-Inf;
if(nargin>0)
Generations=paraments(1);
fitnesslimit=paraments(2);
end
[P,T,R,S1,S2,S]=nninit;
FitnessFunction=@gafitness;
numberOFVariables=S;
opts=gaoptimset('PlotFcns',{@gaplotbestf,@gaplotstopping},'Generations',Generations,'FitnessLimit',fitnesslimit);
[x,Fval,ecitFlag,Output]=ga(FitnessFunction,numberOFVariables,opts);
function f=gafitness(y)
[P,T,R,S1,S2,Q,S]=nninit;
x=y;
[W1,B1,W2,B2,P,T,A1,A2,SE,val]=gadecod(x);
f=val;
function [W1,B1,W2,B2,P,T,A1,A2,SE,val]=gadecod(x)
[P,T,R,S1,S2,Q,S]=nninit;
for i=1:S1,
W1(i,1)=x(i);
end
for i=1:S2,
W2(i,1)=x(i+S1);
end
for i=1:S1,
B1(i,1)=x(i+S1+S2);
end
for i=1:S2,
B2(i,1)=x(i+S1+S2+S1);
end
[m n]=size(P);
sum=0;
SE=0;
for i=1:n
xi=W1*P(i)+B1;
A1=tansig(x1);
x2=W2*A1+B2;
A2=purelin(x2);
se=sumsqr(T(i)-A2);
sum=sum+SE;
end
val=10/sum;
function [P,T,R,S1,S2,Q,S]=nninit
P=[0:3:255];
T=zeros(1,86);
t(29:86)=1;
[R,Q]=size(P);
[S2,Q]=size(T);
S1=6;
S=R*S1+S2+S1+S2;
function [bw]=setment(net,img)
[m n]=size(img);
P=img(:);
P=double(P);
P=P';
T=sim(net,P);
T(T
T(T>0.5)=255;
t=uint8(T);
t=t';
bw=reshape(t,m,n);