LabColorDistance.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using ColorHelper;
  2. namespace Terminal.Gui.Drawing.Quant;
  3. public abstract class LabColorDistance : IColorDistance
  4. {
  5. // Reference white point for D65 illuminant (can be moved to constants)
  6. private const double RefX = 95.047;
  7. private const double RefY = 100.000;
  8. private const double RefZ = 108.883;
  9. // Conversion from RGB to Lab
  10. protected LabColor RgbToLab (Color c)
  11. {
  12. var xyz = ColorHelper.ColorConverter.RgbToXyz (new RGB (c.R, c.G, c.B));
  13. // Normalize XYZ values by reference white point
  14. double x = xyz.X / RefX;
  15. double y = xyz.Y / RefY;
  16. double z = xyz.Z / RefZ;
  17. // Apply the nonlinear transformation for Lab
  18. x = x > 0.008856 ? Math.Pow (x, 1.0 / 3.0) : 7.787 * x + 16.0 / 116.0;
  19. y = y > 0.008856 ? Math.Pow (y, 1.0 / 3.0) : 7.787 * y + 16.0 / 116.0;
  20. z = z > 0.008856 ? Math.Pow (z, 1.0 / 3.0) : 7.787 * z + 16.0 / 116.0;
  21. // Calculate Lab values
  22. double l = 116.0 * y - 16.0;
  23. double a = 500.0 * (x - y);
  24. double b = 200.0 * (y - z);
  25. return new LabColor (l, a, b);
  26. }
  27. // LabColor class encapsulating L, A, and B values
  28. protected class LabColor
  29. {
  30. public double L { get; }
  31. public double A { get; }
  32. public double B { get; }
  33. public LabColor (double l, double a, double b)
  34. {
  35. L = l;
  36. A = a;
  37. B = b;
  38. }
  39. }
  40. /// <inheritdoc />
  41. public abstract double CalculateDistance (Color c1, Color c2);
  42. }