Matlab实现AppDesigner实现人脸识别小应用

算法实现参考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界面上。即用户可点击选择图片按钮,多次选择图片,点击识别按钮即可识别出相似图像,此外,可点击退出程序按钮退出应用。

三、运行效果截图

图片库:

运行截图:

  • 13
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
人脸识别是计算机视觉领域的一个重要研究方向,目前已有很多成熟的算法和工具可以实现人脸识别Matlab作为一个强大的数学软件,也提供了丰富的图像处理和计算机视觉工具箱,可以用来实现人脸识别。 下面是一个简单的基于Matlab人脸识别程序,主要包括以下步骤: 1. 读取训练集和测试集图像 2. 提取训练集图像的特征向量 3. 选取测试图像,并提取其特征向量 4. 计算测试图像与每个训练图像的距离,并选取距离最近的k个训练图像 5. 统计距离最近的k个训练图像中出现频率最高的人脸标签,作为测试图像的识别结果 以下是简单的Matlab代码实现: ```matlab % 读取训练集和测试集图像 train_dir = 'train_images/'; test_dir = 'test_images/'; train_files = dir([train_dir '*.jpg']); test_files = dir([test_dir '*.jpg']); % 提取训练集图像的特征向量 train_features = []; for i = 1:length(train_files) img = imread([train_dir train_files(i).name]); feature = extract_feature(img); train_features = [train_features; feature]; end % 选取测试图像,并提取其特征向量 test_idx = 1; test_img = imread([test_dir test_files(test_idx).name]); test_feature = extract_feature(test_img); % 计算测试图像与每个训练图像的距离,并选取距离最近的k个训练图像 k = 5; distances = pdist2(train_features, test_feature); [~, idx] = sort(distances); nearest_k = idx(1:k); % 统计距离最近的k个训练图像中出现频率最高的人脸标签,作为测试图像的识别结果 labels = {'person1', 'person2', 'person3', 'person4', 'person5'}; label_freq = zeros(length(labels), 1); for i = 1:k label_idx = find(strcmp(labels, train_files(nearest_k(i)).name(1:end-6))); label_freq(label_idx) = label_freq(label_idx) + 1; end [~, max_idx] = max(label_freq); fprintf('Test image is recognized as %s.\n', labels{max_idx}); ``` 其中,`extract_feature()`函数用于提取图像的特征向量,可以根据具体的人脸识别算法进行实现。在这个简单的示例中,我们假设每个人脸图像都是大小相同的灰度图像,直接将图像展开为一个向量作为特征向量。在实际应用中,可能需要考虑更复杂的特征提取方法,如LBP、HOG等。 需要注意的是,这个示例只是一个简单的人脸识别程序,实际应用中还需要考虑很多问题,如人脸检测、人脸对齐、特征选择和分类器的选择等。同时,由于人脸识别涉及到个人隐私,需要考虑相关法律法规和道德伦理问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值