在你的代码中,如果当前半径值 currentRadius 已经超过了最大半径限制(即图像中心到边缘的最小距离),那么循环会被终止。这样就无法精确地找到满足条件的最准确半径值。
如果你想要找到更准确的满足条件的半径值,可以考虑使用二分查找算法。以下是修改后的代码片段示例:
int startRadius = 0;
int endRadius = std::min(Center.y, Center.x);
int bestRadius = -1; // 保存满足条件的最优半径值
while (startRadius <= endRadius)
{
int currentRadius = (startRadius + endRadius) / 2;
// 计算当前半径对应的总和
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 && rowPtr[j] != 0)
{
sum += rowPtr[j];
}
}
}
}
// 根据当前总和与目标总和的比较,更新起始或结束半径值
if (sum < sum1 * ratio / 100)
{
startRadius = currentRadius + 1;
}
else
{
bestRadius = currentRadius;
endRadius = currentRadius - 1;
}
}
if (bestRadius != -1)
{
beamdiameter_energy = bestRadius * 2;
}
else
{
// 没有找到满足条件的半径值
return false;
}
以上代码使用二分查找算法,在每次循环中将当前半径值与最终目标总和进行比较,并根据比较结果更新起始和结束半径。当找到满足条件的最优半径时,将其赋值给 bestRadius 变量。
注意,为了使用二分查找,你需要在循环开始前定义一个 endRadius 变量来保存最大半径限制。如果没有找到满足条件的半径值,则返回 false。
内容由零声教学AI助手提供,问题来源于学员提问




