%Filename:ex9_2.m%BP网络数字识别%加载数字0-9图像文件(每个数字有10个文件,共100个文件)%取出图像的最大有效区域,归一化(Normalization)为16×16的二值图像%16×16的二值图像按行顺序排列得到该数字的模式特征向量(16×16=256维)%生成数字0-9的模式特征向量和目标向量(每个数字有10个,共100个)clc;%清除命令窗口clearall;%清除内存变量'Loading......'forkk=0:99p1=ones(16,16);m=strcat('F:\新建文件夹\MATLAB\数字识别\手写数字\',int2str(kk),'.bmp');x=imread(m);%将灰度图像转换成二值图像bw=im2bw(x,0.5);%设threshold=0.5,将亮度大于threshold的像素位置置1(白色),亮度小于threshold的像素位置置为0(黑色)[i,j]=find(bw==0);%检索矩阵bw中等于0的元素的行下标和列下标imin=min(i);imax=max(i);jmin=min(j);jmax=max(j);bw1=bw(imin:imax,jmin:jmax);rate=16/max(size(bw1));bw1=imresize(bw1,rate);%调整图像大小[i,j]=size(bw1);i1=round((16-i)/2);j1=round((16-j)/2);p1(i1+1:i1+i,j1+1:j1+j)=bw1;p1=-1.*p1+ones(16,16);%归一化后的16×16大小二值图像form=0:15p(m*16+1:(m+1)*16,kk+1)=p1(1:16,m+1);%将16×16大小二值图像转成256维BP网络输入特征向量endswitchkkcase{0,10,20,30,40,50,60,70,80,90},t(kk+1)=0;case{1,11,21,31,41,51,61,71,81,91},t(kk+1)=1;case{2,12,22,32,42,52,62,72,82,92},t(kk+1)=2;case{3,13,23,33,43,53,63,73,83,93},t(kk+1)=3;case{4,14,24,34,44,54,64,74,84,94},t(kk+1)=4;case{5,15,25,35,45,55,65,75,85,95},t(kk+1)=5;case{6,16,26,36,46,56,66,76,86,96},t(kk+1)=6;case{7,17,27,37,47,57,67,77,87,97},t(kk+1)=7;case{8,18,28,38,48,58,68,78,88,98},t(kk+1)=8;case{9,19,29,39,49,59,69,79,89,99},t(kk+1)=9;endend'LoadOk.'saveex9_2ptpt;%将手写数字0-9的模式特征矩阵p和目标向量t存为二进制文件ex9_2pt.mat%创建和训练BP神经网络clearall;loadex9_2ptpt;%将二进制文件ex9_2pt.mat的内容读入内存(读入模式特征矩阵和目标向量)pr(1:256,1)=0;pr(1:256,2)=1;net=newff(pr,[251],{'logsig','purelin'},'traingd');net.trainParam.epochs=15000;net.trainParam.goal=0.001;net.trainParam.show=10;net.trainParam.lr=0.05;net=train(net,p,t);saveex9_2netnet;%将创建的神经网络net存为二进制文件ex9_2net.matfortimes=0:99clearall;p(1:256,1)=1;p1=ones(16,16);loadex9_2netnet;%读入神经网络test=input('请输入待识别的完整数字文件名:','s');x=imread(test);figure(1);imshow(x);%显示某数字的原图像%将灰度图像转换成黑白图像bw=im2bw(x,0.5);%设threshold=0.5,将亮度大于threshold的像素位置置1(白色),亮度小于threshold的像素位置置为0(黑色)[i,j]=find(bw==0);%检索矩阵bw中等于0的元素的行下标和列下标imin=min(i);imax=max(i);jmin=min(j);jmax=max(j);bw1=bw(imin:imax,jmin:jmax);rate=16/max(size(bw1));bw1=imresize(bw1,rate);[i,j]=size(bw1);i1=round((16-i)/2);j1=round((16-j)/2);p1(i1+1:i1+i,j1+1:j1+j)=bw1;p1=-1.*p1+ones(16,16);figure(2);imshow(p1);%显示原数字图像的16×16大小特征图像form=0:15p(m*16+1:(m+1)*16,1)=p1(1:16,m+1);endy=sim(net,p1);y=round(y);y(1)en