ColorQuantizer.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. namespace Terminal.Gui;
  2. /// <summary>
  3. /// Translates colors in an image into a Palette of up to 256 colors.
  4. /// </summary>
  5. public class ColorQuantizer
  6. {
  7. private Dictionary<Color, int> colorFrequency;
  8. public List<Color> Palette;
  9. private const int MaxColors = 256;
  10. public ColorQuantizer ()
  11. {
  12. colorFrequency = new Dictionary<Color, int> ();
  13. Palette = new List<Color> ();
  14. }
  15. public void BuildPalette (Color [,] pixels, IPaletteBuilder builder)
  16. {
  17. List<Color> allColors = new List<Color> ();
  18. int width = pixels.GetLength (0);
  19. int height = pixels.GetLength (1);
  20. for (int x = 0; x < width; x++)
  21. {
  22. for (int y = 0; y < height; y++)
  23. {
  24. allColors.Add (pixels [x, y]);
  25. }
  26. }
  27. Palette = builder.BuildPalette(allColors,MaxColors);
  28. }
  29. public int GetNearestColor (Color toTranslate, IColorDistance distanceAlgorithm)
  30. {
  31. // Simple nearest color matching based on Euclidean distance in RGB space
  32. double minDistance = double.MaxValue;
  33. int nearestIndex = 0;
  34. for (var index = 0; index < Palette.Count; index++)
  35. {
  36. Color color = Palette [index];
  37. double distance = distanceAlgorithm.CalculateDistance(color, toTranslate);
  38. if (distance < minDistance)
  39. {
  40. minDistance = distance;
  41. nearestIndex = index;
  42. }
  43. }
  44. return nearestIndex;
  45. }
  46. }
  47. public interface IPaletteBuilder
  48. {
  49. List<Color> BuildPalette (List<Color> colors, int maxColors);
  50. }
  51. /// <summary>
  52. /// Interface for algorithms that compute the relative distance between pairs of colors.
  53. /// This is used for color matching to a limited palette, such as in Sixel rendering.
  54. /// </summary>
  55. public interface IColorDistance
  56. {
  57. /// <summary>
  58. /// Computes a similarity metric between two <see cref="Color"/> instances.
  59. /// A larger value indicates more dissimilar colors, while a smaller value indicates more similar colors.
  60. /// The metric is internally consistent for the given algorithm.
  61. /// </summary>
  62. /// <param name="c1">The first color.</param>
  63. /// <param name="c2">The second color.</param>
  64. /// <returns>A numeric value representing the distance between the two colors.</returns>
  65. double CalculateDistance (Color c1, Color c2);
  66. }
  67. /// <summary>
  68. /// Calculates the distance between two colors using Euclidean distance in 3D RGB space.
  69. /// This measures the straight-line distance between the two points representing the colors.
  70. /// </summary>
  71. public class EuclideanColorDistance : IColorDistance
  72. {
  73. public double CalculateDistance (Color c1, Color c2)
  74. {
  75. int rDiff = c1.R - c2.R;
  76. int gDiff = c1.G - c2.G;
  77. int bDiff = c1.B - c2.B;
  78. return Math.Sqrt (rDiff * rDiff + gDiff * gDiff + bDiff * bDiff);
  79. }
  80. }
  81. class MedianCutPaletteBuilder : IPaletteBuilder
  82. {
  83. public List<Color> BuildPalette (List<Color> colors, int maxColors)
  84. {
  85. // Initial step: place all colors in one large box
  86. List<ColorBox> boxes = new List<ColorBox> { new ColorBox (colors) };
  87. // Keep splitting boxes until we have the desired number of colors
  88. while (boxes.Count < maxColors)
  89. {
  90. // Find the box with the largest range and split it
  91. ColorBox boxToSplit = FindBoxWithLargestRange (boxes);
  92. if (boxToSplit == null || boxToSplit.Colors.Count == 0)
  93. {
  94. break;
  95. }
  96. // Split the box into two smaller boxes
  97. var splitBoxes = SplitBox (boxToSplit);
  98. boxes.Remove (boxToSplit);
  99. boxes.AddRange (splitBoxes);
  100. }
  101. // Average the colors in each box to get the final palette
  102. return boxes.Select (box => box.GetAverageColor ()).ToList ();
  103. }
  104. // Find the box with the largest color range (R, G, or B)
  105. private ColorBox FindBoxWithLargestRange (List<ColorBox> boxes)
  106. {
  107. ColorBox largestRangeBox = null;
  108. int largestRange = 0;
  109. foreach (var box in boxes)
  110. {
  111. int range = box.GetColorRange ();
  112. if (range > largestRange)
  113. {
  114. largestRange = range;
  115. largestRangeBox = box;
  116. }
  117. }
  118. return largestRangeBox;
  119. }
  120. // Split a box at the median point in its largest color channel
  121. private List<ColorBox> SplitBox (ColorBox box)
  122. {
  123. List<ColorBox> result = new List<ColorBox> ();
  124. // Find the color channel with the largest range (R, G, or B)
  125. int channel = box.GetLargestChannel ();
  126. var sortedColors = box.Colors.OrderBy (c => GetColorChannelValue (c, channel)).ToList ();
  127. // Split the box at the median
  128. int medianIndex = sortedColors.Count / 2;
  129. var lowerHalf = sortedColors.Take (medianIndex).ToList ();
  130. var upperHalf = sortedColors.Skip (medianIndex).ToList ();
  131. result.Add (new ColorBox (lowerHalf));
  132. result.Add (new ColorBox (upperHalf));
  133. return result;
  134. }
  135. // Helper method to get the value of a color channel (R = 0, G = 1, B = 2)
  136. private static int GetColorChannelValue (Color color, int channel)
  137. {
  138. switch (channel)
  139. {
  140. case 0: return color.R;
  141. case 1: return color.G;
  142. case 2: return color.B;
  143. default: throw new ArgumentException ("Invalid channel index");
  144. }
  145. }
  146. // The ColorBox class to represent a subset of colors
  147. public class ColorBox
  148. {
  149. public List<Color> Colors { get; private set; }
  150. public ColorBox (List<Color> colors)
  151. {
  152. Colors = colors;
  153. }
  154. // Get the color channel with the largest range (0 = R, 1 = G, 2 = B)
  155. public int GetLargestChannel ()
  156. {
  157. int rRange = GetColorRangeForChannel (0);
  158. int gRange = GetColorRangeForChannel (1);
  159. int bRange = GetColorRangeForChannel (2);
  160. if (rRange >= gRange && rRange >= bRange)
  161. {
  162. return 0;
  163. }
  164. if (gRange >= rRange && gRange >= bRange)
  165. {
  166. return 1;
  167. }
  168. return 2;
  169. }
  170. // Get the range of colors for a given channel (0 = R, 1 = G, 2 = B)
  171. private int GetColorRangeForChannel (int channel)
  172. {
  173. int min = int.MaxValue, max = int.MinValue;
  174. foreach (var color in Colors)
  175. {
  176. int value = GetColorChannelValue (color, channel);
  177. if (value < min)
  178. {
  179. min = value;
  180. }
  181. if (value > max)
  182. {
  183. max = value;
  184. }
  185. }
  186. return max - min;
  187. }
  188. // Get the overall color range across all channels (for finding the box to split)
  189. public int GetColorRange ()
  190. {
  191. int rRange = GetColorRangeForChannel (0);
  192. int gRange = GetColorRangeForChannel (1);
  193. int bRange = GetColorRangeForChannel (2);
  194. return Math.Max (rRange, Math.Max (gRange, bRange));
  195. }
  196. // Calculate the average color in the box
  197. public Color GetAverageColor ()
  198. {
  199. int totalR = 0, totalG = 0, totalB = 0;
  200. foreach (var color in Colors)
  201. {
  202. totalR += color.R;
  203. totalG += color.G;
  204. totalB += color.B;
  205. }
  206. int count = Colors.Count;
  207. return new Color (totalR / count, totalG / count, totalB / count);
  208. }
  209. }
  210. }