I've read a lot in the very complete post: Formula to determine brightness of RGB color
What bothers me is that even with all those formulas, I can't get a fine result... And this is quite bothering since I want to sort colors in a palette, from darkest to lightest. If the sorting is wrong, it is quickly a lot of pain to watch.
Quick example with the formula: (0.2126*R + 0.7152*G + 0.0722*B) which seems to be the most common answer over the web.
Edited after Peter's answer
function colorCodeToRGB(colorCode) {
colorCode = colorCode.substr(1);
return [
colorCode.substr(0, 2),
colorCode.substr(2, 2),
colorCode.substr(4, 2)
].map(it => parseInt(it, 16));
}
const luminanceCoefficients = [.2126, .7152, .0722];
function getLuminance(color) {
const [r, g, b] = colorCodeToRGB(color);
return r * luminanceCoefficients[0] + g * luminanceCoefficients[1] + b * luminanceCoefficients[2];
}
function linearizeSRGB(colorChannel) {
colorChannel /= 255;
if (colorChannel <= .04045 ) {
return colorChannel / 12.92;
} else {
return Math.pow((colorChannel + .055)/1.055, 2.4);
}
}
console.log('First set of colors');
console.log('#1883b1', getLuminance('#1883b1'));
console.log('#2c3b4c', getLuminance('#2c3b4c'));
console.log('Second set of colors');
console.log('#920f1e', getLuminance('#920f1e'));
console.log('#c3313d', getLuminance('#c3313d'));
.c {
height: 2rem;
width: 2rem;
}
Sample of colors
<span class="c" style="background-color: #1883b1"> </span>
<span class="c" style="background-color: #2c3b4c"> </span>
<span class="c" style="background-color: #920f1e"> </span>
<span class="c" style="background-color: #c3313d"> </span>
Everyone can see that the first blue is lighter than the second one, and its value is smaller, although on the second set, the first red seems darker than the second one, although it has a smaller value...
I don't get it, is there some way to actually determine perceived brightness?
I've tested all of the formulas on the post mentioned at the beginning of this question, and by sliding the color picker, I always find funny cases that illustrate a problem. I've no constraints, I can work with HSL, RGB, CIELAB, whatever!
Thanks by advance guys!
Apparently there are at least two issues with your implementation.
The first is that the ^
operator (in ^2.4
) is not a power operator in JavaScript, but an "exclusive-or" operator. Replace the line where that operator appears with the following.
return Math.pow(((colorChannel + .055)/1.055), 2.4);
Also, the getLuminance
method is implemented incorrectly; the main reason for that might be the reduce
method, which can be confusing, at least to me. Replace that implementation with the following (which uses the much simpler map
as well as direct addition and multiplication):
function getLuminance(color) {
var cv=colorCodeToRGB(color).map(v=>linearizeSRGB(v))
return cv[0]*luminanceCoefficients[0]+
cv[1]*luminanceCoefficients[1]+
cv[2]*luminanceCoefficients[2]
}