Find a color from a palette that most closely matches a given color. Args: color (Tuple[int, int, int]): RGB components in range 0 > 255. Returns: int: Index of closes matching color.
(self, color: Tuple[int, int, int])
| 43 | # This is somewhat inefficient and needs caching |
| 44 | @lru_cache(maxsize=1024) |
| 45 | def match(self, color: Tuple[int, int, int]) -> int: |
| 46 | """Find a color from a palette that most closely matches a given color. |
| 47 | |
| 48 | Args: |
| 49 | color (Tuple[int, int, int]): RGB components in range 0 > 255. |
| 50 | |
| 51 | Returns: |
| 52 | int: Index of closes matching color. |
| 53 | """ |
| 54 | red1, green1, blue1 = color |
| 55 | _sqrt = sqrt |
| 56 | get_color = self._colors.__getitem__ |
| 57 | |
| 58 | def get_color_distance(index: int) -> float: |
| 59 | """Get the distance to a color.""" |
| 60 | red2, green2, blue2 = get_color(index) |
| 61 | red_mean = (red1 + red2) // 2 |
| 62 | red = red1 - red2 |
| 63 | green = green1 - green2 |
| 64 | blue = blue1 - blue2 |
| 65 | return _sqrt( |
| 66 | (((512 + red_mean) * red * red) >> 8) |
| 67 | + 4 * green * green |
| 68 | + (((767 - red_mean) * blue * blue) >> 8) |
| 69 | ) |
| 70 | |
| 71 | min_index = min(range(len(self._colors)), key=get_color_distance) |
| 72 | return min_index |
| 73 | |
| 74 | |
| 75 | if __name__ == "__main__": # pragma: no cover |
no outgoing calls