ZBLOG

cv::Mat image1; image1 = image.clone(); //image.copyTo(image1); int sum = 0; int currentRadius = 0; int sum1 = cv::sum(image1)[0]; // 计算灰度图像的像素总和 while (sum < sum1 * ratio / 100) { // 遍历每个像素点 sum = 0; ...

在上面的代码中,计算sum的目的是为了确定当前累加半径下像素值的总和是否达到了特定阈值。如果你希望减少计算sum的频率以节省性能,可以尝试以下两种方法:

  1. 调整循环逻辑:将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只在每次增加半径时计算一次,而不是在内层循环中多次重复计算。

  1. 使用累积和技巧:通过使用累积和的方式来避免重复计算。你可以预先计算并存储一个矩阵,记录每个像素点及其相邻像素的灰度值总和,然后根据需要直接查询该矩阵获取指定范围内的总和。这样可以大幅减少循环中的重复计算。

希望以上方法能对你有所帮助!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16486

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?