基于matlab的自动人脸识别系统GUI设计

基于matlab的自动人脸识别系统GUI设计

   之前做的一个课设项目半成品,一边网上找资料一边自己瞎捣鼓,完成了GUI界面的设计,实时视频中的人脸检测和追踪,PCA算法训练,单张人脸识别。
   但是识别率比较低,多人人脸识别和识别准确率统计这些部分还没有完成,等之后有空闲时再进行完善,然后将整个项目的具体过程给大家分享。
   下面是代码(省事,整个代码贴上来了,需要的话自己再处理一下吧,也欢迎各位大佬指点一下小白)。
   PCA算法部分参考了GitHub开源项目-face_recognize-master
   人脸检测部分参考了https://www.ilovematlab.cn/thread-201626-8-1.html
function varargout = charutupian(varargin)
% CHARUTUPIAN MATLAB code for charutupian.fig
%      CHARUTUPIAN, by itself, creates a new CHARUTUPIAN or raises the existing
%      singleton*.
%
%      H = CHARUTUPIAN returns the handle to a new CHARUTUPIAN or the handle to
%      the existing singleton*.
%
%      CHARUTUPIAN('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in CHARUTUPIAN.M with the given input arguments.
%
%      CHARUTUPIAN('Property','Value',...) creates a new CHARUTUPIAN or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before charutupian_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to charutupian_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help charutupian

% Last Modified by GUIDE v2.5 23-Jun-2020 22:26:13

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @charutupian_OpeningFcn, ...
                   'gui_OutputFcn',  @charutupian_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before charutupian is made visible.
function charutupian_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to charutupian (see VARARGIN)

% Choose default command line output for charutupian
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes charutupian wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = charutupian_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargout{1} = handles.output;

 




% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%拍照
 % Create a cascade detector object.
 global vidDevice
 global im
 im = step(vidDevice);
 axes(handles.axes2);
 imshow(im);
 



% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global vidDevice
vidDevice = imaq.VideoDevice('winvideo',1,'MJPG_1280x720') ;
hVideoIn = vision.VideoPlayer;
hVideoIn.Name  = 'Input Video';
hVideoOut = vision.VideoPlayer;
hVideoOut.Name  = 'Output Video';
faceDetector = vision.CascadeObjectDetector();
pointTracker = vision.PointTracker('MaxBidirectionalError', 2);
numPts = 0;
n = 0;
while(n<200)
    videoFrame = step(vidDevice);
    videoFrameOutput = videoFrame;
    videoFrameGray = rgb2gray(videoFrame);
    if numPts < 10
        % Detection mode.
        bbox = faceDetector.step(videoFrameGray);
        if ~isempty(bbox)
            % Find corner points inside the detected region.
            points = detectMinEigenFeatures(videoFrameGray, 'ROI', bbox(1, :));
            % Re-initialize the point tracker.
            xyPoints = points.Location;
            numPts = size(xyPoints,1);
            release(pointTracker);
            initialize(pointTracker, xyPoints, videoFrameGray);
            % Save a copy of the points.
            oldPoints = xyPoints;
            % Convert the rectangle represented as [x, y, w, h] into an
            % M-by-2 matrix of [x,y] coordinates of the four corners. This
            % is needed to be able to transform the bounding box to display
            % the orientation of the face.
            bboxPoints = bbox2points(bbox(1, :));
            % Convert the box corners into the [x1 y1 x2 y2 x3 y3 x4 y4]
            % format required by insertShape.
            bboxPolygon = reshape(bboxPoints', 1, []);
            % Display a bounding box around the detected face.
            videoFrameOutput = insertShape(videoFrameOutput, 'Polygon', bboxPolygon, 'LineWidth', 3);
            % Display detected corners.
            videoFrameOutput = insertMarker(videoFrameOutput, xyPoints, '+', 'Color', 'white');
        end
    else
        % Tracking mode.
        [xyPoints, isFound] = step(pointTracker, videoFrameGray);
        visiblePoints = xyPoints(isFound, :);
        oldInliers = oldPoints(isFound, :);
        numPts = size(visiblePoints, 1);
        if numPts >= 10
            % Estimate the geometric transformation between the old points
            % and the new points.
            [xform, oldInliers, visiblePoints] = estimateGeometricTransform(...
                oldInliers, visiblePoints, 'similarity', 'MaxDistance', 4);
            % Apply the transformation to the bounding box.
            bboxPoints = transformPointsForward(xform, bboxPoints);
            % Convert the box corners into the [x1 y1 x2 y2 x3 y3 x4 y4]
            % format required by insertShape.
            bboxPolygon = reshape(bboxPoints', 1, []);
            % Display a bounding box around the face being tracked.
            videoFrameOutput = insertShape(videoFrameOutput, 'Polygon', bboxPolygon, 'LineWidth', 3);
            % Display tracked points.
                videoFrameOutput = insertMarker(videoFrameOutput, visiblePoints, '+', 'Color', 'white');
            % Reset the points.
            oldPoints = visiblePoints;
            setPoints(pointTracker, oldPoints);
        end
    end
   
    % Display video.
    step(hVideoIn, videoFrame);
    step(hVideoOut, videoFrameOutput);
    n = n+1;
end
release(vidDevice);
release(hVideoOut);
release(hVideoIn);

  
    





 



% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global im                   %待识别图片
global reference            
global W                    
global imgmean              %行均值向量
global col_of_data          %列数
global pathname
global img_path_list

% 预处理新数据
im = double(im(:));
objectone = W'*(im - imgmean);
distance = 100000000;

% 最小距离法,寻找和待识别图片最为接近的训练图片
for k = 1:col_of_data     %遍历每张图片
    temp = norm(objectone - reference(:,k));  %
    if(distance>temp)
        aimone = k;
        distance = temp;
        aimpath = strcat(pathname, '/', img_path_list(aimone).name);
        axes( handles.axes3 )
        imshow(aimpath)
        disp('识别成功')
    else
        disp('识别不成功')
    end
end
disp('完成')





% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%训练机器
global reference
global W
global imgmean
global col_of_data
global pathname
global img_path_list

% 批量读取指定文件夹下的图片
pathname = uigetdir;
img_path_list = dir(strcat(pathname,'\*.jpg'));
img_num = length(img_path_list);
imagedata = [];
if img_num >0
    for j = 1:img_num
        img_name = img_path_list(j).name;
        temp = imread(strcat(pathname, '/', img_name));   %读取照片
        temp = double(temp(:));
        imagedata = [imagedata, temp];
    end
end
col_of_data = size(imagedata,2);   %返回列数

% 中心化 & 计算协方差矩阵
imgmean = mean(imagedata,2);             %返回行均值向量
for i = 1:col_of_data
    imagedata(:,i) = imagedata(:,i) - imgmean;
end
covMat = imagedata'*imagedata;
[COEFF, latent, explained] = pcacov(covMat);

% 选择构成95%能量的特征值
i = 1;
proportion = 0;
while(proportion < 95)
    proportion = proportion + explained(i);
    i = i+1;
end
p = i - 1;   

% 特征脸
W = imagedata*COEFF;    % N*M阶
W = W(:,1:p);           % N*p阶,选出最大的P个构成变换矩阵(1280X720)*P

% 训练样本在新座标基下的表达矩阵 p*M
reference = W'*imagedata;
p
img_path_list
disp('训练好了')



% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global W
global reference
col_of_data = 60;

pathname = uigetdir;
img_path_list = dir(strcat(pathname,'\*.bmp'));
img_num = length(img_path_list);
testdata = [];
if img_num >0
    for j = 1:img_num
        img_name = img_path_list(j).name;
        temp = imread(strcat(pathname, '/', img_name));
        temp = double(temp(:));
        testdata = [testdata, temp];
    end
end
col_of_test = size(testdata,2);
testdata = center( testdata );
object = W'* testdata;

% 最小距离法,寻找和待识别图片最为接近的训练图片
% 计算分类器准确率
num = 0;
for j = 1:col_of_test;
    distance = 1000000000000;
    for k = 1:col_of_data;
        temp = norm(object(:,j) - reference(:,k));
        if(distance>temp)
            aimone = k;
            distance = temp;
        end
    end
    if ceil(j/3)==ceil(aimone/4)
       num = num + 1;
    end
end
accuracy = num/col_of_test;
msgbox(['分类器准确率:                   ',num2str(accuracy)],'accuracy')


% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global im;
[filename, pathname] = uigetfile({'*.jpg'},'choose photo');
p = [pathname, filename];
im = imread(p);
axes( handles.axes2);
imshow(im);



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
  • 7
    点赞
  • 84
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值