grzebyk
grzebyk

Reputation: 1034

Getting camera image from thread

I am using opencv library to obtain video from the built-in webcam. The following code works perfectly well when i put camera logic code into the main function, but it doesn't when i put it into separate thread. The task1() thread stops at cv::VideoCapture capture(0). Meanwhile both task2() and the main thread are executing correctly.

Could someone explain me why opencv logic doesn't work when put into separate thread?

My code:

#include <iostream>
#include <string.h>
#include <thread>
#include <unistd.h>
#include <opencv2/opencv.hpp>

using namespace std;

void task1 (){
            cout<<"1st thread ";
            cv::Mat frame;
            cv::VideoCapture capture(0);
            if ( capture.isOpened() == false )
            {
                cout<<"Failed to open camera";
            }

            cv::namedWindow("Test OpenCV",1);


            while ( true ){
                capture >> frame;
                cv::imshow("Test OpenCV", frame );
                int key = cv::waitKey(1);
                if ( key == 27 )
                    break;
            }

        }

        void task2 (){
            int n = 0;
            while (1){
                cout<<"2nd thread "<<n<<"\n";
                sleep(3);
                n++;
            }
        }

        int main(int argc, const char * argv[]) {
            // insert code here...
            cout << "Hello, World!\n";
            thread t1(task1);
            thread t2(task2);
            //t1.join();
            //t2.join();
            int n = 0;
            while (1){
                cout<<"main thread "<<n<<"\n";
                sleep(1);
                n++;
            }  
            return 0;
        }

Upvotes: 3

Views: 2024

Answers (1)

Vasanth
Vasanth

Reputation: 1278

Your code runs as it should for me (without any modifications) and I get the live feed through the task1 thread (using OpenCV 2.4.5). I added -std=gnu++0x flag for compiler support (otherwise g++ throws an error).

g++ -std=gnu++0x opencv_thread.cpp -o opencv_thread `pkg-config --cflags --libs opencv`

Check my console output here. I added a cout << "1st thread "<< endl; within the while loop in task1.

I think the issue might be specific to some opencv versions as I have seen similar issues in an older version (don't remember which one) and boost threads. Can you give details about the version you used?. Also try it with 2.4.5.

Upvotes: 1

Related Questions