一、在完成OpenCV+多线程视频采集(一)后,我们可以改用moveToThread函数来实现多线程,不需要从OThread继承它,创建一个新类VidoProcessor;
1、vidoprocessor.h
#ifndef VIDOPROCESSOR_H
#define VIDOPROCESSOR_H
#include <QObject>
#include <opencv2/opencv.hpp>
#include <QPixmap>
#include <QImage>
using namespace std;
using namespace cv;
class VidoProcessor : public QObject
{
Q_OBJECT
public:
explicit VidoProcessor(QObject *parent = nullptr);
signals:
void inDisplay1(QPixmap pixmap);
void outDisplay1(QPixmap pixmap);
public slots:
void startVideo();
void stopVideo();
private:
bool stopped;
};
#endif // VIDOPROCESSOR_H
2、vidoprocessor.cpp
#include "vidoprocessor.h"
#include <QDebug>
VidoProcessor::VidoProcessor(QObject *parent) : QObject(parent)
{
stopped=false;
void VidoProcessor::startVideo()
{
VideoCapture camera(0);
Mat inFrame, outFrame;
while (camera.isOpened() && !stopped) {
camera >> inFrame;
if(inFrame.empty())
continue;
bitwise_not(inFrame,outFrame);
emit inDisplay1(
QPixmap::fromImage(
QImage(inFrame.data,
inFrame.cols,
inFrame.rows,
static_cast<int>(inFrame.step),
QImage::Format_RGB888).rgbSwapped()));
emit outDisplay1(
QPixmap::fromImage(
QImage(outFrame.data,
outFrame.cols,
outFrame.rows,
static_cast<int>(outFrame.step),
QImage::Format_RGB888).rgbSwapped()));
}
}
void VidoProcessor::stopVideo()
{
stopped = true;
}
二、现在,可以MainWindow类中使用它,然后将以下内容添加到MainWindow的私有成员部分:
// VideoProcessorThread processor;
VidoProcessor *processor;
三、在MainWindow构造函数中:
processor = new VidoProcessor();
processor->moveToThread(new QThread(this));
connect(processor->thread(),SIGNAL(started()),processor,SLOT(startVideo()));
connect(processor->thread(),SIGNAL(finished()),processor,SLOT(deleteLater()));
processor->thread()->start();
四、在MainWindow析构函数中:
processor->stopVideo();
processor->thread()->quit();
processor->thread()->wait();
delete ui;