Getting a camera image from a stream

I am using the opencv library to get video from an embedded webcam. The following code works fine when I put the camera code in the main function, but it doesn't when I put it on a separate thread. The thread task1()

stops at cv::VideoCapture capture(0)

. Meanwhile, both as task2()

well as the main thread execute correctly.

Can anyone explain to me why the opencv logic doesn't work when put on a 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;
        }

      

+3


source to share


1 answer


Your code works as it should for me (without any changes) and I am getting a live feed via task1 stream (using OpenCV 2.4.5). I added a flag -std=gnu++0x

to support the compiler (otherwise g ++ will throw an error).

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

      



Check my console output here . I added cout << "1st thread "<< endl;

inside the while loop to task1.

I think the problem might be specific to some versions of opensv, as I've seen similar problems in an older version (can't remember which one) and raises threads. Can you give details of the version you were using ?. Also try with 2.4.5.

+1


source







All Articles