- #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;
- //分配缓存:用于保存接收图片数据
- char *buffer = new char[MAXLEN];
- //分配套接字
- QTcpSocket *s = new QTcpSocket;
- // 连接服务器
- s->connectToHost(QHostAddress("192.168.21.131"), 59999);
- //等连接成功
- if(!s->waitForConnected(~0)){
- goto ERR_STEP;
- }
- //给界面发生连接成功信号
- emit sigConnected();
- //死循环
- while(1){
- char req[]= "clientack";
- //给服务器发送请求
- s->write(req, sizeof(req));
- //等待套接字缓存可读(给服务器发送请求后,服务器收到则采样一张图片,回发客户端)
- if(s->waitForReadyRead(~0)){
- //读出4字节协议头:图片正文的长度
- 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;
- }
- //循环接收len字节数据(不多收也不少收)
- 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);
- //把接收来的图片数据装到字节数组
- QByteArray arr;
- arr.append(buffer, len);
- //定义管理图片的QImage对象
- QImage img;
- //把字节数组中图片用img对象管理起来
- img.loadFromData(arr);
- //把QImage转换成Mat格式
- cv::Mat frame = ::QImage_to_Mat(img);
- //人脸检测
- ::detectFaceOpenCV(frame);
- //把Mat转换成QImage
- img = ::Mat_to_QImage(frame);
- //把QImage转换QPixmap
- QPixmap pix = QPixmap::fromImage(img);
- //给界面发送信号
- 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();
- }
- }
复制代码
|