所以我試圖弄清楚如何計算許多物體的平均色調,其顏色由HSL值表示。幸運的是,我偶然發現了this Stack Overflow post,並開始實施頂級答案中提供的算法(我正在使用C++)。平均圓形值(特別是HSL顏色方案中的色調)
不幸的是,我的實現似乎沒有工作。這是完整的;請注意,儘管我編寫「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;
}
取而代之的3(因爲355應該等於-5在此方案)中,預期的答案,我得到86.9951。
有人可以指出我做錯了什麼嗎?這似乎很基本。
哦,上帝,這是尷尬。我應該看到這一點。謝謝! – GarrickW
提醒自己這個事實的一個方法是記住你要做的是得到'atan(Y/X)',除了我們希望它仍然是'X - > 0'。這種看起來像'atan2(Y,X)'。 –
爲了簡化程序員的生活,請注意一些語言的順序相反 - 例如在Excel中atan2(x; y) –