使用多线程加速处理这一段for (int i = 0; i < m; i++) { edges = Extract1DEdgeCircle.Get1DEdge(RoiMat, m_vpdEquinoxPoints[i], m_dMeasureLength, m_dMeasureHeight, m_vdMeasureAngle[i] , m_dSigma, m_nThresholdCircle, m_nTranslationCircle == 1 ? Translation::Poisitive : Translation::Negative, Selection::Strongest); for (int i = 0; i < edges.size(); i++) { m_vpdEdgePoints.push_back(edges[i].m_pdEdgePoint); m_vdEdgeGradient.push_back(edges[i].m_dGradient); } }
时间: 2023-12-10 10:40:19 浏览: 62
14个常用OpenCV+C++图像处理.rar
可以使用多线程的方式将这个for循环中的任务分配给多个线程处理,从而加速处理过程。
具体实现方式可以使用C++11中的std::thread库进行线程的创建和管理。将for循环的迭代次数分配给多个线程处理,每个线程处理一部分数据。需要注意的是,多个线程同时向同一个vector中添加元素可能会存在竞争条件,需要使用互斥锁来保证线程安全。
示例代码如下:
```c++
#include <thread>
#include <vector>
#include <mutex>
// 定义互斥锁
std::mutex mtx;
void process(int start, int end, const cv::Mat& RoiMat, const std::vector<cv::Point2d>& m_vpdEquinoxPoints, double m_dMeasureLength, double m_dMeasureHeight, double m_dSigma, double m_nThresholdCircle, int m_nTranslationCircle, const std::vector<double>& m_vdMeasureAngle, std::vector<cv::Point2d>& m_vpdEdgePoints, std::vector<double>& m_vdEdgeGradient)
{
std::vector<Edge> edges;
for (int i = start; i < end; i++)
{
edges = Extract1DEdgeCircle.Get1DEdge(RoiMat, m_vpdEquinoxPoints[i], m_dMeasureLength, m_dMeasureHeight, m_vdMeasureAngle[i], m_dSigma, m_nThresholdCircle, m_nTranslationCircle == 1 ? Translation::Poisitive : Translation::Negative, Selection::Strongest);
// 加锁
mtx.lock();
for (int j = 0; j < edges.size(); j++)
{
m_vpdEdgePoints.push_back(edges[j].m_pdEdgePoint);
m_vdEdgeGradient.push_back(edges[j].m_dGradient);
}
// 解锁
mtx.unlock();
}
}
int main()
{
// 定义线程数
const int thread_num = 4;
// 定义任务数量
const int task_num = m;
// 定义每个线程处理的任务数量
const int task_per_thread = task_num / thread_num;
// 定义线程池
std::vector<std::thread> threads;
// 分配任务并启动线程
for (int i = 0; i < thread_num; i++)
{
int start = i * task_per_thread;
int end = i < thread_num - 1 ? start + task_per_thread : task_num;
threads.emplace_back(std::thread(process, start, end, std::ref(RoiMat), std::ref(m_vpdEquinoxPoints), m_dMeasureLength, m_dMeasureHeight, m_dSigma, m_nThresholdCircle, m_nTranslationCircle, std::ref(m_vdMeasureAngle), std::ref(m_vpdEdgePoints), std::ref(m_vdEdgeGradient)));
}
// 等待所有线程执行完毕
for (auto& t : threads)
{
t.join();
}
return 0;
}
```
阅读全文