【问题标题】:How to combine between opencv and multithread?如何在opencv和多线程之间结合?
【发布时间】:2014-04-23 08:40:16
【问题描述】:

我是一名新软件开发人员。我使用 OPENCV 开发了一个 OCR 项目。我想分割图像并将图像的每一部分视为一个孤立的图像。我想到了一个想法,为什么不使用多线程来最小化和优化执行时间。 谁有在 C++ 中结合 opencv 和多线程的链接或示例。
非常感谢。

【问题讨论】:

  • 要求链接是不受欢迎的,StackOverflow 正在寻找可以独立存在的答案。真的,这里的问题是什么?你有没有尝试过你提出的建议?这有什么问题吗?
  • 问题是opencv和多线程如何结合?
  • 如果你编译的 OpenCV 支持线程(如 TBB 或 OpenMP),许多内置函数已经是多线程的。

标签: c++ multithreading opencv


【解决方案1】:

使用 C++11,您可以使用内置的 thread 类来创建多个线程。您可以将参数传递给这些线程,就像对函数所做的那样。请注意,多个线程可能会产生比它们解决的问题更多的问题!

【讨论】:

    【解决方案2】:

    您可以使用TBB。这是一个例子:

    #include "tbb/parallel_for.h"
    #include "tbb/blocked_range.h"
    
    using namespace tbb;
    class TaskPool {
        Mat image; /**< Image to process  */
        Task** t_vector;
    
    public:
        // This empty constructor with an initialization list is used to setup calls to the function
        TaskPool(cv::Mat frame, Task** current_tasks)
        {
            image = frame;
            t_vector = current_tasks;
        }
    
      /*----------------------------------------------------------+
       | Here is the actual body, that will be called in parallel |
       | by the TBB runtime. You MUST put this code inside the    |
       | class definition, since the compiler will be expanding   |
       | and inlining this code as part of the template process.  |
       |                                                          |
       | The blocked_range<int> is something like a list of       |
       | indexes corresponding to each invocation of the function |
       +----------------------------------------------------------*/
        void operator() ( const blocked_range<int>& r ) const
        {
            for ( int i = r.begin(); i != r.end(); i++ )
            { // iterates over the entire chunk
                t_vector[i]->run(image);
            }
    
        }
    };
    
    // Here is the call to the parallelized code
    void RunTasks(const Mat&image)
    {
        // Each Task is a class containing a run(const Mat&) method which process some region of the image (e.g. calculates the histogram or whatever)
        vector<Task*> taskVector;
        // ... create/initialize the tasks here
    
        /// Do the TBB parallel stuff
        int k = trackVector.size();
        parallel_for(blocked_range<int>(0,k),
                     TaskPool(image,&(taskVector[0])));
    
    }
    

    如您所见,您拥有处理 Task 类中每个图像区域的代码。然后,当您通过 TaskPool 构造函数调用 parallel_for 时,它将处理多线程的东西。

    另一个选项包括OpenMP,它可以更容易使用(它还包括parallel for),但我在尝试将它与某些版本的 GCC 编译器一起使用时遇到了一些麻烦。

    【讨论】:

      【解决方案3】:

      Opencv 支持使用具有许多基本功能(如 cvtColor)的线程。这取决于您如何编译 opencv 库。

      查看 opencv parallel_for 了解更多信息。

      【讨论】:

        猜你喜欢
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-08
        • 1970-01-01
        • 2019-11-17
        • 1970-01-01
        • 2013-08-21
        相关资源
        最近更新 更多