本程序采用2级PCA提取特征,最小藕欧距离分类器进行人脸识别,实验数据为orl人脸库。

本文作为我从事模式识别研究的开始,留下此代码作为见证。

由于Matlab软件是初次使用,很多函数还不是很熟识,所以代码的执行效率可能不够高,本代码仅供参考。

参考文献:J. Yang, D. Zhang, A.F. Frangi, J.Y.

Yang, Two-dimensional PCA: a new approach to appearancebased face

representation and recognition, IEEE Trans. Pattern Anal. Mach.

Intell. 26 (1) (2004)

131–137.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%This program is writen by zhangming on 2009-5-10

%this is my homeworke of machine leaning

%my e-mail: zm_fred@163.com

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear all

clc

close all

%选择训练样本路径

TrainDatabasePath = uigetdir('D:\myexperiments\mydate\orl_faces',

'Select training database path' );

%选择测试样本路径

TestDatabasePath = uigetdir('D:\myexperiments\mydate\orl_faces',

'Select test database path');

%生成测试数据集

%T = CreateDatabase(TrainDatabasePath);

TrainFiles = dir(TrainDatabasePath);

class_Number = 0;

s=size(TrainFiles,1);

%计算训练样本个数

for i = 1:size(TrainFiles,1)

if

not(strcmp(TrainFiles(i).name,'.')|strcmp(TrainFiles(i).name,'..')|strcmp(TrainFiles(i).name,'README'))

class_Number = class_Number + 1; % Number of all images in the

training database

end

end

%读取训练集第一个图像,得到其尺寸,初始化图像矩阵

str = strcat(TrainDatabasePath,'\s1.\1.pgm');

img = imread(str);

[irow,icol] = size(img);

A=zeros(irow,icol,2);

%合计有Train_Number人的目录,每个目录存放某人的10幅人脸图像,取前n副图像做训练样本

n=5;

for i = 1 : class_Number

topdir =

int2str(i);

topdir =

strcat(TestDatabasePath,'\s',topdir);

for j= 1 :

n

%for j= 1 :2 :9

str = int2str(j);

str = strcat(topdir,'\',str,'.pgm');

img = imread(str);

A(:,:,n*(i-1)+j) = img; end

end

%得到训练样本的个数Train_Number

Train_Number = size(A,3);

%求所有训练样本向量的均值 M

M=mean(A,3);

%求图像散布矩阵Gt

Gt=zeros(icol,icol);

for i = 1 : Train_Number

temp =

A(:,:,i)-M;

Gt

= Gt + temp'*temp;

end

Gt=Gt/Train_Number;

d = 10;

[V D] = eigs(Gt,d);

%PCA空间投影图像

%V = orth(V);

ProjectedImages = zeros(irow,d);

for i = 1 : Train_Number

ProjectedImages(:,:,i) =

A(:,:,i)*V; end

%已识别测试集的数目Recnum

Recnum=0

for i = 1 : class_Number

topdir =

int2str(i);

topdir =

strcat(TestDatabasePath,'\s',topdir);

for j=

n+1:10

%for j= 2 :2 :10

str = int2str(j);

TestImage = strcat(topdir,'\',str,'.pgm'); %测试样本路径

%测试样本原始数据

im = imread(TestImage);

%测试样本的投影

ProjectedTestImage = double(im)*V;

gc=[];

%for t=1 : class_Number

% mk=mean( ProjectedImages( :,:,(t-1)*n+1:t*n), 3);

%此处参数t*n,n是前n个样本作为训练样本,

% % temp = norm( ProjectedTestImage - mk );

% gc=[gc

temp];

%end

for i=1 : Train_Number

temp = norm( ProjectedTestImage - ProjectedImages( :,:,i

),'fro');

gc=[gc temp];

end

[dist_min , Recognized_index1] = min(gc);

Recognized_index1 = floor((Recognized_index1-1)/n)+1;

OutputName =

Recognized_index1; OutputName

=strcat(TestDatabasePath,'\s',int2str(OutputName));

%如果测试样本分类正确,则 Recnum加1

if(strcmp(OutputName,topdir)==1)

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐