线程之间Qt信号/插槽通信中的分段故障

问题描述

我在Qt项目中包含了OpenCV,以检测视频中的部分。我有一个单独的线程,它遍历每个框架。为了调试输出,我将Mat转换为QImage并将引用发送到主线程,在该主线程中图像显示QLabel

Init函数,它还会启动线程以返回第一帧。

void KeyDetectorThread::init(QString videoPath)
{
    capture = new VideoCapture(videoPath.toStdString());

    initiated = true;

    if (!isRunning())
    {
        start(LowPriority);
    }
}

线程在每次迭代时都会暂停,以分析每一帧,除非pauseIteration == false

void KeyDetectorThread::run()
{
    Mat frame;
    //while (capture->grab())
    for(int i = 0; i < 10; ++i)
    {
        qDebug() << i;

        capture->read(frame);
        QImage *img = new QImage((uchar*) frame.data,frame.cols,frame.rows,frame.step,QImage::Format_RGB888);
        emit imageChanged(img);

        mutex.lock();
        if (pauseIteration)
            condition.wait(&mutex);
        mutex.unlock();
    }
}

主线程中的插槽:

void MainWindow::setVideoImage(QImage *image)
{
    qDebug() << curVideoImg << " | " << image;

    if (curVideoImg != nullptr)
    {
        // free memory for old image
        delete curVideoImg;
    }

    curVideoImg = image;

    Qpixmap pm = Qpixmap::fromImage(*curVideoImg);
    int w = ui->imageOutput->width ();
    int h = ui->imageOutput->height ();
    ui->imageOutput->setpixmap (pm.scaled (w,h,Qt::KeepAspectRatio));
}

当线程中的迭代完成时,我在Qpixmap pm = Qpixmap::fromImage(*curVideoImg);行中遇到了分段错误。我以为,当我将指针传递给信号时,就不会发生这种情况。确实,这种错误不会一直发生。我还没有找到一种模式。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)