clear;
clc;
train_path='E:\TrainingSet\angry\positive\';
images = dir('E:\TrainingSet\angry\positive\*.bmp');
phi=zeros(30,64*64);
% 加载样本图像到 30*(64*64)的矩阵中,每一行代表一幅图像
for i=1:30
path=strcat(train_path,images(i).name);
Image=imread(path);
Image=imresize(Image,[64,64]);
phi(i,:)=double(reshape(Image,1,[]));
end;
% 计算平均脸,并保存用以查看
mean_phi=mean(phi,1);
mean_face=reshape(mean_phi,64,64);
Image_mean=mat2gray(mean_face);
imwrite(Image_mean,'meanface2.bmp','bmp');
% 使用matlab自带的pca进行降维
[coeff, score, latent, TSQUARED] = princomp(phi,'econ');
%display Eigenface
for i=1:29
Eigenface=reshape(coeff(:,i),[64,64]);
figure(i);
imshow(mat2gray(Eigenface));
end
% 进行测试
%使用测试样本进行测试
clc;
test_path='E:\BIT\code\FER\meanface.bmp';
error=zeros([1,4]);
Image=imread(test_path);
Image=double(imresize(Image,[64,64]));
phi_test=zeros(1,64*64);
phi_test(1,:)=double(reshape(Image,1,[])); % 读入的测试图像保存为一行,行向量
X_test=phi_test-mean_phi;
Y_test=X_test*coeff;
X_test_re=Y_test*coeff';
Face_re=X_test_re+mean_phi;
%calculate error rate
e=Face_re-phi_test;
%%display figure
Face_re_2=reshape(Face_re(1,:),[64,64]);
figure(i);
imshow(mat2gray(Image));
title('Original');
figure(10+i);
imshow(mat2gray(Face_re_2));
title('Reconstruct');
error(1,i)=norm(e);
%dispaly error rate
error_rate=error(1,i);
display(error_rate);
转载自 :
http://www.tuicool.com/articles/jMBjyu