Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV and Qt VideoCapture does not open the correct camera on windows

I am using opencv and Qt to create an application. Inside the application I am creating a small tool to record video. For this reason and not to block the main event thread I created a separate dialog that contains a recording thread. In this thread for starters I wanted to just see the camera output(I have not introduced the recording code yet). So I subclassed QThread and the run() function is the following:

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";
}

this is supposed to work, but the problem is that when the thread starts, I get a new dialog "out of the blue" asking me to select the camera when I select one of the cameras connected, it sometimes work and sometimes it doesn't. Here is the dialog that I get:

enter image description here

Any help on what can I do?

like image 309
msmechanized Avatar asked Apr 26 '12 20:04

msmechanized


1 Answers

I've noticed that OpenCV has problems when some functions are not executed from the main thread.

Move the initialization of the capture procedure to the main thread of your application and leave the rest on your secondary thread. The initialization part seems to be:

cv::VideoCapture capture;

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

if(!capture.isOpened())
{
    qDebug() << "Could not open camera" << cameraIndex;
    emit threadReturned();
    return;
}
like image 83
karlphillip Avatar answered Oct 14 '22 00:10

karlphillip