PHP Find the closest RGB to the predefined RGB from the list.

My goal is to find the closest RGB match compared to the RGB from the array. I already created a function that intersects every pixel in the picture. The only thing I need now is to find the 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 the image to 8 bits in order to reduce the number of colors and compare them later in the database, but that just doesn't seem like a good idea.

+6
source share
1 answer

Try the following:

 $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 is also possible to use

Disclaimer: There may be more elegant implementation methods, possibly using map .

+6
source

Source: https://habr.com/ru/post/946350/


All Articles