color_utils.py 946 B

123456789101112131415161718192021222324
  1. """Color comparison utilities for RFID/firmware color matching."""
  2. def colors_similar(hex_a: str, hex_b: str, threshold: int = 50) -> bool:
  3. """Compare two RRGGBB(AA) hex colors with tolerance for RFID/firmware variations.
  4. Uses Euclidean RGB distance. Alpha channel (bytes 7-8) is ignored.
  5. Default threshold of 50 accommodates typical RFID read variations
  6. (e.g. 7CC4D5 vs 56B7E6 = distance ~43.6) while rejecting clearly
  7. different colors (e.g. red vs blue = distance ~360).
  8. """
  9. a = hex_a.strip().upper()
  10. b = hex_b.strip().upper()
  11. if a == b:
  12. return True
  13. if len(a) < 6 or len(b) < 6:
  14. return False
  15. try:
  16. ra, ga, ba = int(a[0:2], 16), int(a[2:4], 16), int(a[4:6], 16)
  17. rb, gb, bb = int(b[0:2], 16), int(b[2:4], 16), int(b[4:6], 16)
  18. except ValueError:
  19. return False
  20. dist = ((ra - rb) ** 2 + (ga - gb) ** 2 + (ba - bb) ** 2) ** 0.5
  21. return dist <= threshold