PCA检测人脸的简单示例_matlab实现

时间:2023-02-22 08:32:12
%训练
%Lx=X'*X
clear;
clc;
train_path='..\Data\TrainingSet\';
phi=zeros(64*64,20);
for i=1:20
path=strcat(train_path,num2str(i),'.bmp');
Image=imread(path);
Image=imresize(Image,[64,64]);
phi(:,i)=double(reshape(Image,1,[])');
end;
%mean
mean_phi=mean(phi,2);
mean_face=reshape(mean_phi,64,64);
Image_mean=mat2gray(mean_face);
imwrite(Image_mean,'meanface.bmp','bmp');
%demean
for i=1:19
X(:,i)=phi(:,i)-mean_phi;
end
Lx=X'*X;
tic;
[eigenvector,eigenvalue]=eigs(Lx,19);
toc;
%normalization
for i=1:19
%K-L变换
UL(:,i)=X*eigenvector(:,i)/sqrt(eigenvalue(i,i));
end
%display Eigenface
for i=1:19
Eigenface=reshape(UL(:,i),[64,64]);
figure(i);
imshow(mat2gray(Eigenface));
end

得到的均值图像mean_face:

PCA检测人脸的简单示例_matlab实现

前19个最大主元对应的“特征脸”

PCA检测人脸的简单示例_matlab实现

测试
测试用样本:

PCA检测人脸的简单示例_matlab实现

%使用测试样本进行测试
clc;
test_path='..\Data\TestingSet\';
error=zeros([1,4]);
for i=1:4
path=strcat(test_path,num2str(i),'.bmp');
Image=imread(path);
Image=double(imresize(Image,[64,64]));
phi_test=zeros(64*64,1);
phi_test(:,1)=double(reshape(Image,1,[])');
X_test=phi_test-mean_phi;
Y_test=UL'*X_test;
X_test_re=UL*Y_test;
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);
end
重建出的测试样本与原样本的对比:

PCA检测人脸的简单示例_matlab实现

四副测试样本的重建误差分别为:
1.4195e+003
1.9564e+003
4.7337e+003
7.0103e+003

可见测试样本为人脸的样本的重建误差显然小于非人脸的重建误差。