Skip to content

Commit

Permalink
Improve mechanism that picks the closest color
Browse files Browse the repository at this point in the history
  • Loading branch information
willemstuursma committed Oct 2, 2018
1 parent e52f7c5 commit 3ff734a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
4 changes: 4 additions & 0 deletions src/Legofy.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ class Legofy
{
private $brick;
private $brickAverageColor;

/**
* @var LegoPaletteInterface
*/
private $palette;

public function __construct($brickResource = null, LegoPaletteInterface $palette = null)
Expand Down
27 changes: 15 additions & 12 deletions src/Pallete/ColorPalette.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class ColorPalette implements LegoPaletteInterface
{
private $palette = [
private const PALETTE = [
'024' => [
254,
196,
Expand Down Expand Up @@ -264,28 +264,31 @@ class ColorPalette implements LegoPaletteInterface
],
];

/**
* @link https://stackoverflow.com/questions/4485229/rgb-to-closest-predefined-color
*/
public function pickClosestColor(AbstractColor $color): AbstractColor
{
$distances = [];

$colorArray = $color->getArray();

foreach ($this->palette as $colorIdentifier => $colorSchema) {
$distance =
abs($colorSchema[0] - $colorArray[0]) +
abs($colorSchema[1] - $colorArray[1]) +
abs($colorSchema[2] - $colorArray[2]);
foreach (self::PALETTE as $colorIdentifier => $colorSchema) {

$distances[$distance] = [$colorSchema[0], $colorSchema[1], $colorSchema[2]];
}
$rDistance = $colorSchema[0] - $colorArray[0];
$gDistance = $colorSchema[1] - $colorArray[1];
$bDistance = $colorSchema[2] - $colorArray[2];

$distance = ($rDistance * .299) ** 2 + ($gDistance * .587) ** 2 + ($bDistance * .114) ** 2;

ksort($distances);
$distances[$colorIdentifier] = $distance;
}

$colorFound = reset($distances);
asort($distances);

list($r, $g, $b) = $colorFound;
$colorIdentifier = array_keys($distances)[0];

$color->initFromRgb($r, $g, $b);
$color->initFromRgb(...self::PALETTE[$colorIdentifier]);

return $color;
}
Expand Down

0 comments on commit 3ff734a

Please sign in to comment.