analyze.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import math
  2. from dataclasses import dataclass
  3. from itertools import combinations
  4. import numpy as np
  5. from PIL import Image
  6. from scipy.cluster import vq
  7. # https://en.wikipedia.org/wiki/SRGB#Transformation
  8. linearize_srgb = np.vectorize(
  9. lambda v: (v / 12.92) if v <= 0.04045 else (((v + 0.055) / 1.055) ** 2.4)
  10. )
  11. delinearize_lrgb = np.vectorize(
  12. lambda v: (v * 12.92) if v <= 0.0031308 else ((v ** (1 / 2.4)) * 1.055 - 0.055)
  13. )
  14. # https://mina86.com/2019/srgb-xyz-matrix/
  15. RGB_TO_XYZ = np.array([
  16. [33786752 / 81924984, 29295110 / 81924984, 14783675 / 81924984],
  17. [8710647 / 40962492, 29295110 / 40962492, 2956735 / 40962492],
  18. [4751262 / 245774952, 29295110 / 245774952, 233582065 / 245774952],
  19. ])
  20. XYZ_TO_RGB = [
  21. [4277208 / 1319795, -2028932 / 1319795, -658032 / 1319795],
  22. [-70985202 / 73237775, 137391598 / 73237775, 3043398 / 73237775],
  23. [164508 / 2956735, -603196 / 2956735, 3125652 / 2956735],
  24. ]
  25. # https://bottosson.github.io/posts/oklab/
  26. XYZ_TO_LMS = np.array([
  27. [0.8189330101, 0.3618667424, -0.1288597137],
  28. [0.0329845436, 0.9293118715, 0.0361456387],
  29. [0.0482003018, 0.2643662691, 0.6338517070],
  30. ])
  31. RGB_TO_LMS = XYZ_TO_LMS @ RGB_TO_XYZ
  32. LMS_TO_RGB = np.linalg.inv(RGB_TO_LMS)
  33. LMS_TO_OKLAB = np.array([
  34. [0.2104542553, 0.7936177850, -0.0040720468],
  35. [1.9779984951, -2.4285922050, 0.4505937099],
  36. [0.0259040371, 0.7827717662, -0.8086757660],
  37. ])
  38. OKLAB_TO_LMS = np.linalg.inv(LMS_TO_OKLAB)
  39. def oklab2hex(pixel: np.array) -> str:
  40. # no need for a vectorized version, this is only for providing the mean hex
  41. return "#" + "".join(f"{int(x * 255):02X}" for x in delinearize_lrgb(((pixel @ OKLAB_TO_LMS.T) ** 3) @ LMS_TO_RGB.T))
  42. def srgb2oklab(pixels: np.array) -> np.array:
  43. return (linearize_srgb(pixels / 255) @ RGB_TO_LMS.T) ** (1 / 3) @ LMS_TO_OKLAB.T
  44. @dataclass
  45. class Stats:
  46. size: int
  47. proportion: int
  48. variance: float
  49. stddev: float
  50. hex: str
  51. Lbar: float
  52. abar: float
  53. bbar: float
  54. Cbar: float
  55. hbar: float
  56. Lhat: float
  57. ahat: float
  58. bhat: float
  59. def calc_statistics(pixels: np.array, total_size=None) -> Stats:
  60. # mean pixel of the image, (L-bar, a-bar, b-bar)
  61. mean = pixels.mean(axis=0)
  62. # square each component
  63. squared = pixels ** 2
  64. # Euclidean norm squared by summing squared components
  65. sqnorms = squared.sum(axis=1)
  66. # mean pixel of normalized image, (L-hat, a-hat, b-hat)
  67. tilt = (pixels / np.sqrt(sqnorms)[:, np.newaxis]).mean(axis=0)
  68. # variance = mean(||p||^2) - ||mean(p)||^2
  69. variance = sqnorms.mean(axis=0) - sum(mean ** 2)
  70. # chroma^2 = a^2 + b^2
  71. chroma = np.sqrt(squared[:, 1:].sum(axis=1))
  72. # hue = atan2(b, a), but we need a circular mean
  73. # https://en.wikipedia.org/wiki/Circular_mean#Definition
  74. # cos(atan2(b, a)) = a / sqrt(a^2 + b^2) = a / chroma
  75. # sin(atan2(b, a)) = b / sqrt(a^2 + b^2) = b / chroma
  76. hue = math.atan2(*(pixels[:, [2, 1]] / chroma[:, np.newaxis]).mean(axis=0))
  77. return Stats(
  78. size=len(pixels),
  79. proportion=1 if total_size is None else (len(pixels) / total_size),
  80. variance=variance,
  81. stddev=math.sqrt(variance),
  82. hex=oklab2hex(mean),
  83. Lbar=mean[0],
  84. abar=mean[1],
  85. bbar=mean[2],
  86. Cbar=chroma.mean(axis=0),
  87. hbar=(hue * 180 / math.pi) % 360,
  88. Lhat=tilt[0],
  89. ahat=tilt[1],
  90. bhat=tilt[2],
  91. )
  92. def find_clusters(pixels: np.array, cluster_attempts=5, seed=0) -> list[Stats]:
  93. means, labels = max(
  94. (
  95. # Try k = 2, 3, and 4, and try a few times for each
  96. vq.kmeans2(pixels.astype(float), k, minit="++", seed=seed + i)
  97. for k in (2, 3, 4)
  98. for i in range(cluster_attempts)
  99. ),
  100. key=lambda c:
  101. # Evaluate clustering by seeing the average distance in the ab-plane
  102. # between the centers. Maximizing this means the clusters are highly
  103. # distinct, which gives a sense of which k was best.
  104. (np.array([m1 - m2 for m1, m2 in combinations(c[0][:, 1:], 2)]) ** 2)
  105. .sum(axis=1)
  106. .mean(axis=0)
  107. )
  108. return [calc_statistics(pixels[labels == i], len(pixels)) for i in range(len(means))]
  109. def get_pixels(img: Image.Image) -> np.array:
  110. rgb = []
  111. for fr in range(getattr(img, "n_frames", 1)):
  112. img.seek(fr)
  113. rgb += [
  114. [r, g, b]
  115. for r, g, b, a in img.convert("RGBA").getdata()
  116. if a > 0 and (r, g, b) != (0, 0, 0)
  117. ]
  118. return srgb2oklab(np.array(rgb))
  119. if __name__ == "__main__":
  120. print("TODO")