Does anyone know the correct formula to get the saturation level from RGB color?
I already have a function that does this. I tried many of them posted on the Internet, but only this one seemed to work (for me for the first time), except that the saturation level sometimes went a little out of order.
rgb(204,153,51) should equal hsl(40,60,50) , instead I have hsl(40,75,50) . Since you can see that my hue and lightness are correct, in fact, saturation is basically correct too, but sometimes it is not, and I have to fix it if I can.
This is what I have created so far, so I can verify that all color values โโare correct for my images before storing them in a database for my search engine.

And here is this function, in which I believe that saturation is not calculated correctly:
function RGBtoHSL($red, $green, $blue) { $r = $red / 255.0; $g = $green / 255.0; $b = $blue / 255.0; $H = 0; $S = 0; $V = 0; $min = min($r,$g,$b); $max = max($r,$g,$b); $delta = ($max - $min); $L = ($max + $min) / 2.0; if($delta == 0) { $H = 0; $S = 0; } else { $S = $delta / $max; $dR = ((($max - $r) / 6) + ($delta / 2)) / $delta; $dG = ((($max - $g) / 6) + ($delta / 2)) / $delta; $dB = ((($max - $b) / 6) + ($delta / 2)) / $delta; if ($r == $max) $H = $dB - $dG; else if($g == $max) $H = (1/3) + $dR - $dB; else $H = (2/3) + $dG - $dR; if ($H < 0) $H += 1; if ($H > 1) $H -= 1; } $HSL = ($H*360).', '.($S*100).', '.round(($L*100),0); return $HSL; }
One hint that I have about why this is not working 100% is that I first convert the HEX color to RGB and then RGB to HSL. Will this be a problem due to web safe colors or can you find anything else that might cause this in a function? Or is it just that?
UPDATE 1
An attempt at other images appears to be mainly โbeigeโ (approximate) colors that slightly come out of saturation. Using a set of colors, if I move the saturation panel to where it should be, it doesn't really matter, so maybe my search function won't depend too much on that. It would be nice to solve this problem before I ran it on 500,000 photos.
CORRECTION
Thanks to OmnipotentEntity below, he noticed that I am missing a part for my function. I changed:
$S = $delta / $max;
in
$S = $L > 0.5 ? $delta / (2 - $max - $min) : $delta / ($max + $min);
and now gives 100% correct results.
FRIENDLY NOTE
If someone wants the code to create this color table, just ask.