opencv VideoCapture is blocked in thread

倾然丶 夕夏残阳落幕 提交于 2019-12-12 15:33:55

问题


I need some some help with the usage of opencv VideoCapture in another thread.

When I use the VideoCapture in the main thread, it is perfectly fine and it shows the video smoothly. But once I put the code in another thread and expect it do the same thing, it seems the VideoCapture does not work at all.

I made some attempts: if I initialize the VideoCapture with 0 (the default one) as parameter, it gets blocked. But if I don't initialize it

VideoCapture cap; 

or use another number

VideoCapture cap(1); 

it prints out error message and exits but does not get blocked.

Here is the code:

#include <iostream>
#include <thread>
#include <functional>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace std;
using namespace cv;

class MyClass {
public:
    // display the video
    static void display(int i) {
        VideoCapture cap(0);

        if (!cap.isOpened()) {
            cout << "cannot access webcame" << endl;
            exit(-1);
        }

        Mat imgOriginal;
        namedWindow("Original", WINDOW_AUTOSIZE);
        while (true) {
            bool success = cap.read(imgOriginal);
            if (!success) {
                cout << "fail to read video into mat" << endl;
                break;
            }
            imshow("Original", imgOriginal);

            if (waitKey(30) == 27) {
                break;
            }
        }
    }
};

int main()
{
    //cout << "Hello World!" << endl;
    thread myThread(bind(MyClass::display, 0));
    myThread.join();

    return 0;
}

Very appreciated if anyone can point out where I got it wrong. Thank you.

来源:https://stackoverflow.com/questions/23624698/opencv-videocapture-is-blocked-in-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!