OpenCV,pthread - 在新线程中显示图像

时间:2012-04-21 14:59:02

标签: c++ multithreading image-processing opencv pthreads

我有一个主要功能从某个地方拍摄图像,它应该显示在一个新的线程中。这就是我正在做的事情:

int main(int argc, char** argv)
{
    Mat frame = imread("img.jpg");

    auto_ptr<SomeClass> thread1(new SomeClass(1, frame));
    auto_ptr<SomeClass> thread2(new SomeClass(2, frame));

    thread1->Start();
    thread2->Start();

    int result1 = reinterpret_cast<int>(thread1->Join());
    int result2 = reinterpret_cast<int>(thread2->Join());

    return 0;
}

我找到了许多源代码来实现一个简单的pthread包装类,哪些工作正常,只要我不尝试将“cv :: Mat frame”图像传递给派生线程(通过它的构造函数) )。

pthread包装类:

/* ********************* THREAD.H ********************* */
extern "C++" class __declspec(dllexport) Thread 
{
public:
    Thread();
    virtual ~Thread(void);

    void Start(void);
    void* Join(void);

private:
    virtual void* Run(void) = 0;

    static void* StartThread(void* pVoid);

    pthread_t threadID_;
    pthread_attr_t threadAttribute_;
    void* result_;
};

/* ********************* THREAD.CPP ********************* */
Thread::Thread() {}

Thread::~Thread() {}

void* Thread::StartThread(void* pVoid) 
{
    Thread* aThread = static_cast<Thread*>(pVoid);
    aThread->result_ = aThread->Run();
    return aThread->result_;
}

void Thread::Start() 
{
    pthread_attr_init(&threadAttribute_);
    pthread_attr_setscope(&threadAttribute_, PTHREAD_SCOPE_SYSTEM);

    pthread_create(&threadID_, &threadAttribute_, Thread::StartThread, (void*)this);
    pthread_attr_destroy(&threadAttribute_);
}


void* Thread::Join() 
{
    pthread_join(threadID_, NULL);
    return result_;
}

Thread的子类如下所示:

/* ********************* SOMECLASS.H ********************* */
extern "C++" class __declspec(dllexport) SomeClass : public Thread
{
public:
    SomeClass(int id, cv::Mat& frame);
    ~SomeClass(void);

    virtual void* Run();
private:
    int id_;
    cv::Mat frame_;
};

/* ********************* SOMECLASS.CPP ********************* */
SomeClass::SomeClass(int id, cv::Mat& frame) : id_(id)
{
    frame_ = frame.clone();
}

SomeClass::~SomeClass(void) {}

void* SomeClass::Run() 
{
    cout << id_ << ", " << frame_.cols << ", " << frame_.rows << endl;

    imshow("frame " + id_, frame_);
    waitKey(1);

    return reinterpret_cast<void*>(id_);
}

执行在imshow()行中断...有什么想法会导致这个问题,或者我该如何解决?

1 个答案:

答案 0 :(得分:0)

问题已经解决了。如果有人遇到类似的麻烦,那么: 整个OpenCV项目需要通过英特尔TBB支持进行重建。 (它与OpenCV 2.3.1配合良好)