因此,我想弄清楚如何计算颜色由HSL值表示的多个对象的平均色相。值得庆幸的是,我偶然发现了this Stack Overflow post,并开始着手实现最佳答案中提供的算法(我在C++中工作)。

不幸的是,我的实现似乎没有用。这是全部。请注意,尽管我写了“Hue”,但按照初始实现,我使用的是角度(以度为单位)(一旦我知道我的代码有效,就可以从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)。

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

最佳答案

atan2以相反的顺序接受其参数。我知道,烦人!因此,请尝试:

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

现在给出的答案是3.00488。

09-18 13:12