Reputation:
I'm a new software developper.I develop an OCR project using OPENCV. I want to split the image and consider evry part of the image as an isolated image. An idea come in my mind why not i use multithread to minimize and optimize the time of execution.
Who have a link or an example which combine between opencv and multithread in C++.
Thanks a lot.
Upvotes: 0
Views: 5508
Reputation: 1519
Opencv has support for using threads with a lot of basic functions like cvtColor. It depends on how you compiled the opencv lib.
Look at opencv parallel_for for more information.
Upvotes: 0
Reputation: 1212
With C++11, you can use the in-built thread class to create multiple threads. You can pass arguments to these threads as you'd do for functions. Note that multiple threads may create more problems than they were solving!
Upvotes: 2
Reputation: 3858
You can use TBB. Here is an example:
#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])));
}
As you see you have the code for processing each of the image regions in the Task class. Then, when you call the parallel_for
passing the TaskPool
constructor, it will handle the multithreading stuff.
Another options include OpenMP, which can be even easier to use (it also includes parallel for
), but I had some trouble when trying to use it with some versions of the GCC compiler.
Upvotes: 1