ColorQuantizer.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 
  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 (),50) ;
  27. public void BuildPalette (Color [,] pixels)
  28. {
  29. List<Color> allColors = new List<Color> ();
  30. int width = pixels.GetLength (0);
  31. int height = pixels.GetLength (1);
  32. for (int x = 0; x < width; x++)
  33. {
  34. for (int y = 0; y < height; y++)
  35. {
  36. allColors.Add (pixels [x, y]);
  37. }
  38. }
  39. Palette = PaletteBuildingAlgorithm.BuildPalette (allColors, MaxColors);
  40. }
  41. public int GetNearestColor (Color toTranslate)
  42. {
  43. // Simple nearest color matching based on DistanceAlgorithm
  44. double minDistance = double.MaxValue;
  45. int nearestIndex = 0;
  46. for (var index = 0; index < Palette.Count; index++)
  47. {
  48. Color color = Palette.ElementAt (index);
  49. double distance = DistanceAlgorithm.CalculateDistance (color, toTranslate);
  50. if (distance < minDistance)
  51. {
  52. minDistance = distance;
  53. nearestIndex = index;
  54. }
  55. }
  56. return nearestIndex;
  57. }
  58. }