1.引言
这是本项目的第五篇文章,主要介绍相关的代码。
第一篇文章,主要介绍项目的任务和实验环境,点击阅读
第二篇文章,主要介绍opencv和相关模型,点击阅读。
第三篇文章,主要介绍人脸检测haar+adaboost的原理,点击阅读。
第四篇文章,主要介绍PCA降维和人脸识别的原理,点击阅读。
2.环境
本文的代码主要的IDE是qtcreator,主要语言是C++。
因为把代码全部贴出来极不方便阅读,篇幅也会过于冗长,我把源码放在github上,感觉有用的请star一下。
链接:https://github.com/LastDance500/face-recognization
3.代码部分
pro部分
.pro文件是对整个工程的配置,例如工程里包含哪些文件,路径是什么;以来哪些库,路径是什么,使用了Qt的哪些组件,等等。
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TEMPLATE = app //建立一个应用程序的makefile 这是默认值,所以如果模板没有被指定,这个将被使用
//配置信息
CONFIG += console c++11
CONFIG += app_bundle
CONFIG += qt
CONFIG += QApplication
DEFINES += QT_DEPRECATED_WARNINGS
//头文件
HEADERS += \
mainwindow.h \
detect.h \
functions.h \
recognize2.h \
facein.h \
dialog.h
//源文件
SOURCES += main.cpp \
mainwindow.cpp \
functions.cpp \
detect.cpp \
recognize2.cpp \
facein.cpp \
dialog.cpp
//工程中包含的资源文件
#RESOURCES += \
# img.qrc \
# img.qrc \
# resource.qrc
//窗口ui设计文件
FORMS += \
mainwindow.ui \
detect.ui \
recognize2.ui \
facein.ui \
dialog.ui
//制定生成的应用程序名
TARGET = interface
INCLUDEPATH += /usr/local/include\
/usr/local/include/opencv4\
/usr/local/include/opencv4/opencv2/
LIBS += /usr/local/lib/lib*
人脸检测代码
在这一部分,我把头文件的引用写出来,后面的为了简短一点,头文件的引用就不写出来了。在这里我使用了dnn模型,并未使用之前介绍的haar+adaboost训练的模型,如果你要使用的话,可以直接在opencv的haarcascade文件夹里找到相应的模型进行替换。
#include "detect.h"
#include <QMainWindow>
#include <QWidget>
#include <QPushButton>
#include "ui_detect.h"
#include <QFileDialog>
#include <QDebug>
#include <QLabel>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2/dnn/dnn.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/face.hpp>
#include <opencv2/face/facerec.hpp>
#include <opencv2/imgproc/types_c.h>
#include <iostream>
#include <stdio.h>
#include <ctime>
#include <stdio.h>
#include <string>
#include <vector>
#include <math.h>
using namespace std;
using namespace cv;
using namespace dnn;
detect::detect(QWidget *parent) : QWidget(parent)
{
//人脸检测界面
this->setWindowTitle("人脸检测");
this->resize(600,400);
//回退button
QPushButton *back_button = new QPushButton("back",this);
connect(back_button,&QPushButton::clicked,this,&detect::emit_detectsignal);
back_button->show();
back_button ->resize(40,20);
back_button ->move(10,10);
//开始播放button
QPushButton *play_button = new QPushButton("play",this);
connect(play_button,&QPushButton::clicked,this,&detect::facedetect);
play_button->show();
play_button ->resize(40,20);
play_button ->move(100,100);
}
QImage detect::Mat2QImage(const cv::Mat &mat)
{
QImage img;
Mat rgb;
if(mat.channels()==3)
{
//cvt Mat BGR 2 QImage RGB
cvtColor(mat,rgb,CV_BGR2RGB);
img =QImage((const unsigned char*)(rgb.data),
rgb.cols,rgb.rows,
rgb.cols*rgb.channels(),
QImage::Format_RGB888);
}
else
{
img =QImage((const unsigned char*)(mat.data),
mat.cols,mat.rows,
mat.cols*mat.channels(),
QImage::Format_RGB888);
}
return img;
}
void detect::facedetect()
{
//摄像头播放
string modelConfiguration ="/home/tbs/test/opencv_project/deploy.prototxt";