OpenCV和Qt VideoCapture无法在Windows上打开正确的摄像头

msm*_*zed 8 c++ windows qt opencv image-processing

我正在使用opencv和Qt来创建一个应用程序.在应用程序内部,我正在创建一个记录视频的小工具.出于这个原因而不是阻止主事件线程我创建了一个包含记录线程的单独对话框.在这个初学者的线程中我想看到相机输出(我还没有介绍录制代码).所以我分类QThread了,run()功能如下:

void VideoRecordThread::run(){
    cv::VideoCapture capture;
    cv::Mat frame;
    QImage img;

    qDebug() << "Opening camera" << cameraIndex ;
    capture.open(cameraIndex);

    if(!capture.isOpened()){
        qDebug() << "Could not open camera" << cameraIndex;
        emit threadReturned();
        return;
    }

    while(!stopFlag){
        capture >> frame;
        qDebug() << "Frame Width = " << frame.cols << "Frame Height = " << frame.rows;
        if(frame.cols ==0 || frame.rows==0){
            qDebug() << "Invalid frame skipping";
            continue;
        }
        img = cvMatToQImage(frame); //Custom function
        emit imageCaptured(img);
    }
    capture.release();
    emit threadReturned(); //Custom signal
    qDebug() << "Thread returning";
}
Run Code Online (Sandbox Code Playgroud)

这应该可以工作,但问题是,当线程启动时,我得到一个"突然出现"的新对话框,要求我选择相机时选择其中一个连接的相机,它有时可以工作,有时它不会吨.这是我得到的对话框:

在此输入图像描述

有什么帮助,我该怎么办?

kar*_*lip 4

我注意到,当某些函数不从主线程执行时,OpenCV 会出现问题。

将捕获过程的初始化移至应用程序的主线程,并将其余部分留在辅助线程上。初始化部分似乎是:

cv::VideoCapture capture;

qDebug() << "Opening camera" << cameraIndex ;
capture.open(cameraIndex);

if(!capture.isOpened())
{
    qDebug() << "Could not open camera" << cameraIndex;
    emit threadReturned();
    return;
}
Run Code Online (Sandbox Code Playgroud)