【问题标题】:Averaging circular values (particularly Hues in HSL color scheme)平均循环值(特别是 HSL 配色方案中的色调)
【发布时间】:2012-12-07 05:05:15
【问题描述】:

所以我试图弄清楚如何计算许多颜色由 HSL 值表示的对象的平均色调。值得庆幸的是,我偶然发现了this Stack Overflow post,并开始着手实现最佳答案中提供的算法(我正在使用 C++)。

不幸的是,我的实现似乎不起作用。在这里,完整的;请注意,虽然我写了“色调”,但我使用的是角度,以度为单位,根据初始实现(从 0-360 角度切换到 0-256 色调,一旦我知道我的代码有效,应该不难)。

#include <iostream>    
#include <vector>
#include <cmath>

#define PI (4*atan(1))

int main()
{
    ///
    /// Calculations adapted from this source:
    /// https://stackoverflow.com/questions/8169654/how-to-calculate-mean-and-standard-deviation-for-hue-values-from-0-to-360

    std::vector<double> Hues = {355, 5, 5, 5, 5};

    //These will be used to store the sum of the angles
    double X = 0.0;
    double Y = 0.0;

    //Loop through all H values
    for (int hue = 0; hue < Hues.size(); ++hue)
    {
        //Add the X and Y values to the sum X and Y
        X += cos(Hues[hue] / 180 * PI);
        Y += sin(Hues[hue] / 180 * PI);
    }

    //Now average the X and Y values
    X /= Hues.size();
    Y /= Hues.size();

    //Get atan2 of those
    double AverageColor = atan2(X, Y) * 180 / PI;

    std::cout << "Average: " << AverageColor << "\n";
    return 0;
}

我得到的是 86.9951,而不是预期的 3(因为在这个方案中 355 应该等于 -5)。

有人能指出我做错了什么吗?这似乎很基本。

【问题讨论】:

    标签: c++ math colors hsl


    【解决方案1】:

    atan2 以相反的顺序接受它的参数。我知道,烦人!所以试试:

    double AverageColor = atan2(Y, X) * 180 / PI;
    

    它现在给出的答案是 3.00488。

    【讨论】:

    • 天哪,太尴尬了。我应该看到的。谢谢!
    • 提醒自己这一事实的一种方法是记住,您要做的是获取atan(Y / X),但我们希望它仍以X -&gt; 0 工作。这种看起来像atan2(Y, X)
    • 为了简化程序员的生活,请注意有些语言的顺序是相反的——例如在 Excel 中 atan2(x;y)
    【解决方案2】:

    试试atan2(Y, X)atan2(a,b)atan(a/b) 类似,您需要平均正弦与平均余弦的反正切。

    【讨论】:

      猜你喜欢
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      相关资源
      最近更新 更多