在上面的代码中,计算sum的目的是为了确定当前累加半径下像素值的总和是否达到了特定阈值。如果你希望减少计算sum的频率以节省性能,可以尝试以下两种方法:
- 调整循环逻辑:将sum计算放在内层循环之外,这样只需要在每个半径增加时重新计算一次即可。修改后的代码如下所示:
while (sum < sum1 * ratio / 100)
{
sum = 0;
// 遍历每个像素点
#pragma omp parallel for reduction(+:sum)
for (int i = Center.y - currentRadius; i <= Center.y + currentRadius; ++i)
{
double powIcenterX = pow(i - Center.y, 2);
uchar* rowPtr = image1.ptr<uchar>(i); // 获取当前行指针,减少内存访问次数
for (int j = Center.x - currentRadius; j <= Center.x + currentRadius; ++j)
{
if (i >= 0 && i < image1.rows && j >= 0 && j < image1.cols)
{
double distance = sqrt(powIcenterX + pow(j - Center.x, 2));
if (distance <= currentRadius)
{
sum += rowPtr[j];
}
}
else
{
continue;
}
}
}
currentRadius += 6;
if (Center.y - currentRadius < 0 || Center.y + currentRadius >= image1.rows ||
Center.x - currentRadius < 0 || Center.x + currentRadius >= image1.cols)
{
break;
}
}
beamdiameter_energy = (currentRadius - 6/2) * 2;
return true;
这样,sum只在每次增加半径时计算一次,而不是在内层循环中多次重复计算。
- 使用累积和技巧:通过使用累积和的方式来避免重复计算。你可以预先计算并存储一个矩阵,记录每个像素点及其相邻像素的灰度值总和,然后根据需要直接查询该矩阵获取指定范围内的总和。这样可以大幅减少循环中的重复计算。
希望以上方法能对你有所帮助!
内容由零声教学AI助手提供,问题来源于学员提问