My goal is to find the closest match of RGB compared to the RGB from the array. I have already created a function that loops trough every pixel in a picture. The only thing I need now is to find closest color of each pixel in the picture to the color from the array.
$colors = array(
array(221,221,221),
array(219,125,62),
array(179,80,188),
array(107,138,201),
array(177,166,39),
array(65,174,56),
array(208,132,153),
array(64,64,64),
array(154,161,161),
array(46,110,137),
array(126,61,181),
array(46,56,141),
array(79,50,31),
array(53,70,27),
array(150,52,48),
array(25,22,22)
);
I tried converting picture to 8bits to reduce number of colors and compare them later in database but that just doesn't seem to be a good idea.
Try it like this:
$inputColor = array(20,40,80);
function compareColors($colorA, $colorB) {
return abs($colorA[0] - $colorB[0]) + abs($colorA[1] - $colorB[1]) + abs($colorA[2] - $colorB[2]);
}
$selectedColor = $colors[0];
$deviation = PHP_INT_MAX;
foreach ($colors as $color) {
$curDev = compareColors($inputColor, $color);
if ($curDev < $deviation) {
$deviation = $curDev;
$selectedColor = $color;
}
}
var_dump($selectedColor);
The advantage of this solution is that you can easily replace the comparison function. It might also be possible to use
Disclaimer: There might be more elegant ways of implementation, perhaps leveraging map
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With