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:
Any help on what can I do?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With