如何使用特征值和特征向量获得特征脸?

时间:2014-03-10 19:06:16

标签: matlab

我想从特征值中找到特征值,这里是参考代码。

clc;
clear all;
close all;

% I) READ IMAGES
for i = 1:9
    img{i} = imread(['C:\Users\shree\Desktop\archana\target\' num2str(i) '.jpg']);
end

%II) CONVERTING TO GRAY SCALE
gray_img=cellfun(@rgb2gray,img,'uniformoutput',false);
%imshow(gray_img{2});

%III) RESIZING GRAY IMAGES
res_img = cellfun(@(x)(imresize(x, [50, 50])), gray_img, 'UniformOutput', false);
%imshow(res_img{2});

%DISPLAYING ALL IMAGE
    D=[res_img{1} res_img{2} res_img{3}
        res_img{4} res_img{5} res_img{6}
        res_img{7} res_img{8} res_img{9}];
   figure, imshow(D);

%MEAN IMAGE 
mean_img=(res_img{1}+res_img{2}+res_img{3}+res_img{4}+res_img{5}+res_img{6}+res_img{7}+res_img{8}+res_img{9})/9;
figure,imshow(mean_img);

%III)SINGLE VECTOR CONVERSION
vect_img= cellfun(@(x)((x(:))), res_img, 'UniformOutput', false);

%MEAN OF SINGLE VECTOR
mean_vect=(vect_img{1}+vect_img{2}+vect_img{3}+vect_img{4}+vect_img{5}+vect_img{6}+vect_img{7}+vect_img{8}+vect_img{9})/9;

%DEVIATION MATRIX
dev_mat=cellfun(@(x) ((x)-mean_vect),vect_img,'uniformoutput',false);
%imshow(dev_mat{1})
U=[dev_mat{1} dev_mat{2} dev_mat{3} dev_mat{4} dev_mat{5} dev_mat{6} dev_mat{7} dev_mat{8} dev_mat{9} ]
figure ,imshow(U);

%COVARIENCE MATRIX
C=[double(U')*double(U)]/9;

%VARIENCE
v=var(C);

%EIGEN VALUES
lambda = eig(C);
[V,D] = eig(C) ;% eigenvalues (D) & eigenvectors (V),=> A*V = V*D
size(lambda);
% EXTRACT DIONAL OF MATRIX VECTOR
%V = diag(V);

%SORT VARIENCE ACC.DECREASING ORDER
sort(lambda,'descend');

我达到了将eiganvalues安排到不增加的顺序plz帮助我如何获得以获得eigenfaces.regards

2 个答案:

答案 0 :(得分:2)

使用double(NEW) * double(NEW');

此外,请勿使用meancov作为变量名称。它们是内置函数。我猜你在协方差计算中想要C = cov(double(NEW) * double(NEW'));

答案 1 :(得分:2)

不要逐个加载每个文件,请尝试使用

ImageDatabasePath ='C:\Users\shree\Desktop\final data';

ImageFiles = dir(ImageDatabasePath);

Train_Number = 0;

for i = 1:size(ImageFiles,1)

if not(strcmp(ImageFiles(i).name,'.')|strcmp(ImageFiles(i).name,'..')...

        |strcmp(ImageFiles(i).name,'Thumbs.db'))

    Image_Number = Image_Number + 1; 

end
end

现在将图像制作成一维图像载体

 T = [ ];

  for i = 1 : Image_Number

str = int2str(i);
str = strcat('\',str,'.jpg');
str = strcat(ImageDatabasePath,str);

imt = imread(str);

[irow icol] = size(imt);

temp = reshape(imt,irow*icol,1);   
T = [T temp];                  
end

计算平均值

m = mean(T,2); 

Train_Number = size(T,2);

计算每张图片与平均图片的偏差

A = [ ];  

for i = 1 : Image_Number
    temp = double(T(:,i)) - m; 
    A = [A temp];
end

创建协方差矩阵

L = A'*A; 

用特征值计算特征值和特征向量V-本征向量D-对角矩阵

[V D] = eig(L); 

L_eig_vec = [];

for i = 1 : size(V,2) 

    if( D(i,i)>1 )

        L_eig_vec = [L_eig_vec V(:,i)];
    end
end

协方差矩阵C(或所谓的“特征脸”)的特征向量可以从L's eiegnvectors中恢复。

Eigenfaces = A * L_eig_vec;