在尝试了几种不同的公式后,我在以下方面取得了最大的成功
let colorfulness = ((max+ min) * (max-min))/max
其中 max 和 min 分别是最高和最低 RGB 值。 This page 对公式本身有更详细的解释。
这将返回一个介于 0 和 255 之间的值,其中 0 是最不色彩的,而 255 是最多的。通过在一堆不同的颜色上运行它,我发现对于我的应用程序,任何高于 50 的值都足够色彩鲜艳,我认为你可以调整它。
我的最终代码如下
function getColorFromImage(image) {
//gets the three most commonly occuring, distinct colors in an image as RGB values, in order of their frequency
let palette = getPaletteFromImage(image, 3)
for (let color of palette){
var colorfulness = 0
//(0,0,0) will return NAN if used in the formula, if (0,0,0) leave colorfulness as its default 0
if (color != [0,0,0]){
//get min & max values
let min = Math.min(color)
let max = Math.max(color)
//calculate colorfulness of color
colorfulness = ((max+ min) * (max-min))/max
}
//compare color's colorfulness against a threshold to determine if color is "colorful" enough
//ive found 50 is a good threshold but adjust as needed
if (colorfulness >= 50.0){
return color
}
}
//if none of the colors are deemed to be sufficiently colorful, just return the most common
return palette[0]
}