clear all;
%---------------------- 打開訓練圖像集 --------------------%
Files = dir('FREET\F1\*.bmp'); %打開文件夾中所有圖像
Dir = 'FREET\F1\';
for k = 1:length(Files);
Filename = [Dir , Files(k).name];
Img = imread(Filename);
x(:,k) = Img(:); % 把圖像放在矩陣x的第k列
end;
nImages = k; % 圖像個數
imsize = size(Img); % 圖像維度
nPixels = imsize(1)*imsize(2); % 圖像總像素數
x = double(x)/255; % 將x轉換爲double型
%----------- 計算每幅訓練圖像的與平均臉的差值 -------%
avrgx = mean(x')'; %計算均值圖像
for i=1:1:nImages
x(:,i) = x(:,i) - avrgx; % x每一列減去平均臉
end;
%-----奇異值分解方法計算協方差矩陣的特徵值和特徵向量----%
cov_mat = x'*x; %協方差矩陣爲x*x’,這裏用奇異值分解
[V,D] = eig(cov_mat); %V爲以特徵向量爲列的矩陣,D爲特徵值組成的對角陣
V = x*V*(abs(D))^-0.5; %求協方差矩陣x*x'的特徵向量
%------------------------計算特徵臉個數--------------------------%
add = 0.0;
D=diag(D); %將對角陣D轉換爲矢量
sum = sum(D);
for k =nImages:-1:1 %由於在D按照從小到大排列,故逆序遍歷
add = add + D(k);
if add/sum > 0.95 %當差異信息比例達到95%時退出循環
break;
end
end
%-------------測試樣本在新空間上投影后的座標-----------%
KLCoef = x'*V;
%---------------------- 打開待識別圖像集 --------------------%
files = dir('FREET\F2\*.bmp'); %打開文件夾中所有圖像
dir = 'FREET\F2\';
for k = 1:length(files);
filename = [dir , files(k).name];
img = imread(filename);
y(:,k) = img(:);
end;
y = double(y)/255;
%----------- 計算每幅待識別圖像的與平均臉的差值 -------%
for i=1:1:nImages
y(:,i) = y(:,i) - avrgx; % y每一列減去平均臉
end;
%-------------待識別樣本在新空間上投影后的座標-----------%
dKLCoef = y'*V;
%---------------------------按照最近鄰法分類------------------------%
count = 0.0; %計數器,用於計算正確識別的人臉個數
for image_index = 1:1:nImages
for i=1:1:nImages
%計算待識別圖像與每幅訓練圖像座標間的歐氏距離,由特徵臉的正交歸一性,歐氏距離就是座標點乘再開方
dist_comp(i) = sqrt(dot(dKLCoef(image_index,:)-KLCoef(i,:), dKLCoef(image_index,:)-KLCoef(i,:)));
end
min_index = find(dist_comp == min(dist_comp)); %找出歐氏距離最小的訓練圖像的下標
if min_index(1) == image_index %判斷最近鄰分類是否正確
count= count + 1;
end
end
rate = count/nImages %輸出識別正確率
轉自:http://lovefreewind.blog.163.com/blog/static/17834635720120904529174/