標題:
去年做的基于Qt的人臉識別系統(tǒng),這是在Qt客戶端上運行的完整代碼
[打印本頁]
作者:
54166
時間:
2020-3-29 21:15
標題:
去年做的基于Qt的人臉識別系統(tǒng),這是在Qt客戶端上運行的完整代碼
#include "facedetectwnd.h"
#include "ui_facedetectwnd.h"
#include <QByteArray>
#include <QHostAddress>
#include "FaceDetect.h"
FaceDetectThr::FaceDetectThr(QObject *parent):
QThread (parent)
{
}
FaceDetectThr::~FaceDetectThr()
{
}
void FaceDetectThr::run()
{
#define MAXLEN int(800*600)
int size;
//分配緩存:用于保存接收圖片數(shù)據(jù)
char *buffer = new char[MAXLEN];
//分配套接字
QTcpSocket *s = new QTcpSocket;
// 連接服務器
s->connectToHost(QHostAddress("192.168.21.131"), 59999);
//等連接成功
if(!s->waitForConnected(~0)){
goto ERR_STEP;
}
//給界面發(fā)生連接成功信號
emit sigConnected();
//死循環(huán)
while(1){
char req[]= "clientack";
//給服務器發(fā)送請求
s->write(req, sizeof(req));
//等待套接字緩存可讀(給服務器發(fā)送請求后,服務器收到則采樣一張圖片,回發(fā)客戶端)
if(s->waitForReadyRead(~0)){
//讀出4字節(jié)協(xié)議頭:圖片正文的長度
s->read((char *)&size, 4);
int len = size;
char *p1 = (char *)&len;
char *p2 = (char *)&size;
p1[0] = p2[3];
p1[1] = p2[2];
p1[2] = p2[1];
p1[3] = p2[0];
if(MAXLEN < len){
goto ERR_STEP;
}
//循環(huán)接收len字節(jié)數(shù)據(jù)(不多收也不少收)
p1 = buffer;
int pos = len;
while(pos){
if(!s->waitForReadyRead(~0)){
goto ERR_STEP;
}
size = int(s->read(p1, pos));
pos -= size;
p1 += size;
}
qDebug("len = %d, pos=%d\n", len, pos);
//把接收來的圖片數(shù)據(jù)裝到字節(jié)數(shù)組
QByteArray arr;
arr.append(buffer, len);
//定義管理圖片的QImage對象
QImage img;
//把字節(jié)數(shù)組中圖片用img對象管理起來
img.loadFromData(arr);
//把QImage轉(zhuǎn)換成Mat格式
cv::Mat frame = ::QImage_to_Mat(img);
//人臉檢測
::detectFaceOpenCV(frame);
//把Mat轉(zhuǎn)換成QImage
img = ::Mat_to_QImage(frame);
//把QImage轉(zhuǎn)換QPixmap
QPixmap pix = QPixmap::fromImage(img);
//給界面發(fā)送信號
emit sigPixmap(pix);
}
}
ERR_STEP:
qDebug("線程出錯退出");
delete [] buffer;
delete s;
emit sigDisconnected();
return;
}
FaceDetectWnd::FaceDetectWnd(QWidget *parent) :
QWidget(parent),
ui(new Ui::FaceDetectWnd)
{
ui->setupUi(this);
//分配一個接收線程對象
detectThr = new FaceDetectThr;
connect(detectThr, SIGNAL(sigPixmap(QPixmap)),
this, SLOT(slotRecv(QPixmap)));
connect(detectThr, SIGNAL(sigConnected()),
this, SLOT(slotConnected()));
connect(detectThr, SIGNAL(sigDisconnected()),
this, SLOT(slotDisconnected()));
setWindowTitle("智能門崗");
}
FaceDetectWnd::~FaceDetectWnd()
{
delete ui;
}
void FaceDetectWnd::slotConnected()
{
setWindowTitle("連接成功");
ui->pushButton->setEnabled(true);
}
void FaceDetectWnd::slotDisconnected()
{
setWindowTitle("連接斷開");
ui->pushButton->setText("連接");
ui->pushButton->setEnabled(true);
}
void FaceDetectWnd::slotRecv(QPixmap pix)
{
ui->label->setPixmap(pix);
}
void FaceDetectWnd::on_pushButton_clicked()
{
if("連接" == ui->pushButton->text()){
ui->pushButton->setText("斷開");
detectThr->start();
setWindowTitle("連接中...");
ui->pushButton->setEnabled(false);
}else{
ui->pushButton->setText("連接");
detectThr->terminate();
}
}
復制代碼
歡迎光臨 (http://www.torrancerestoration.com/bbs/)
Powered by Discuz! X3.1