Matlab使用卷积神经网络(CNN),进行人脸表情情绪识别GUI界面。
工作如下:
1、加载数据集。选用JAFFE数据集,含有7类表情,共213张人脸图像。
工作如下:
1、加载数据集。选用JAFFE数据集,含有7类表情,共213张人脸图像。
2、构建CNN网络、options。
3、80%作为训练集、20%作为测试集,进行训练测试。
4、封装成GUI。可显示整个测试集的结果,以及点击识别某一张图像。
注:需要Matlab2020及以上版本。main.m是源代码,用来搭建和训练网络,注释详细;
page.fig和page.m是GUI界面;;附word运行说明文档;准确率高是本数据集本身导致,也可有偿帮忙替换数据集。
项目名称
基于卷积神经网络(CNN)的人脸表情情绪识别GUI界面
项目概述
本项目旨在使用Matlab构建一个卷积神经网络(CNN),对JAFFE数据集中的人脸表情进行情绪识别,并将整个过程封装成一个用户友好的图形用户界面(GUI)。项目涵盖了从数据加载、模型构建、训练测试到GUI封装的完整流程。通过这个项目,用户可以直观地查看整个测试集的结果,并且可以通过点击来识别单张人脸图像的情绪。
项目特点
- 高精度:使用CNN进行人脸表情识别,具有较高的识别率。
- 用户友好:提供GUI界面,方便用户操作和查看结果。
- 详细注释:代码中包含详细的注释,便于理解和修改。
- 易于上手:适合初学者快速入门CNN和Matlab GUI开发。
- 可扩展性:可以轻松替换数据集或调整网络结构以适应不同的需求。
项目结构
Face_Expression_Recognition_GUI/
├── data/ # 数据文件夹
│ ├── JAFFE/ # JAFFE数据集
│ ├── angry/ # 生气表情
│ ├── happy/ # 高兴表情
│ ├── ...
├── src/ # 源代码文件夹
│ ├── main.m # 主程序,用于搭建和训练网络
│ ├── page.fig # GUI界面设计文件
│ ├── page.m # GUI界面实现文件
├── utils/ # 工具函数
│ ├── load_data.m # 数据加载工具
│ ├── plot_results.m # 结果绘制工具
├── README.md # 项目说明文档
└── requirements.txt # 依赖库文件
项目内容
-
数据处理
- 加载JAFFE数据集,该数据集包含7类表情(生气、高兴、惊讶、悲伤、恐惧、厌恶、中性),共213张人脸图像。
- 将数据集划分为训练集(80%)和测试集(20%)。
-
模型构建
- 定义卷积神经网络(CNN)架构,包括卷积层、池化层、全连接层等。
- 设置训练参数,如学习率、批次大小、训练轮数等。
-
训练与测试
- 使用训练集数据训练CNN模型。
- 在测试集上评估模型性能,计算准确率并显示混淆矩阵。
-
GUI封装
- 设计并实现GUI界面,允许用户查看整个测试集的结果。
- 提供功能按钮,允许用户选择并识别单张人脸图像的情绪。
代码示例
1. 主程序 src/main.m
% 主程序 main.m
% 使用CNN进行人脸表情情绪识别
% 需要Matlab 2020及以上版本
% 1. 加载数据
data_dir = 'data/JAFFE';
X, y, classNames = load_data(data_dir);
% 2. 划分训练集和测试集
cv = cvpartition(y, 'HoldOut', 0.2);
idx = cv.test;
X_train = X(~idx, :);
y_train = categorical(y(~idx));
X_test = X(idx, :);
y_test = categorical(y(idx));
% 3. 构建CNN网络
layers = [
imageInputLayer([size(X, 1), size(X, 2), 1])
convolution2dLayer(5, 32, 'Padding', 'same')
batchNormalizationLayer
reluLayer
maxPooling2dLayer(2, 'Stride', 2)
convolution2dLayer(5, 64, 'Padding', 'same')
batchNormalizationLayer
reluLayer
maxPooling2dLayer(2, 'Stride', 2)
fullyConnectedLayer(numel(classNames))
softmaxLayer
classificationLayer
];
% 4. 构建options
options = trainingOptions('adam', ...
'MaxEpochs', 20, ...
'MiniBatchSize', 32, ...
'Plots', 'training-progress', ...
'Verbose', false, ...
'Shuffle', 'every-epoch');
% 5. 训练
net = trainNetwork(X_train, y_train, layers, options);
% 6. 测试
Y_pred = classify(net, X_test);
accuracy = sum(Y_pred == y_test) / numel(y_test);
fprintf('Accuracy: %.2f%%\n', accuracy * 100);
% 保存模型
save('trained_net.mat', 'net');
2. 数据加载工具 utils/load_data.m
function [X, y, classNames] = load_data(data_dir)
% 加载JAFFE数据集
classNames = {'angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral'};
numClasses = numel(classNames);
imageSize = 256; % 图像尺寸
X = [];
y = [];
for i = 1:numClasses
classDir = fullfile(data_dir, classNames{i});
files = dir(fullfile(classDir, '*.tiff'));
for j = 1:numel(files)
img = imread(fullfile(classDir, files(j).name));
img = imresize(img, [imageSize, imageSize]);
img = rgb2gray(img); % 转为灰度图像
X = cat(4, X, img);
y = [y, i];
end
end
% 转换为四维数组
X = permute(X, [2, 1, 3, 4]);
X = double(X) / 255; % 归一化
y = categorical(y);
end
3. GUI界面实现 src/page.m
function varargout = page(varargin)
% PAGE MATLAB code for page.fig
% PAGE, by itself, creates a new PAGE or raises the existing
% singleton*.
%
% H = PAGE returns the handle to a new PAGE or the handle to
% the existing singleton*.
%
% PAGE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in PAGE.M with the given input arguments.
%
% PAGE('Property','Value',...) creates a new PAGE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before page_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to page_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% Edit the above text to modify the response to help page
% Last Modified by GUIDE v2.5 10-Oct-2024 09:00:00
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @page_OpeningFcn, ...
'gui_OutputFcn', @page_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 page is made visible.
function page_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 page (see VARARGIN)
% Choose default command line output for page
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% Load the trained network
load('trained_net.mat', 'net');
handles.net = net;
guidata(hObject, handles);
% Load test images
data_dir = 'data/JAFFE';
[X, y, classNames] = load_data(data_dir);
cv = cvpartition(y, 'HoldOut', 0.2);
idx = cv.test;
X_test = X(:, :, :, idx);
y_test = y(idx);
handles.X_test = X_test;
handles.y_test = y_test;
handles.classNames = classNames;
guidata(hObject, handles);
% Display the first image in the test set
imshow(handles.X_test(:, :, :, 1));
title(handles.classNames{double(handles.y_test(1))});
% --- Outputs from this function are returned to the command line.
function varargout = page_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;
% --- Button to show next image
function btnNextImage_Callback(hObject, eventdata, handles)
% hObject handle to btnNextImage (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get the current index
currentIdx = getappdata(hObject, 'CurrentIndex');
if isempty(currentIdx)
currentIdx = 1;
end
% Update the index
currentIdx = mod(currentIdx, size(handles.X_test, 4)) + 1;
setappdata(hObject, 'CurrentIndex', currentIdx);
% Display the next image
imshow(handles.X_test(:, :, :, currentIdx));
title(handles.classNames{double(handles.y_test(currentIdx))});
% Predict the emotion
img = handles.X_test(:, :, :, currentIdx);
img = img(:,:,:,1); % Ensure it is a single image
img = img(:,:,:,1); % Convert to 3D
predictedClass = classify(handles.net, img);
disp(['Predicted Emotion: ', char(predictedClass)]);
% Update the title
title(sprintf('%s (Predicted: %s)', handles.classNames{double(handles.y_test(currentIdx))}, char(predictedClass)));
% --- Button to predict a specific image
function btnPredictImage_Callback(hObject, eventdata, handles)
% hObject handle to btnPredictImage (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Open a file dialog to select an image
[filename, pathname] = uigetfile({'*.tiff';'*.jpg';'*.png'}, 'Select an Image');
if isequal(filename, 0)
return;
end
% Read and preprocess the selected image
img = imread(fullfile(pathname, filename));
img = imresize(img, [256, 256]);
img = rgb2gray(img);
img = double(img) / 255;
% Predict the emotion
predictedClass = classify(handles.net, img);
disp(['Predicted Emotion: ', char(predictedClass)]);
% Display the image and predicted emotion
imshow(img);
title(char(predictedClass));
使用说明
-
环境准备:
- 确保安装了Matlab 2020及以上版本。
- 下载JAFFE数据集并解压到
data/JAFFE/
目录下。
-
运行主程序:
- 在Matlab环境中运行
src/main.m
脚本,训练CNN模型并保存模型文件trained_net.mat
。
- 在Matlab环境中运行
-
启动GUI界面:
- 运行
src/page.m
脚本,启动GUI界面。 - GUI界面上会显示第一张测试集图像及其真实标签。
- 点击“Next Image”按钮查看下一张图像及其预测结果。
- 点击“Predict Image”按钮选择并识别单张图像的情绪。
- 运行
注意事项
- 数据格式:确保JAFFE数据集中的图像格式正确,并且每张图像的尺寸一致。
- 硬件要求:建议使用GPU进行训练和推理,以加快处理速度。如果没有足够的计算资源,可以考虑使用云服务提供商的GPU实例。
- 超参数调整:根据实际情况调整网络层数、卷积核大小、学习率等超参数,以获得更好的性能。
通过上述步骤,你可以轻松地使用Matlab和CNN进行人脸表情情绪识别,并通过GUI界面直观地查看和操作结果。