You are on page 1of 2

% Loading date-base path to PCA_FRS

TrainPath = uigetdir('D:\New folder\belajar','select path of training images');


TestPath = uigetdir('D:\New folder\uji','select path of training images');

% Taking test Image from file selector

[path, file]=uigetfile('D:\New folder\uji\*.jpg','MultiSelect','on');


filename=strcat(file, path);
TestImage = imread(filename);

% Number of all images in the training Tdbbase


TrainFiles = dir(TrainPath);
Train_Number = 0;

for i = 1:size(TrainFiles,1)
if not(strcmp(TrainFiles(i).name,'.')|strcmp(TrainFiles(i).name,'..'))
Train_Number = Train_Number + 1;
end
end

% 1) Data-base construction
Tdb = [];
for i = 1 : Train_Number
str = int2str(i);
str = strcat('\',str,'.jpg');
str = strcat(TrainPath,str);

img = imread(str);

if length(size(img))==3
img = rgb2gray(test);
end

[row col] = size(img);

tmp = reshape(img',row*col,1);
Tdb = [Tdb tmp];
end
Train_Number = size(Tdb,2);

% 2) Finding mean-image
m = mean(Tdb,2);

% 3) Subtracting mean-image from Train-Database


A = [];
for i = 1 : Train_Number
temp1 = double(Tdb(:,i)) - m;
A = [A temp1];
end

% 4) Finding co-variance matrix


covr = A'*A;

% 5) Finding eigen values and eigen vectors


[evec eval] = eig(covr);

% 6) Selecting eigen-values w.r.t eigen-vectors


covr_eig_vec = [];
for i = 1 : size(evec,2)
if( eval(i,i)>0 )
covr_eig_vec = [covr_eig_vec evec(:,i)];
end
end

% 7) Projection image matrix ( PCA-output )


projmatrix = A * covr_eig_vec;

% 8) Miniature database
ProjectedImages = [];
Train_Number = size(projmatrix,2);

for i = 1 : Train_Number
temp2 = projmatrix'*A(:,i);
ProjectedImages = [ProjectedImages temp2];
end

% Testing:
% 9) Finding test image projecttion
temp = TestImage(:,:,1);
[irow icol] = size(temp);
InImage = reshape(temp',irow*icol,1);
Difference = double(InImage)-m;
ProjectedTestImage = projmatrix'*Difference;

% 10) Finding euclidean distance


Euc_dist = [];
for i = 1 : Train_Number
q = ProjectedImages(:,i);
temp = ( norm( ProjectedTestImage - q ) )^2;
Euc_dist = [Euc_dist temp];

end

% 11) Finding equivalent image path


[Euc_dist_min , Recognized_index] = min(Euc_dist);
OutputName = strcat(int2str(Recognized_index),'.jpg');
SelectedImage = strcat(TrainPath,'\',OutputName);
SelectedImage = imread(SelectedImage);

% 12) Displaying result


subplot(2,1,1);
imshow(TestImage);
title('Gambar uji');
subplot(2,1,2);
imshow(SelectedImage);
title('Gambar yang cocok');

str = strcat('Gambar yang cocok adalah : ',OutputName);


disp(str);
disp(min(Euc_dist));