Jump to content

calculation of average color in clipart image


murfy

Recommended Posts

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");

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).')');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.