ColorQuantizer.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Collections.Concurrent;
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// Translates colors in an image into a Palette of up to <see cref="MaxColors"/> colors (typically 256).
  5. /// </summary>
  6. public class ColorQuantizer
  7. {
  8. /// <summary>
  9. /// Gets the current colors in the palette based on the last call to
  10. /// <see cref="BuildPalette"/>.
  11. /// </summary>
  12. public IReadOnlyCollection<Color> Palette { get; private set; } = new List<Color> ();
  13. /// <summary>
  14. /// Gets or sets the maximum number of colors to put into the <see cref="Palette"/>.
  15. /// Defaults to 256 (the maximum for sixel images).
  16. /// </summary>
  17. public int MaxColors { get; set; } = 256;
  18. /// <summary>
  19. /// Gets or sets the algorithm used to map novel colors into existing
  20. /// palette colors (closest match). Defaults to <see cref="EuclideanColorDistance"/>
  21. /// </summary>
  22. public IColorDistance DistanceAlgorithm { get; set; } = new EuclideanColorDistance ();
  23. /// <summary>
  24. /// Gets or sets the algorithm used to build the <see cref="Palette"/>.
  25. /// </summary>
  26. public IPaletteBuilder PaletteBuildingAlgorithm { get; set; } = new PopularityPaletteWithThreshold (new EuclideanColorDistance (),8) ;
  27. private readonly ConcurrentDictionary<Color, int> _nearestColorCache = new ();
  28. public void BuildPalette (Color [,] pixels)
  29. {
  30. List<Color> allColors = new List<Color> ();
  31. int width = pixels.GetLength (0);
  32. int height = pixels.GetLength (1);
  33. for (int x = 0; x < width; x++)
  34. {
  35. for (int y = 0; y < height; y++)
  36. {
  37. allColors.Add (pixels [x, y]);
  38. }
  39. }
  40. _nearestColorCache.Clear ();
  41. Palette = PaletteBuildingAlgorithm.BuildPalette (allColors, MaxColors);
  42. }
  43. public int GetNearestColor (Color toTranslate)
  44. {
  45. if (_nearestColorCache.TryGetValue (toTranslate, out var cachedAnswer))
  46. {
  47. return cachedAnswer;
  48. }
  49. // Simple nearest color matching based on DistanceAlgorithm
  50. double minDistance = double.MaxValue;
  51. int nearestIndex = 0;
  52. for (var index = 0; index < Palette.Count; index++)
  53. {
  54. Color color = Palette.ElementAt (index);
  55. double distance = DistanceAlgorithm.CalculateDistance (color, toTranslate);
  56. if (distance < minDistance)
  57. {
  58. minDistance = distance;
  59. nearestIndex = index;
  60. }
  61. }
  62. _nearestColorCache.TryAdd (toTranslate, nearestIndex);
  63. return nearestIndex;
  64. }
  65. }