【发布时间】:2021-04-25 15:32:53
【问题描述】:
我正在尝试在线程内使用 OpenCV 库处理一些图像,因为处理操作需要一些时间才能完成。
所以问题是 QThread 总是返回一个 Null QImage 到 QMainWindow 中的 Slot。
我得到这个异常错误:
Exception thrown at 0x00007FFE01962F6D (Qt5Guid.dll) in QtWidgetsApplication1.exe: 0xC0000005: Access violation reading location 0x0000022CAB6EE080.
此文件出现错误:
qtwidgetsapplication1.cpp此文件用于QMainWindow
#include "qtwidgetsapplication1.h"
#include "stdafx.h"
QtWidgetsApplication1::QtWidgetsApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
connect(ui.addItem_btn, SIGNAL(clicked()), this, SLOT(addItem_btn_OnClick())); // Add Item to the List
dftThread = new DetectFaceThread(this);
connect(dftThread, &DetectFaceThread::detectedFace, this, &QtWidgetsApplication1::onDetectedFace);
connect(dftThread, &DetectFaceThread::finished, dftThread, &QObject::deleteLater);
}
QtWidgetsApplication1::~QtWidgetsApplication1()
{
}
void QtWidgetsApplication1::addItem_btn_OnClick()
{
dftThread->start();
}
void QtWidgetsApplication1::onDetectedFace(const QImage& face)
{
if (face.isNull())
{
QMessageBox::warning(this, QString("Detection Error"), QString("Face not detected!"));
return;
}
ui.imgDisplay_label->setPixmap(QPixmap::fromImage(face));
}
这是我的代码:
DetectFaceThread.h
#pragma once
#include <qthread.h>
#include <QtWidgets/qmessagebox.h>
#include <qmutex.h>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
class DetectFaceThread :
public QThread
{
Q_OBJECT
public:
DetectFaceThread(QWidget* parent = nullptr);
~DetectFaceThread();
void run() override;
signals:
void detectedFace(const QImage &face);
};
DetectFaceThread.cpp
#include "DetectFaceThread.h"
DetectFaceThread::DetectFaceThread(QWidget* parent)
{
}
DetectFaceThread::~DetectFaceThread()
{
QMessageBox::information(nullptr, QString("Thread Info"), QString("Thread successfully destroyed"));
}
void DetectFaceThread::run()
{
QMutex mutex;
mutex.lock();
std::string img_path = "res/paper.jpg";
cv::Mat img = cv::imread(img_path);
if (img.empty())
{
QMessageBox::warning(nullptr, QString("Load Error"), QString("Image not found!"));
return;
}
cv::cvtColor(img, img, cv::ColorConversionCodes::COLOR_BGR2RGB);
float w = 800, h = 1000;
cv::Point2f src[4] = { {383, 445}, {885, 521}, {89, 1125}, {921, 1270} };
cv::Point2f dst[4] = { {0.0f, 0.0f}, {w, 0.0f}, {0.0f, h}, {w, h} };
cv::Mat matrix = getPerspectiveTransform(src, dst);
cv::Mat img_warp;
cv::warpPerspective(img, img_warp, matrix, cv::Size(w, h));
QImage qimage(img_warp.data, img_warp.cols, img_warp.rows, img_warp.step, QImage::Format::Format_RGB888);
mutex.unlock();
emit detectedFace(qimage);
}
最后应用程序就终止了,谁能帮帮我。
更新:我尝试了您的解决方案,但它引发了相同的异常错误。
connect(dftThread, &DetectFaceThread::detectedFace, this, &QtWidgetsApplication1::onDetectedFace, Qt::QueuedConnection);
【问题讨论】:
标签: c++ visual-studio qt