ColorQuantizer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. using System.Collections.ObjectModel;
  2. using ColorHelper;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Translates colors in an image into a Palette of up to 256 colors.
  6. /// </summary>
  7. public class ColorQuantizer
  8. {
  9. /// <summary>
  10. /// Gets the current colors in the palette based on the last call to
  11. /// <see cref="BuildPalette"/>.
  12. /// </summary>
  13. public IReadOnlyCollection<Color> Palette { get; private set; } = new List<Color> ();
  14. /// <summary>
  15. /// Gets or sets the maximum number of colors to put into the <see cref="Palette"/>.
  16. /// Defaults to 256 (the maximum for sixel images).
  17. /// </summary>
  18. public int MaxColors { get; set; } = 256;
  19. /// <summary>
  20. /// Gets or sets the algorithm used to map novel colors into existing
  21. /// palette colors (closest match). Defaults to <see cref="CIE94ColorDistance"/>
  22. /// </summary>
  23. public IColorDistance DistanceAlgorithm { get; set; } = new CIE94ColorDistance ();
  24. /// <summary>
  25. /// Gets or sets the algorithm used to build the <see cref="Palette"/>.
  26. /// Defaults to <see cref="MedianCutPaletteBuilder"/>
  27. /// </summary>
  28. public IPaletteBuilder PaletteBuildingAlgorithm { get; set; } = new MedianCutPaletteBuilder ();
  29. public void BuildPalette (Color [,] pixels)
  30. {
  31. List<Color> allColors = new List<Color> ();
  32. int width = pixels.GetLength (0);
  33. int height = pixels.GetLength (1);
  34. for (int x = 0; x < width; x++)
  35. {
  36. for (int y = 0; y < height; y++)
  37. {
  38. allColors.Add (pixels [x, y]);
  39. }
  40. }
  41. Palette = PaletteBuildingAlgorithm.BuildPalette(allColors,MaxColors);
  42. }
  43. public int GetNearestColor (Color toTranslate)
  44. {
  45. // Simple nearest color matching based on Euclidean distance in RGB space
  46. double minDistance = double.MaxValue;
  47. int nearestIndex = 0;
  48. for (var index = 0; index < Palette.Count; index++)
  49. {
  50. Color color = Palette.ElementAt(index);
  51. double distance = DistanceAlgorithm.CalculateDistance(color, toTranslate);
  52. if (distance < minDistance)
  53. {
  54. minDistance = distance;
  55. nearestIndex = index;
  56. }
  57. }
  58. return nearestIndex;
  59. }
  60. }
  61. public interface IPaletteBuilder
  62. {
  63. List<Color> BuildPalette (List<Color> colors, int maxColors);
  64. }
  65. /// <summary>
  66. /// Interface for algorithms that compute the relative distance between pairs of colors.
  67. /// This is used for color matching to a limited palette, such as in Sixel rendering.
  68. /// </summary>
  69. public interface IColorDistance
  70. {
  71. /// <summary>
  72. /// Computes a similarity metric between two <see cref="Color"/> instances.
  73. /// A larger value indicates more dissimilar colors, while a smaller value indicates more similar colors.
  74. /// The metric is internally consistent for the given algorithm.
  75. /// </summary>
  76. /// <param name="c1">The first color.</param>
  77. /// <param name="c2">The second color.</param>
  78. /// <returns>A numeric value representing the distance between the two colors.</returns>
  79. double CalculateDistance (Color c1, Color c2);
  80. }
  81. /// <summary>
  82. /// Calculates the distance between two colors using Euclidean distance in 3D RGB space.
  83. /// This measures the straight-line distance between the two points representing the colors.
  84. /// </summary>
  85. public class EuclideanColorDistance : IColorDistance
  86. {
  87. public double CalculateDistance (Color c1, Color c2)
  88. {
  89. int rDiff = c1.R - c2.R;
  90. int gDiff = c1.G - c2.G;
  91. int bDiff = c1.B - c2.B;
  92. return Math.Sqrt (rDiff * rDiff + gDiff * gDiff + bDiff * bDiff);
  93. }
  94. }
  95. public abstract class LabColorDistance : IColorDistance
  96. {
  97. // Reference white point for D65 illuminant (can be moved to constants)
  98. private const double RefX = 95.047;
  99. private const double RefY = 100.000;
  100. private const double RefZ = 108.883;
  101. // Conversion from RGB to Lab
  102. protected LabColor RgbToLab (Color c)
  103. {
  104. var xyz = ColorHelper.ColorConverter.RgbToXyz (new RGB (c.R, c.G, c.B));
  105. // Normalize XYZ values by reference white point
  106. double x = xyz.X / RefX;
  107. double y = xyz.Y / RefY;
  108. double z = xyz.Z / RefZ;
  109. // Apply the nonlinear transformation for Lab
  110. x = (x > 0.008856) ? Math.Pow (x, 1.0 / 3.0) : (7.787 * x) + (16.0 / 116.0);
  111. y = (y > 0.008856) ? Math.Pow (y, 1.0 / 3.0) : (7.787 * y) + (16.0 / 116.0);
  112. z = (z > 0.008856) ? Math.Pow (z, 1.0 / 3.0) : (7.787 * z) + (16.0 / 116.0);
  113. // Calculate Lab values
  114. double l = (116.0 * y) - 16.0;
  115. double a = 500.0 * (x - y);
  116. double b = 200.0 * (y - z);
  117. return new LabColor (l, a, b);
  118. }
  119. // LabColor class encapsulating L, A, and B values
  120. protected class LabColor
  121. {
  122. public double L { get; }
  123. public double A { get; }
  124. public double B { get; }
  125. public LabColor (double l, double a, double b)
  126. {
  127. L = l;
  128. A = a;
  129. B = b;
  130. }
  131. }
  132. /// <inheritdoc />
  133. public abstract double CalculateDistance (Color c1, Color c2);
  134. }
  135. /// <summary>
  136. /// This is the simplest method to measure color difference in the CIE Lab color space. The Euclidean distance in Lab
  137. /// space is more aligned with human perception than RGB space, as Lab attempts to model how humans perceive color differences.
  138. /// </summary>
  139. public class CIE76ColorDistance : LabColorDistance
  140. {
  141. public override double CalculateDistance (Color c1, Color c2)
  142. {
  143. var lab1 = RgbToLab (c1);
  144. var lab2 = RgbToLab (c2);
  145. // Euclidean distance in Lab color space
  146. return Math.Sqrt (Math.Pow (lab1.L - lab2.L, 2) + Math.Pow (lab1.A - lab2.A, 2) + Math.Pow (lab1.B - lab2.B, 2));
  147. }
  148. }
  149. /// <summary>
  150. /// CIE94 improves on CIE76 by introducing adjustments for chroma (color intensity) and lightness.
  151. /// This algorithm considers human visual perception more accurately by scaling differences in lightness and chroma.
  152. /// It is better but slower than <see cref="CIE76ColorDistance"/>.
  153. /// </summary>
  154. public class CIE94ColorDistance : LabColorDistance
  155. {
  156. // Constants for CIE94 formula (can be modified for different use cases like textiles or graphics)
  157. private const double kL = 1.0;
  158. private const double kC = 1.0;
  159. private const double kH = 1.0;
  160. public override double CalculateDistance (Color first, Color second)
  161. {
  162. var lab1 = RgbToLab (first);
  163. var lab2 = RgbToLab (second);
  164. // Delta L, A, B
  165. double deltaL = lab1.L - lab2.L;
  166. double deltaA = lab1.A - lab2.A;
  167. double deltaB = lab1.B - lab2.B;
  168. // Chroma values for both colors
  169. double c1 = Math.Sqrt (lab1.A * lab1.A + lab1.B * lab1.B);
  170. double c2 = Math.Sqrt (lab2.A * lab2.A + lab2.B * lab2.B);
  171. double deltaC = c1 - c2;
  172. // Delta H (calculated indirectly)
  173. double deltaH = Math.Sqrt (Math.Pow (deltaA, 2) + Math.Pow (deltaB, 2) - Math.Pow (deltaC, 2));
  174. // Scaling factors
  175. double sL = 1.0;
  176. double sC = 1.0 + 0.045 * c1;
  177. double sH = 1.0 + 0.015 * c1;
  178. // CIE94 color difference formula
  179. return Math.Sqrt (
  180. Math.Pow (deltaL / (kL * sL), 2) +
  181. Math.Pow (deltaC / (kC * sC), 2) +
  182. Math.Pow (deltaH / (kH * sH), 2)
  183. );
  184. }
  185. }
  186. class MedianCutPaletteBuilder : IPaletteBuilder
  187. {
  188. public List<Color> BuildPalette (List<Color> colors, int maxColors)
  189. {
  190. // Initial step: place all colors in one large box
  191. List<ColorBox> boxes = new List<ColorBox> { new ColorBox (colors) };
  192. // Keep splitting boxes until we have the desired number of colors
  193. while (boxes.Count < maxColors)
  194. {
  195. // Find the box with the largest range and split it
  196. ColorBox boxToSplit = FindBoxWithLargestRange (boxes);
  197. if (boxToSplit == null || boxToSplit.Colors.Count == 0)
  198. {
  199. break;
  200. }
  201. // Split the box into two smaller boxes
  202. var splitBoxes = SplitBox (boxToSplit);
  203. boxes.Remove (boxToSplit);
  204. boxes.AddRange (splitBoxes);
  205. }
  206. // Average the colors in each box to get the final palette
  207. return boxes.Select (box => box.GetAverageColor ()).ToList ();
  208. }
  209. // Find the box with the largest color range (R, G, or B)
  210. private ColorBox FindBoxWithLargestRange (List<ColorBox> boxes)
  211. {
  212. ColorBox largestRangeBox = null;
  213. int largestRange = 0;
  214. foreach (var box in boxes)
  215. {
  216. int range = box.GetColorRange ();
  217. if (range > largestRange)
  218. {
  219. largestRange = range;
  220. largestRangeBox = box;
  221. }
  222. }
  223. return largestRangeBox;
  224. }
  225. // Split a box at the median point in its largest color channel
  226. private List<ColorBox> SplitBox (ColorBox box)
  227. {
  228. List<ColorBox> result = new List<ColorBox> ();
  229. // Find the color channel with the largest range (R, G, or B)
  230. int channel = box.GetLargestChannel ();
  231. var sortedColors = box.Colors.OrderBy (c => GetColorChannelValue (c, channel)).ToList ();
  232. // Split the box at the median
  233. int medianIndex = sortedColors.Count / 2;
  234. var lowerHalf = sortedColors.Take (medianIndex).ToList ();
  235. var upperHalf = sortedColors.Skip (medianIndex).ToList ();
  236. result.Add (new ColorBox (lowerHalf));
  237. result.Add (new ColorBox (upperHalf));
  238. return result;
  239. }
  240. // Helper method to get the value of a color channel (R = 0, G = 1, B = 2)
  241. private static int GetColorChannelValue (Color color, int channel)
  242. {
  243. switch (channel)
  244. {
  245. case 0: return color.R;
  246. case 1: return color.G;
  247. case 2: return color.B;
  248. default: throw new ArgumentException ("Invalid channel index");
  249. }
  250. }
  251. // The ColorBox class to represent a subset of colors
  252. public class ColorBox
  253. {
  254. public List<Color> Colors { get; private set; }
  255. public ColorBox (List<Color> colors)
  256. {
  257. Colors = colors;
  258. }
  259. // Get the color channel with the largest range (0 = R, 1 = G, 2 = B)
  260. public int GetLargestChannel ()
  261. {
  262. int rRange = GetColorRangeForChannel (0);
  263. int gRange = GetColorRangeForChannel (1);
  264. int bRange = GetColorRangeForChannel (2);
  265. if (rRange >= gRange && rRange >= bRange)
  266. {
  267. return 0;
  268. }
  269. if (gRange >= rRange && gRange >= bRange)
  270. {
  271. return 1;
  272. }
  273. return 2;
  274. }
  275. // Get the range of colors for a given channel (0 = R, 1 = G, 2 = B)
  276. private int GetColorRangeForChannel (int channel)
  277. {
  278. int min = int.MaxValue, max = int.MinValue;
  279. foreach (var color in Colors)
  280. {
  281. int value = GetColorChannelValue (color, channel);
  282. if (value < min)
  283. {
  284. min = value;
  285. }
  286. if (value > max)
  287. {
  288. max = value;
  289. }
  290. }
  291. return max - min;
  292. }
  293. // Get the overall color range across all channels (for finding the box to split)
  294. public int GetColorRange ()
  295. {
  296. int rRange = GetColorRangeForChannel (0);
  297. int gRange = GetColorRangeForChannel (1);
  298. int bRange = GetColorRangeForChannel (2);
  299. return Math.Max (rRange, Math.Max (gRange, bRange));
  300. }
  301. // Calculate the average color in the box
  302. public Color GetAverageColor ()
  303. {
  304. int totalR = 0, totalG = 0, totalB = 0;
  305. foreach (var color in Colors)
  306. {
  307. totalR += color.R;
  308. totalG += color.G;
  309. totalB += color.B;
  310. }
  311. int count = Colors.Count;
  312. return new Color (totalR / count, totalG / count, totalB / count);
  313. }
  314. }
  315. }