user2307268
user2307268

Reputation:

How do i apply principal component analysis on an image

I am trying to apply pca on an image. Assign new W axis which is the first principal component,and second principal component as the P axis. In the W–P axis,the image is re-plotted. can anyone tell me how to do it?

I tried the following code but i cant proceed further. Please help.

I2=;%grayscale image
arr=[];
for i=1:size(I2,1)
  for j=1:size(I2,2)
    arr=[arr;i,j,I2(i,j)];
  end
end
c=pca(arr);
c=c(:,1:2);%i select the first two components here. How do i proceed now

Upvotes: 2

Views: 2142

Answers (1)

bilaly
bilaly

Reputation: 536

In PCA the eigenvalue matrix, the largest eigenvalues represent the the most prominent features, e.g nose. with that in mind locating these values is a simple matter of reshaping the image to produce a covariance matrix and calculating the eigenvalues and the extracting the correct eigenvector columns. with that done you reshape the matrix again and display it..

basic sample code attached below:

% Reshape the image into a row vector where each row
% is placed next to the one above it. 
MD_image1_Row = reshape(MD_image1.',1,[]);

% multiplying the the row matrix with its transpose to form a very large
% matrix
cov_matrix = (1/3).*(MD_image1_Row * MD_image1_Row .');

% finding the eigenvalues and eigenvectors of the matrix formed above
[Vector, Value] = eig(cov_matrix);

% by looking at the eigenvalue matrix the three (depending on the image)
% largest eigenvalues are located and then the corresponding column in the 
% Eigenvector matrix is taken and manipulated to produce the Eigenface

% Extracting Eigenvector column
Eig_Vector1 = Vector(:,2803); %value is example

% reshaping Eigenvector into a matrix with the same dimensions as the
% original image
Eig_1_Matrix = reshape(Eig_Vector1.', 51,55); %value is example

% checking size of the EigenMatrix - this is to check the new image has the 
% same size as the original images
EigenMatrix = size(Eig_1_Matrix)

% displaying EigenMatrix image using specific limits so that the images are
% displayed correctly
figure, CC = imshow(Eig_1_Matrix,...
                    [min(Eig_1_Matrix(:)),...
                    max(Eig_1_Matrix(:))]);

tip: light intensity of the subject needs to be taken into account, image orientation also needs to be taken into account to display it correctly.

once you have identified the features you wish and extracted the correct eigenvector columns you can label them and do whatever you wish.

Upvotes: 5

Related Questions