Yale人脸数据库、PCA算法实现Matlab中特征脸生成和简单的人脸识别

算法实现步骤:

1. 读取训练库中的图片,并把每一张图片生成为一个列向量(需要注意的是如果数据库中的图片人脸位置不一,需要先手动或代码把人脸调整到差不多的位置。图片最好是大小一致的灰度图);

2. 生成训练库向量集合的平均值,即平均脸;

3. 训练库向量集合减去平均脸;

4. 使用eigs()或eig()或svds()生成特征脸空间;

5. 将训练集合投影到特征空间;

6. 读取测试库中的图片,生成列向量集合,并通过计算最小的欧氏距离来计算匹配的人脸图像。



Matlab代码如下:

close all;
clear all;

%read all traning images
train_num = 135;
test_num = 10;
img_dims = [100 100];

trainpath = 'yalefaces/trainingset/';
testpath = 'yalefaces/testset/subject02.happy.gif';
file = 's*';    
train_filenames = dir([trainpath file]);    % return a structure with filenames
test_filenames = dir([testpath file]);      


A = [];
for i = 1 : train_num
    filename = [trainpath train_filenames(i).name];   % filename in the list
    a = imread(filename);
    vec = reshape(a,100*100,1);
    A = [A vec];
end
A = double(A);

%find the mean face and substract it from origin face
mean_face = mean(A,2);

A1 = A;
for i = 1 : train_num
    A1(:,i) = A(:,i) - mean_face;
end

A1 = double(A1);
[ah,aw] = size(A1);

%Peform PCA on the data matrix
C = (1/train_num) * A1' * A1;
[ch,cw] = size(C);

%calculate the top 15 eigenvectors and eigenvalues
[V,D] = eigs(C,15);

%Compute the eigenfaces
eigenface = [];
for i = 1 : 15
    mv = A1 * V(:,i);
    mv = mv/norm(mv);
    eigenface = [eigenface mv];
    [eh,ew] = size(eigenface);
end

%Display the 15 eigenfaces
figure;
for i = 1:15
    im = eigenface(:,i);
    im = reshape(im,100,100);
    subplot(3,5,i);
    im = imagesc(im);colormap('gray');
end

%Project each training image onto the new space
img_project = [];
for i = 1:train_num
    temp = double(A1(:,i)') * eigenface ;
    img_project = [img_project temp'];
end


%read the test image
input_img = imread(testpath);
input_img = imresize(input_img,img_dims);
[p,q] = size(input_img);
temp = reshape(input_img,p*q,1);
temp = double(temp) - mean_face;
%calculate the similarity of the input to each training image
feature_vec = temp' * eigenface ;

dist = [];
for i = 1 : train_num
    distance = norm(feature_vec' - img_project(:,i))^2;
    dist = [dist distance];
end

[dist_min index] = sort(dist);
num1 = index(1);
num2 = index(2);
num3 = index(3);

img1 = A(:,num1);
img1 = reshape(uint8(img1),100,100);
img2 = A(:,num2);
img2 = reshape(uint8(img2),100,100);
img3 = A(:,num3);
img3 = reshape(uint8(img3),100,100);

figure;
subplot(1,4,1);
imshow(input_img);
title('Test image');

subplot(1,4,2);
imshow(img1);
title('Recognition image1');

subplot(1,4,3);
imshow(img2);
title('Recognition image2')

subplot(1,4,4);
imshow(img3);
title('Recognition image3')

Results:

特征脸空间:

Yale人脸数据库、PCA算法实现Matlab中特征脸生成和简单的人脸识别_第1张图片

人脸识别:

Yale人脸数据库、PCA算法实现Matlab中特征脸生成和简单的人脸识别_第2张图片

你可能感兴趣的:(Matlab图像处理)