I'd like to add some multithreading to my application (opencv-opengl integration), and I'm starting from the structure found in this answer. For now there is a thread that grab the video frame and send it to the MainWindow, nothing more.
I have tried to search a little bit but nothing makes it clear but only make things more obscure.
Even if I read an article that says not to subclass QThread
but use moveToThread()
I read another article somewhere (other then one of the official example) that say to do it.
If I run the application and then close it crashes.
If I run the application and I call the endCapture
and then start again.. it crashes again.
Every kind of help or comment is appreciated!
Here is the VideoThread.h:
#ifndef VIDEOTHREAD_H
#define VIDEOTHREAD_H
#include <QMutex>
#include <QImage>
#include <QThread>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
class VideoThread : public QThread
{
Q_OBJECT
public:
explicit VideoThread(QObject *parent = 0);
~VideoThread();
protected:
void run();
private:
cv::VideoCapture video;
QMutex m_AbortCaptureLock;
bool m_AbortCapture;
signals:
void sendImage(QImage);
public slots:
void endCapture();
};
#endif // VIDEOTHREAD_H
VideoThread.cpp:
#include "videothread.h"
#include <QDebug>
VideoThread::VideoThread(QObject *parent) :
QThread(parent)
{
qDebug() << "VideoThread > ctor.";
}
VideoThread::~VideoThread()
{
qDebug() << "VideoThread > dtor";
if(video.isOpened()) {
video.release();
qDebug() << "Camera successfully disconnected.";
}
}
void VideoThread::run()
{
m_AbortCapture = false;
video = cv::VideoCapture(0);
qDebug() << "VideoThread::run..";
while(true)
{
m_AbortCaptureLock.lock();
if (m_AbortCapture) {
qDebug() << "VideoThread::run > abort capture..";
break;
}
m_AbortCaptureLock.unlock();
cv::Mat cvFrame;
video >> cvFrame;
if(cvFrame.empty()) continue;
// convert the Mat to a QImage
QImage qtFrame(cvFrame.data, cvFrame.size().width, cvFrame.size().height, cvFrame.step, QImage::Format_RGB888);
qtFrame = qtFrame.rgbSwapped();
// queue the image to the gui
emit sendImage(qtFrame);
msleep(20);
}
}
void VideoThread::endCapture()
{
qDebug() << "VideoThread::endCapture()";
m_AbortCaptureLock.lock();
m_AbortCapture = true;
m_AbortCaptureLock.unlock();
}
And here the main:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "opencv_glwidget.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
OpenCV_GLWidget *w = new OpenCV_GLWidget();
w->setParent(this->centralWidget());
connect(ui->checkBox, SIGNAL(toggled(bool)),
this, SLOT(toggle(bool)));
ui->checkBox->toggle();
connect(&thread, SIGNAL(sendImage(QImage)),
w, SLOT(renderImage(QImage)));
thread.start();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::toggle(bool n)
{
if(n) {
thread.start();
} else {
thread.endCapture();
}
}