convert.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # I could not find a single decent RGB -> CIELUV conversion library out there
  2. def rescale_and_linearize(component: int) -> float:
  3. # takes an sRGB color component [0,255]
  4. # first rescales to [0,1]
  5. # then linearizes according to some CIEXYZ stuff I don't understand
  6. # then rescales to [0, 100]
  7. component /= 255
  8. linearized = component / 12.92 if component <= 0.04045 else ((component + 0.055) / 1.055) ** 2.4
  9. return 100 * linearized
  10. # conversion values I also do not understand
  11. # pulled from https://www.image-engineering.de/library/technotes/958-how-to-convert-between-srgb-and-ciexyz
  12. # instead of easy rgb, since it seemed to give more accurate values
  13. rgb_to_xyz_matrix = [
  14. [0.4124564, 0.3575761, 0.1804375],
  15. [0.2126729, 0.7151522, 0.0721750],
  16. [0.0193339, 0.1191920, 0.9503041],
  17. ]
  18. # reference values I also also do not understand
  19. # pulled from easy rgb
  20. # note X and Y here have nothing to do with the X and Y metrics below
  21. ref_x = 95.047
  22. ref_y = 100.000
  23. ref_z = 108.883
  24. ref_denom = ref_x + 15 * ref_y + 3 * ref_z
  25. ref_u = 4 * ref_x / ref_denom
  26. ref_v = 9 * ref_y / ref_denom
  27. def rgb_to_cieluv(r: int, g: int, b: int) -> tuple[float, float, float]:
  28. # accepts RGB (components [0, 255])
  29. # converts to CIE LUV (components [0, 1])
  30. # math taken from http://www.easyrgb.com/en/math.php
  31. # RGB (components [0, 255]) -> XYZ (components [0, 100])
  32. # X, Y and Z output refer to a D65/2° standard illuminant.
  33. sr, sg, sb = (rescale_and_linearize(c) for c in (r, g, b))
  34. x, y, z = (cr * sr + cg * sg + cb * sb for cr, cg, cb in rgb_to_xyz_matrix)
  35. # XYZ (components [0, 100]) -> LUV (components [0, 100])
  36. uv_denom = x + 15 * y + 3 * z
  37. u = 4 * x / uv_denom
  38. v = 9 * y / uv_denom
  39. if y > 0.8856:
  40. yprime = (y / 100) ** (1/3)
  41. else:
  42. yprime = (y / 100) * 7.787 + (16/116)
  43. lstar = 116 * yprime - 16
  44. lstar_factor = 13 * lstar
  45. return lstar, lstar_factor * (u - ref_u), lstar_factor * (v - ref_v)