數字影象處理(五) 利用PCA演算法進行人臉識別
阿新 • • 發佈:2019-02-16
load('FaceLab.mat'); %他人原始碼,未經同意不得隨便轉載
% filelist=dir('*.bmp');
%inFilename = filelist.name;
%讀入識別影象
testface = imread('test.bmp');
% testface = rgb2gray(testface);
% testface = imresize(testface, [128 128], 'bicubic');
testface = double(testface(:));
dim=size(StuFaceLab,1);
tal=size(StuFaceLab,2);
class=size(StuFaceLab,3);
ell=2; % ell training sample;
ellsample=1; % ellsample test sample;
t=1e7; % Similarity matrix 的引數
order=1;
dita=1e7;
NumTotal=ell*class;
lpp=NumTotal-class;
lda=class-1;
polynomial=1;
pca=40;
%------------------- KPCA ------------------------------%
Itr=zeros(dim,ell,class); % Training sample feature vector
for classnum=1:class
for e=1:ell
% Itr(:,e,classnum)=Iv(:,e,classnum); %
Itr(:,e,classnum)=StuFaceLab(:,e,classnum); %
end
end
%----------------------------------------------------------------%
% 倒入向量 Iv(dim,ell)
% 樣本類數 class
Imean=zeros(dim,1);
for classnum=1:class
for i=1:ell
Imean=Imean+Itr(:,i,classnum);
end
end
Imean=(1/(ell*class))*Imean; %求平均向量
Q=zeros(dim,ell*class);
for classnum=1:class
for num=1:ell
Q(:,num+(classnum-1)*ell)=Itr(:,num,classnum)-Imean(:,1);
end
end
R=zeros(ell*class,ell*class);
R=Q'*Q; % R's size is ell * ell
d=rank(R);
d=pca;
[U,L]=eigs(R,d,'LM'); % 求出 R 的eigenvector and eigenvalue
Wpca=zeros(dim,d);
for p=1:d
Wpca(:,p)=(1/(sqrt(L(p,p))))*Q*U(:,p);
end
% 程式至此得到了線形變換的矩陣 Wpca .
%----------------------------------------------------------------%
Iy=zeros(d,ell,class); % training feature vector %
for classnum=1:class
for num=1:ell
Y=zeros(d,1);
Iy(:,num,classnum)=Wpca'*Itr(:,num,classnum);
end
end
%---------------------------迴圈體開始-------------------------------%
% X=Tldalpp(:,img,cl); % X input sample vector %
%以下為改進演算法, 求每個類的 Z1 的平均值
% Iymean=zeros(dimension,class);
Iymean=zeros(d,class); % because there two training face, revised by Y.G.Wang
for classnum=1:class % Z1 : the mean of Z1
for i=1:ell
Iymean(:,classnum)=Iymean(:,classnum)+Iy(:,i,classnum);
end
Iymean(:,classnum)=(1/ell)*Iymean(:,classnum);
end
%-------------------------進行匹配-------------------%
%----------------此處可以進行修改,利用其他simlarity measure------------%
G2=zeros(1,class);
for classnum=1:class
G2(1,classnum)=(X'*Iymean(:,classnum))/(norm(X)*norm(Iymean(:,classnum)));
end
Sclass=max(G2);
%---------------得出最後的結果---------------------%
for classnum=1:class
if Sclass==G2(1,classnum)
lastresult=classnum;
end
end
clc
if Sclass > 0.97
fprintf('此臉在本庫中,且是學號:%d\n', lastresult);
else
fprintf('此臉不在本庫中!\n');
end