void Extract1DEdge::GetProfieMat() { if (m_mInputMat.empty()) { return; } if (m_mInputMat.channels() > 1) { cvtColor(m_mInputMat, m_mInputMat, COLOR_BGR2GRAY); } Mat RotateMat = getRotationMatrix2D(m_pdCenter, -m_dAngle, 1); warpAffine(m_mInputMat, m_mInputMat, RotateMat, m_mInputMat.size(), WARP_INVERSE_MAP); Mat newCenter = RotateMat * (Mat_<double>(3, 1) << m_pdCenter.x, m_pdCenter.y, 1); double x = newCenter.at<double>(0, 0); double y = newCenter.at<double>(1, 0); Mat M = (Mat_<double>(2, 3) << 1, 0, x - m_dLength * 0.5, 0, 1, y - m_dHeight * 0.5); warpAffine(m_mInputMat, m_mInputMat, M, Size2d(m_dLength, m_dHeight), WARP_INVERSE_MAP); }如何保持效果不变的情况下加速这段代码给个例程
时间: 2024-02-18 08:59:12 浏览: 120
FindMe-src.zip_Before_throw.m
可以考虑使用OpenCV提供的并行计算模块,如OpenCV的ParallelLoopBody类和ParallelFor函数,来加速这段代码。具体做法如下:
1. 头文件引入:
```cpp
#include <opencv2/core/parallel.hpp>
```
2. 利用ParallelLoopBody类重写GetProfieMat函数中需要并行处理的for循环,如下:
```cpp
class Extract1DEdge_Parallel : public cv::ParallelLoopBody
{
public:
Extract1DEdge_Parallel(Mat& inputMat, Point2d center, double angle, double length, double height)
: m_mInputMat(inputMat), m_pdCenter(center), m_dAngle(angle), m_dLength(length), m_dHeight(height)
{}
virtual void operator()(const cv::Range& range) const
{
for (int i = range.start; i < range.end; i++)
{
// 在这里写需要并行处理的代码
// 例如,对矩阵进行处理等
}
}
private:
Mat& m_mInputMat;
Point2d m_pdCenter;
double m_dAngle;
double m_dLength;
double m_dHeight;
};
```
3. 在GetProfieMat函数中调用ParallelFor函数,并传入ParallelLoopBody类的实例,如下:
```cpp
void Extract1DEdge::GetProfieMat()
{
if (m_mInputMat.empty())
{
return;
}
if (m_mInputMat.channels() > 1)
{
cvtColor(m_mInputMat, m_mInputMat, COLOR_BGR2GRAY);
}
Mat RotateMat = getRotationMatrix2D(m_pdCenter, -m_dAngle, 1);
warpAffine(m_mInputMat, m_mInputMat, RotateMat, m_mInputMat.size(), WARP_INVERSE_MAP);
Mat newCenter = RotateMat * (Mat_<double>(3, 1) << m_pdCenter.x, m_pdCenter.y, 1);
double x = newCenter.at<double>(0, 0);
double y = newCenter.at<double>(1, 0);
Mat M = (Mat_<double>(2, 3) << 1, 0, x - m_dLength * 0.5, 0, 1, y - m_dHeight * 0.5);
warpAffine(m_mInputMat, m_mInputMat, M, Size2d(m_dLength, m_dHeight), WARP_INVERSE_MAP);
// 调用ParallelFor函数
Extract1DEdge_Parallel parallelBody(m_mInputMat, m_pdCenter, m_dAngle, m_dLength, m_dHeight);
cv::parallel_for_(cv::Range(0, m_mInputMat.rows), parallelBody);
}
```
注意:并行计算的效果取决于计算任务的复杂性和硬件环境等因素,需要根据实际情况调整并行范围和线程数等参数,以达到最佳性能。
阅读全文