murfy Posted February 26, 2014 Share Posted February 26, 2014 I have this example code: http://paste.ofcode.org/rc4f3z38S2Vr8VxbX3SvNU You have some png image where you want to calculate an average hue or average color in red colors. For example a clipart of lips which contains three colors: normal red, light red and dark red alias brown. I have the colors in the array $mycolors. Now I would like to calculate the average in this colors so I used a class Lux_Color to convert to HSL color space, then sum the HSL values of colors and then calculate the average. But the result for me is incorrect and I got cyan color, not red or brown as I would expect. Any idea what's wrong? $mycolors = array(array(255,0,0),array(255,126,126),array(86,13,0)); $hsl_colors = array(); $average_color_hsl = array(0,0,0); $lux = new Lux_Color(); for($n=0; $n<count($mycolors); $n++): $hsl = $lux->rgb2hsl($mycolors[$n]); // returns 0 => Hue, 1 => Saturation, 2 => lightness $average_color_hsl[0] += $hsl[0]; $average_color_hsl[1] += $hsl[1]; $average_color_hsl[2] += $hsl[2]; $hsl_colors[] = $hsl; endfor; $average_hue = $average_color_hsl[0]/$n; $average_RGB = $lux->hsl2rgb($average_color_hsl); $average_color = $lux->rgb2hex($average_RGB); die("$n : $average_hue : $average_color"); Quote Link to comment https://forums.phpfreaks.com/topic/286540-calculation-of-average-color-in-clipart-image/ Share on other sites More sharing options...
kicken Posted February 26, 2014 Share Posted February 26, 2014 You're not using your average value when converting back to RGB, rather you are just using the sum of all the pixel HSL values. You need to calculate the average for each or H, S, L and then use those to convert back to RGB with. $mycolors = array(array(255,0,0),array(255,126,126),array(86,13,0)); $average_color_hsl = array(0,0,0); $lux = new Lux_Color(); for($n=0; $n<count($mycolors); $n++): $hsl = $lux->rgb2hsl($mycolors[$n]); // returns 0 => Hue, 1 => Saturation, 2 => lightness $average_color_hsl=array_map(function($a,$b){ return $a+$b; }, $average_color_hsl, $hsl); endfor; $average_color_hsl = array_map(function($a) use ($n) { return $a/$n; }, $average_color_hsl); $average_RGB = $lux->hsl2rgb($average_color_hsl); $average_color = $lux->rgb2hex($average_RGB); die("$n : $average_color rgb(".implode(',', $average_RGB).')'); Quote Link to comment https://forums.phpfreaks.com/topic/286540-calculation-of-average-color-in-clipart-image/#findComment-1470780 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.