php trouble getting closest matching color
I need help finding the closest color match from a set of predefined colors and a single random color, here is my code:
color = array('124','197','118'); // LIGHT GREEN
$match = array(
array('255', '000', '000', 'FF0000'), //red
array('000', '255', '000', '00FF00'), //green
array('000', '000', '255', '0000FF'), //blue
array('0', '255', '255', '00ffff'), //cyan
array('117', '076', '036', '754c24'), //brown
array('000', '000', '000', '000000'), //black
array('149', '149', '149', '959595'), //grey
array('242', '101', '034', 'f26522'), //orange
array('245', '152', '157', 'f5989d'), //pink
array('255', '255', '000', 'FFFF00'), //yellow
array('102', '045', '145', '662d91'), //purple
array('255', '255', '255', 'FFFFFF')); //white
echo 'Color: <div style="background-color:#'.$color.';width:25px;height:25px"></div>'; //color
foreach($match as $co) $temp[] = array( sqrt(($color[0]-$co[0])^2+($color[1]-$co[1])^2+($color[2]-$co[2])^2) , $co[3]);
aso开发者_JAVA百科rt($temp);
foreach($temp as $ta) { echo 'Matched Color: <div style="background-color:#'.$ta[1].';width:25px;height:25px"></div>'; break; }
It returns grey instead of green? How can I fix this problem? Than
here is a link to a matching question with answer:
RGB to closest predefined color
but, if you have an indexed image already, I suggest using this instead:
http://php.net/manual/en/function.imagecolorclosest.php
I put your colors into my color converter to analyze your problem. I think you can see that gray is also the colosest match visually.
I think the tripple 124/197/118 is not a light green but foremost a desaturated green which explains the result.
I'm not sure about some of your color definitions. For me
000 255 000 = Lime Green
000 128 000 = Green
128 128 128 = Gray (50%)
If you still don't like the result:
1, leave out gray from your predefined colors
or
2, define a threshold for returning gray
-> If result is gray but distance > threshold x,
then take the second colosest match
精彩评论