算法实现参考Github某外国开源代码:
https://github.com/HelloYaoZhang/Face-Recognition-Using-PCA
我主要是套个皮,完成一个人机交互的小作业,有需要去资源下载自取。
因为做的实在是比较早,就不写注释了兄弟们,凑活看吧。
具体实现如下:
一、组件设计界面
二、逻辑设计代码:
classdef app < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
Button matlab.ui.control.Button
Button_2 matlab.ui.control.Button
Button_3 matlab.ui.control.Button
UIAxes2 matlab.ui.control.UIAxes
Label matlab.ui.control.Label
UIAxes1 matlab.ui.control.UIAxes
end
properties (Access = public)
Training_Path % Description
Testing_Path% Description
TestImage % Description
SelectedImage % Description
filename % Description
im % Description
pathname % Description
end
properties (Access = private)
end
methods (Access = private)
function Training_Data = ReadFace(~,Training_Path)
% ---------- Construct 2D matrix from all of the 1D image vectors in the training data file ------------
flist = dir(strcat(Training_Path,'\*.jpg'));
Training_Data = [];
for imidx = 1:length(flist)
fprintf('Constructing Training Image Data Space [%d] \n', imidx);
path = strcat(Training_Path,strcat('\',int2str(imidx),'.jpg'));
img = imread(path);
[irow, icol] = size(img);
temp = reshape(img',irow*icol,1); % Reshaping 2D images to 1D image vectors
Training_Data = [Training_Data temp];
end
fprintf('\n');
end
function [m, A, Eigenfaces] = EigenfaceCore(~,Training_Data)
%----------------------------Calculate the mean image ------------------------
% ---------------------compute the covariance matrix --------------------------
m = mean(Training_Data,2);
Train_Number = size(Training_Data,2);
temp_m = [];
for i = 1 : Train_Number
temp_m = [temp_m m];
end
A = double(Training_Data) - temp_m;
%-------------------use the "svd" function to compute the eigenvectors
%--------------------and eigenvalues of the covariance matrix.
disp('Computing...Wait a second please')
L = A'*A;
%size(L)
[V, D] = eig(L);
%-----------------------------Sort and eliminate eigenvalues---------------
Eig_vec = [];
for i = 1 : size(V,2)
if( D(i,i)>1000 ) % Set Threshold value whatever you like
Eig_vec = [Eig_vec V(:,i)];
end
end
Eigenfaces = A * Eig_vec;
end
function OutputName = Recognition(~,TestImage, m, A, Eigenfaces)
ProjectedImages = [];
Train_Number = size(A,2);
for i = 1 : Train_Number
temp = Eigenfaces' * A(:,i); % Projection of centered images into facespace
ProjectedImages = [ProjectedImages temp];
end
%-------------Project the test image you selected into Eigenfaces space-------------
InputImage = imread(TestImage);
temp = InputImage(:,:,1);
[irow, icol] = size(temp);
InImage = reshape(temp',irow*icol,1);
Difference = double(InImage)-m;
Projected_TestImage = Eigenfaces'*Difference; % Test image feature vector
%----------------------- Calculate Euclidean distances and find the
% index of image of minmum Euclidean distances--------------------
Euc_dist = [];
for i = 1 : Train_Number
q = ProjectedImages(:,i);
temp = ( norm( Projected_TestImage - q ) )^2;
Euc_dist = [Euc_dist temp];
end
[Euc_dist_min , Recognized_index] = min(Euc_dist);
OutputName = strcat(int2str(Recognized_index),'.jpg');
end
function Visualize_Eigenface(~,Eigenfaces, imgrow, imgcol)
%-------------------Show the maxmum nine pictures of Eigenfaces---------------
Num_Eigenvalue = size(Eigenfaces,2);
figure('Name','Eigenface')
img = zeros(imgrow, imgcol);
for i=1:min(Num_Eigenvalue,9)
img(:) = Eigenfaces(:,i);
subplot(3,3,i);
imshow(img',[]);
end
end
end
% Callbacks that handle component events
methods (Access = private)
% Button pushed function: Button
function ButtonPushed(app, event)
app.Training_Path = 'TrainDatabase'; %Set your directory for training data file
app.Testing_Path = 'TestDatabase'; %Set your directory for testing data file
[app.filename, app.pathname] = uigetfile({'*.jpg'},'Pick a Testing Photo From TestDatabase please');
app.TestImage = [app.pathname, app.filename];
app.im = imread(app.TestImage);
app.UIFigure.AutoResizeChildren = 'off';
imshow(app.im,'Parent',app.UIAxes1);
title('Test Image','Parent',app.UIAxes1);
end
% Button pushed function: Button_3
function Button_3Pushed(app, event)
choice=questdlg('你是否要关闭?','关闭','Yes','No','No');
switch choice
case 'Yse'
delete(app.UIFigure);
case 'No'
return;
end
end
% Callback function
function Image2_3Clicked(app, event)
figure('name','Recognition Result')
app.UIFigure.AutoResizeChildren = 'off';
imshow(app.im,'Parent',app.UIAxes2);
title(app.UIAxes,'Test Image','Parent',app.UIAxes2);
imshow(app.SelectedImage,'Parent',app.UIAxes2);
title('Recognition Result','Parent',app.UIAxes2);
end
% Button pushed function: Button_2
function Button_2Pushed(app, event)
Training_Data = ReadFace(app,app.Training_Path);
[m, A, Eigenfaces] = EigenfaceCore(app,Training_Data);
OutputName = Recognition(app,app.TestImage, m, A, Eigenfaces);
app.SelectedImage = strcat(app.Training_Path,'\',OutputName);
app.SelectedImage = imread(app.SelectedImage);
imshow(app.SelectedImage,'Parent',app.UIAxes2);
title('Recognition Result','Parent',app.UIAxes2);
disp('Done');
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure and hide until all components are created
app.UIFigure = uifigure('Visible', 'off');
app.UIFigure.Position = [100 100 640 480];
app.UIFigure.Name = 'MATLAB App';
% Create Button
app.Button = uibutton(app.UIFigure, 'push');
app.Button.ButtonPushedFcn = createCallbackFcn(app, @ButtonPushed, true);
app.Button.BackgroundColor = [0.4941 0.1843 0.5569];
app.Button.FontSize = 15;
app.Button.FontColor = [1 1 0.0667];
app.Button.Position = [94 124 152 47];
app.Button.Text = '选择图片';
% Create Button_2
app.Button_2 = uibutton(app.UIFigure, 'push');
app.Button_2.ButtonPushedFcn = createCallbackFcn(app, @Button_2Pushed, true);
app.Button_2.BackgroundColor = [0 0.4471 0.7412];
app.Button_2.FontSize = 15;
app.Button_2.Position = [396 123 149 48];
app.Button_2.Text = '开始识别';
% Create Button_3
app.Button_3 = uibutton(app.UIFigure, 'push');
app.Button_3.ButtonPushedFcn = createCallbackFcn(app, @Button_3Pushed, true);
app.Button_3.BackgroundColor = [1 0 0];
app.Button_3.FontSize = 15;
app.Button_3.FontColor = [1 1 1];
app.Button_3.Position = [245 41 152 47];
app.Button_3.Text = '退出程序';
% Create UIAxes2
app.UIAxes2 = uiaxes(app.UIFigure);
title(app.UIAxes2, 'Recognition Result')
xlabel(app.UIAxes2, '')
ylabel(app.UIAxes2, '')
app.UIAxes2.FontName = 'Times New Roman';
app.UIAxes2.FontSize = 15;
app.UIAxes2.Box = 'on';
app.UIAxes2.XTick = [];
app.UIAxes2.YTick = [];
app.UIAxes2.TitleFontWeight = 'bold';
app.UIAxes2.Position = [325 196 291 185];
% Create Label
app.Label = uilabel(app.UIFigure);
app.Label.HorizontalAlignment = 'center';
app.Label.FontName = '黑体';
app.Label.FontSize = 20;
app.Label.FontWeight = 'bold';
app.Label.Position = [194 404 254 42];
app.Label.Text = '人物图像识别';
% Create UIAxes1
app.UIAxes1 = uiaxes(app.UIFigure);
title(app.UIAxes1, 'TestImage')
xlabel(app.UIAxes1, '')
ylabel(app.UIAxes1, '')
app.UIAxes1.FontName = 'Times New Roman';
app.UIAxes1.FontSize = 15;
app.UIAxes1.Box = 'on';
app.UIAxes1.XTick = [];
app.UIAxes1.YTick = [];
app.UIAxes1.TitleFontWeight = 'bold';
app.UIAxes1.Position = [35 196 291 185];
% Show the figure after all components are created
app.UIFigure.Visible = 'on';
end
end
% App creation and deletion
methods (Access = public)
% Construct app
function app = app
% Create UIFigure and components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end
二、用户需求
用户简单需求:
用户可选择图片在图像库中识别出图片相似度度高的图片,并显示在GUI界面上。即用户可点击选择图片按钮,多次选择图片,点击识别按钮即可识别出相似图像,此外,可点击退出程序按钮退出应用。
三、运行效果截图
图片库:
运行截图: