OpenCV C++ 多线程 [英] OpenCV C++ Multithreading

查看:284
本文介绍了OpenCV C++ 多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 opencv 图像处理函数在 4 个不同的 Mat 对象上被调用 4x.

I have this opencv image processing function being called 4x on 4 diferent Mat objects.

void processBinary(Mat& binaryMat) {
    //image processing
}

我想对它进行多线程处理,以便所有 4 个方法调用同时完成,但让主线程等待每个线程完成.

I want to multi-thread it so that all 4 method calls complete at the same time, but have the main thread wait until each thread is done.

例如:

int main() {

    Mat m1, m2, m3, m4;

    //perform each of these methods simultaneously, but have main thread wait for all processBinary() calls to finish
    processBinary(m1);
    processBinary(m2);
    processBinary(m3);
    processsBinary(m4);
}

我希望实现的是能够根据需要多次调用 processBinary() 并且具有与只调用一次方法相同的效率.我已经查找了多线程,但对调用线程然后加入/分离它们有点困惑.我相信我需要实例化每个线程,然后在每个线程上调用 join() 以便主线程等待每个线程执行,但执行时间似乎没有显着增加.谁能解释我应该如何处理我的程序的多线程?谢谢!

What I hope to accomplish is to be able to call processBinary() as many times as I need and have the same efficiency as having the method called only once. I have looked up multithreading, but am a little confused on calling threads and then joining / detaching them. I believe I need to instantiate each thread and then call join() on each thread so that the main thread waits for each to execute, but there doesn't seem to be a significant increase in execution time. Can anyone explain how I should go about multi-threading my program? Thanks!

编辑:我尝试过的:

//this does not significantly increase execution time. However, calling processBinary() only once does.4

    thread p1(&Detector::processBinary, *this, std::ref(m1));
    thread p2(&Detector::processBinary, *this, std::ref(m2));
    thread p3(&Detector::processBinary, *this, std::ref(m3));
    thread p4(&Detector::processBinary, *this, std::ref(m4));
    p1.join();
    p2.join();
    p3.join();
    p4.join();

推荐答案

实现这一点的巧妙方法不是自己进行线程管理,而是使用提供微并行化的库.

The slick way to achieve this is not to do the thread housekeeping yourself but use a library that provides micro-parallelization.

OpenCV 本身使用 英特尔线程构建块 (TBB) 来完成这项任务——并行运行循环.

OpenCV itself uses Intel Thread Building Blocks (TBB) for exactly this task -- running loops in parallel.

就您而言,您的循环只有四次迭代.使用 C++11,您可以使用 lambda 表达式非常轻松地将其写下来.在您的示例中:

In your case, your loop has just four iterations. With C++11, you can write it down very easily using a lambda expression. In your example:

std::vector<cv::Mat> input = { m1, m2, m3, m4; }
tbb::parallel_for(size_t(0), input.size(), size_t(1), [=](size_t i) {
    processBinary(input[i]); 
});

对于这个例子,我从 此处.

For this example I took code from here.

这篇关于OpenCV C++ 多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆