.pro
#-------------------------------------------------
#
# Project created by QtCreator 2023-06-16T11:40:21
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = day5_camera05
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
INCLUDEPATH += C:/opencv/opencv3.4-qt-intall/install/include
INCLUDEPATH += C:/opencv/opencv3.4-qt-intall/install/include/opencv
INCLUDEPATH += C:/opencv/opencv3.4-qt-intall/install/include/opencv2
LIBS += C:/opencv/opencv3.4-qt-intall/install/x86/mingw/lib/libopencv_*.a
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
#include<opencv2/face.hpp>
#include <vector>
#include <map>
#include <QMessageBox>
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include <QTimerEvent>
#include<QtSerialPort/QtSerialPort>
#include<QtSerialPort/QSerialPortInfo>
using namespace cv;
using namespace cv::face;
using namespace std;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void timerEvent(QTimerEvent *e); //重写定时器事件处理函数
private slots:
void on_open_btn_clicked();
void on_close_btn_clicked();
private:
Ui::MainWindow *ui;
//定义有关处理摄像头的相关变量
VideoCapture v; //视频流对象
Mat src,gray,dst; //容器:彩色 灰色 均衡化
Mat rgb; //bgr-->rgb 转变
CascadeClassifier c; //级联分类器
vector<Rect> faces; //人脸矩形框
int cameraTimerId; //显示摄像头的定时器id
};
#endif // MAINWINDOW_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//打开摄像头
if(v.open(0))
{
QMessageBox::information(this,"success","摄像头打开成功");
}
//下载级联分类器模型
c.load("C:/opencv/picture/face.xml");
}
MainWindow::~MainWindow()
{
delete ui;
}
//打开摄像头按钮对应的槽函数
void MainWindow::on_open_btn_clicked()
{
cameraTimerId = this->startTimer(20); //启动定时器 每隔20毫秒启动定时器处理事件函数
}
//关闭摄像头按钮对应的槽函数
void MainWindow::on_close_btn_clicked()
{
this->killTimer(cameraTimerId);
}
//定时器事件处理函数
void MainWindow::timerEvent(QTimerEvent *e)
{
//判断哪个定时器到位
if(e->timerId() == cameraTimerId)
{
//从视频流中获取一张图像
v.read(src);
//翻转图像
flip(src,src,1);
//灰度处理
cvtColor(src,gray,CV_BGR2GRAY);
//均衡化处理
equalizeHist(gray,dst);
//获取人脸矩形框
c.detectMultiScale(dst,faces);
//将人脸绘制到原图上
for(int i = 0;i < faces.size();i++)
{
rectangle(src,faces[i],Scalar(255,0,0));
}
//将src转换成rgb图像
cvtColor(src,rgb,CV_BGR2RGB);
//将rgb图重新设置尺寸
cv::resize(rgb,rgb,Size(300,300));
//使用rgb图构造出一个QImage图像用于展示到qt的ui界面
QImage image(rgb.data,rgb.cols,rgb.rows,rgb.cols*rgb.channels(),QImage::Format_RGB888);
//将该图像展示到ui界面上的lab中
ui->camera_lable->setPixmap(QPixmap::fromImage(image));
}
}
result