加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

使用PCA进行降维重构图像处理

(2016-10-11 00:04:01)
分类: 图像处理
今天终于把PCA的整个计算过程弄清楚。看到了一篇十分好的文章《使用matlab对训练样本图像降维,并对测试图像使用变换矩阵降维并重构》,原文如下:
——————————————————————————————————————————————
作者:watkins  原文链接


clear;
clc;
train_path='E:\TrainingSet\angry\positive\';
images = dir('E:\TrainingSet\angry\positive\*.bmp');
phi=zeros(30,64*64);

% 加载样本图像到 30*(64*64)的矩阵中,每一行代表一幅图像
for i=1:30
path=strcat(train_path,images(i).name);
Image=imread(path);
Image=imresize(Image,[64,64]);
phi(i,:)=double(reshape(Image,1,[]));
end;

% 计算平均脸,并保存用以查看
mean_phi=mean(phi,1);
mean_face=reshape(mean_phi,64,64);
Image_mean=mat2gray(mean_face);
imwrite(Image_mean,'meanface2.bmp','bmp');

% 使用matlab自带的pca进行降维
[coeff, score, latent, TSQUARED] = princomp(phi,'econ');

%display Eigenface
for i=1:29
Eigenface=reshape(coeff(:,i),[64,64]);
figure(i);
imshow(mat2gray(Eigenface));
end

% 进行测试
%使用测试样本进行测试
clc;
test_path='E:\BIT\code\FER\meanface.bmp';
error=zeros([1,4]);

Image=imread(test_path);
Image=double(imresize(Image,[64,64]));
phi_test=zeros(1,64*64);
phi_test(1,:)=double(reshape(Image,1,[])); % 读入的测试图像保存为一行,行向量
X_test=phi_test-mean_phi;
Y_test=X_test*coeff;
X_test_re=Y_test*coeff';
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);
——————————————————————————————————————————————
如果嫌上面的代码太繁琐,下面是我单单把PCA部分抽取出来的简化版:


X = [2.5 2.4;
0.5 0.7;
2.2 2.9;
1.9 2.2;
3.1 3.0;
2.3 2.7;
2 1.6;
1 1.1;
1.5 1.6;
1.1 0.9];

% 调用princomp进行PCA计算
[pc,score,latent,tsquare] = princomp(X);

% 数据降维:X-〉X1,由2维降为1
X_mean = mean(X);
X_adjust = [X(:,1)-X_mean(1) X(:,2)-X_mean(2)];

tranMatrix = pc(:,1);
X1 = X_adjust * tranMatrix * tranMatrix';
X1 = [X1(:,1)+X_mean(1)];

% 数据还原:
X_re = X_adjust * pc * pc';
X_re = [X_re(:,1)+X_mean(1) X_re(:,2)+X_mean(2)];
进行运算得:
X1 =
    2.3713
    0.6050
    2.4826
    1.9959
    2.9460
    2.4289
    1.7428
    1.0341
    1.5131
    0.9804

X_re =
    2.5000    2.4000
    0.5000    0.7000
    2.2000    2.9000
    1.9000    2.2000
    3.1000    3.0000
    2.3000    2.7000
    2.0000    1.6000
    1.0000    1.1000
    1.5000    1.6000
    1.1000    0.9000
可见,X_re 成功还原了X。

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有