FrameXlabs commited on
Commit
573a02d
·
verified ·
1 Parent(s): be285e0

Add trout/palette.py

Browse files
Files changed (1) hide show
  1. trout/palette.py +303 -0
trout/palette.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trout palette: OKLab colour math, frequency-weighted k-means and RGBA<->token mapping.
2
+
3
+ Token 0 is always "transparent"; tokens 1..K-1 are opaque sRGB colours. The palette is
4
+ built from scratch on the training data: unique opaque colours are clustered in OKLab
5
+ space with frequency-weighted k-means (k-means++ seeding, centroids snapped to real
6
+ data colours so exact pure colours survive quantisation).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import math
13
+ from typing import Optional
14
+
15
+ import numpy as np
16
+ import torch
17
+
18
+ TRANSPARENT = 0
19
+
20
+
21
+ # ---------------------------------------------------------------- OKLab conversions
22
+
23
+ def _srgb_to_linear(c):
24
+ if isinstance(c, torch.Tensor):
25
+ return torch.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
26
+ return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
27
+
28
+
29
+ def _linear_to_srgb(c):
30
+ if isinstance(c, torch.Tensor):
31
+ c = c.clamp(0, 1)
32
+ return torch.where(c <= 0.0031308, 12.92 * c, 1.055 * c.clamp(min=1e-12) ** (1 / 2.4) - 0.055)
33
+ c = np.clip(c, 0, 1)
34
+ return np.where(c <= 0.0031308, 12.92 * c, 1.055 * np.maximum(c, 1e-12) ** (1 / 2.4) - 0.055)
35
+
36
+
37
+ def srgb_to_oklab(rgb):
38
+ """rgb: (..., 3) in [0, 255]. Returns float (..., 3) OKLab."""
39
+ is_t = isinstance(rgb, torch.Tensor)
40
+ x = rgb.float() / 255.0 if is_t else np.asarray(rgb, dtype=np.float64) / 255.0
41
+ lin = _srgb_to_linear(x)
42
+ r, g, b = lin[..., 0], lin[..., 1], lin[..., 2]
43
+ l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b
44
+ m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b
45
+ s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b
46
+ if is_t:
47
+ l_, m_, s_ = torch.pow(l.clamp(min=0), 1 / 3), torch.pow(m.clamp(min=0), 1 / 3), torch.pow(s.clamp(min=0), 1 / 3)
48
+ else:
49
+ l_, m_, s_ = np.cbrt(l), np.cbrt(m), np.cbrt(s)
50
+ L = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_
51
+ A = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_
52
+ B = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_
53
+ if is_t:
54
+ return torch.stack([L, A, B], -1).float()
55
+ return np.stack([L, A, B], -1).astype(np.float32)
56
+
57
+
58
+ def oklab_to_srgb(lab):
59
+ """lab: (..., 3) OKLab -> float sRGB in [0, 255]."""
60
+ is_t = isinstance(lab, torch.Tensor)
61
+ L, A, B = lab[..., 0], lab[..., 1], lab[..., 2]
62
+ l_ = L + 0.3963377774 * A + 0.2158037573 * B
63
+ m_ = L - 0.1055613458 * A - 0.0638541728 * B
64
+ s_ = L - 0.0894841775 * A - 1.2914855480 * B
65
+ l, m, s = l_ ** 3, m_ ** 3, s_ ** 3
66
+ r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s
67
+ g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s
68
+ b = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s
69
+ out = torch.stack([r, g, b], -1) if is_t else np.stack([r, g, b], -1)
70
+ return _linear_to_srgb(out) * 255.0
71
+
72
+
73
+ def rgb_to_key(rgb: np.ndarray) -> np.ndarray:
74
+ rgb = rgb.astype(np.int64)
75
+ return (rgb[..., 0] << 16) | (rgb[..., 1] << 8) | rgb[..., 2]
76
+
77
+
78
+ def key_to_rgb(key: np.ndarray) -> np.ndarray:
79
+ key = np.asarray(key, dtype=np.int64)
80
+ return np.stack([(key >> 16) & 255, (key >> 8) & 255, key & 255], -1).astype(np.uint8)
81
+
82
+
83
+ # ---------------------------------------------------------------- nearest / k-means
84
+
85
+ def nearest_centroids(points: torch.Tensor, centers: torch.Tensor, chunk: int = 1 << 18):
86
+ """(index, squared distance) of the nearest center for each point, chunked."""
87
+ idx = torch.empty(points.shape[0], dtype=torch.long)
88
+ dist = torch.empty(points.shape[0], dtype=points.dtype)
89
+ c2 = (centers * centers).sum(1)
90
+ for s in range(0, points.shape[0], chunk):
91
+ p = points[s:s + chunk]
92
+ d = (p * p).sum(1, keepdim=True) - 2 * p @ centers.T + c2[None]
93
+ dv, di = d.min(1)
94
+ idx[s:s + chunk] = di
95
+ dist[s:s + chunk] = dv.clamp(min=0)
96
+ return idx, dist
97
+
98
+
99
+ def weighted_kmeans(x: torch.Tensor, w: torch.Tensor, k: int, iters: int = 60, seed: int = 0) -> torch.Tensor:
100
+ """Frequency-weighted k-means with weighted k-means++ init. x: (U, 3), w: (U,)."""
101
+ g = torch.Generator().manual_seed(seed)
102
+ U = x.shape[0]
103
+ w = w.float()
104
+ first = torch.multinomial(w, 1, generator=g).item()
105
+ centers = [x[first]]
106
+ d2 = ((x - x[first]) ** 2).sum(1)
107
+ for _ in range(1, k):
108
+ p = (w * d2).double()
109
+ if p.sum() <= 0:
110
+ j = torch.randint(U, (1,), generator=g).item()
111
+ else:
112
+ j = torch.multinomial(p, 1, generator=g).item()
113
+ centers.append(x[j])
114
+ d2 = torch.minimum(d2, ((x - x[j]) ** 2).sum(1))
115
+ C = torch.stack(centers).clone()
116
+ for _ in range(iters):
117
+ assign, dist = nearest_centroids(x, C)
118
+ sums = torch.zeros_like(C).index_add_(0, assign, x * w[:, None])
119
+ ws = torch.zeros(k).index_add_(0, assign, w)
120
+ empty = ws <= 0
121
+ newC = torch.where(empty[:, None], C, sums / ws.clamp(min=1e-12)[:, None])
122
+ if empty.any(): # re-seed empty clusters at the worst-fit points
123
+ worst = torch.topk(w * dist, int(empty.sum().item())).indices
124
+ newC[empty] = x[worst]
125
+ shift = (newC - C).norm(dim=1).max().item()
126
+ C = newC
127
+ if shift < 1e-7:
128
+ break
129
+ return C
130
+
131
+
132
+ # ---------------------------------------------------------------- the palette
133
+
134
+ class Palette:
135
+ """A fixed colour table. Index 0 = transparent; 1..K-1 = opaque sRGB colours."""
136
+
137
+ def __init__(self, colors, name: str = "custom"):
138
+ colors = np.asarray(colors, dtype=np.uint8).reshape(-1, 3).copy()
139
+ colors[TRANSPARENT] = 0
140
+ self.colors = colors
141
+ self.name = name
142
+ lab = srgb_to_oklab(colors).astype(np.float32)
143
+ lab[TRANSPARENT] = 0.0
144
+ self.lab = lab
145
+
146
+ @property
147
+ def size(self) -> int:
148
+ return int(self.colors.shape[0])
149
+
150
+ def __len__(self) -> int:
151
+ return self.size
152
+
153
+ def rgba_table(self) -> np.ndarray:
154
+ t = np.concatenate([self.colors, np.full((self.size, 1), 255, np.uint8)], 1)
155
+ t[TRANSPARENT] = 0
156
+ return t
157
+
158
+ # ---- conversion ----
159
+ def tokens_to_rgba(self, tokens) -> np.ndarray:
160
+ if isinstance(tokens, torch.Tensor):
161
+ tokens = tokens.detach().cpu().numpy()
162
+ tokens = np.asarray(tokens).astype(np.int64)
163
+ table = np.concatenate([self.rgba_table(), np.array([[255, 0, 255, 255]], np.uint8)], 0)
164
+ return table[np.clip(tokens, 0, self.size)]
165
+
166
+ def nearest_index(self, rgb: np.ndarray) -> np.ndarray:
167
+ """Nearest opaque palette entry (1..K-1) in OKLab for an (M, 3) uint8 array."""
168
+ if rgb.shape[0] == 0:
169
+ return np.zeros(0, np.int64)
170
+ pts = torch.from_numpy(srgb_to_oklab(rgb))
171
+ cen = torch.from_numpy(self.lab[1:])
172
+ idx, _ = nearest_centroids(pts, cen)
173
+ return idx.numpy() + 1
174
+
175
+ def build_lut(self, keys: np.ndarray) -> dict:
176
+ keys = np.unique(np.asarray(keys, dtype=np.int64))
177
+ idx = self.nearest_index(key_to_rgb(keys))
178
+ return {"keys": keys, "idx": idx.astype(np.uint16)}
179
+
180
+ def quantize_rgba(self, rgba: np.ndarray, alpha_threshold: int = 128, lut: Optional[dict] = None) -> np.ndarray:
181
+ """uint8 RGBA (..., 4) -> uint16 tokens (...). alpha < threshold becomes transparent."""
182
+ rgba = np.asarray(rgba)
183
+ shape = rgba.shape[:-1]
184
+ flat = rgba.reshape(-1, 4)
185
+ opaque = flat[:, 3] >= alpha_threshold
186
+ out = np.zeros(flat.shape[0], np.uint16)
187
+ if opaque.any():
188
+ keys = rgb_to_key(flat[opaque, :3])
189
+ if lut is None:
190
+ lut = self.build_lut(keys)
191
+ pos = np.searchsorted(lut["keys"], keys)
192
+ pos = np.clip(pos, 0, len(lut["keys"]) - 1)
193
+ hit = lut["keys"][pos] == keys
194
+ vals = lut["idx"][pos]
195
+ if not hit.all():
196
+ miss = ~hit
197
+ vals = vals.copy()
198
+ vals[miss] = self.nearest_index(key_to_rgb(keys[miss]))
199
+ out[opaque] = vals
200
+ return out.reshape(shape)
201
+
202
+ # ---- perceptual label smoothing ----
203
+ def soft_targets(self, tau: float = 0.05) -> torch.Tensor:
204
+ """(K, K) row-stochastic matrix over opaque colours from OKLab distances."""
205
+ lab = torch.from_numpy(self.lab).double()
206
+ d2 = torch.cdist(lab, lab) ** 2
207
+ logits = -d2 / (tau * tau)
208
+ logits[:, TRANSPARENT] = -math.inf
209
+ S = torch.softmax(logits, dim=1)
210
+ S[TRANSPARENT] = 0.0
211
+ S[TRANSPARENT, TRANSPARENT] = 1.0
212
+ return S.float()
213
+
214
+ # ---- persistence ----
215
+ def to_dict(self) -> dict:
216
+ return {"name": self.name, "colors": self.colors.tolist()}
217
+
218
+ def save(self, path: str) -> None:
219
+ with open(path, "w") as f:
220
+ json.dump(self.to_dict(), f)
221
+
222
+ @classmethod
223
+ def from_dict(cls, d: dict) -> "Palette":
224
+ return cls(np.array(d["colors"], dtype=np.uint8), name=d.get("name", "custom"))
225
+
226
+ @classmethod
227
+ def load(cls, path: str) -> "Palette":
228
+ with open(path) as f:
229
+ return cls.from_dict(json.load(f))
230
+
231
+ def preview(self, cell: int = 12, cols: int = 32):
232
+ from PIL import Image
233
+ rows = math.ceil(self.size / cols)
234
+ img = np.full((rows * cell, cols * cell, 3), 255, np.uint8)
235
+ for i in range(self.size):
236
+ r, c = divmod(i, cols)
237
+ if i == TRANSPARENT:
238
+ yy, xx = np.mgrid[0:cell, 0:cell]
239
+ img[r * cell:(r + 1) * cell, c * cell:(c + 1) * cell] = np.where(
240
+ (((yy // 3) + (xx // 3)) % 2 == 0)[..., None], 200, 140)
241
+ else:
242
+ img[r * cell:(r + 1) * cell, c * cell:(c + 1) * cell] = self.colors[i]
243
+ return Image.fromarray(img)
244
+
245
+ # ---- builder ----
246
+ @classmethod
247
+ def build_kmeans(cls, keys: np.ndarray, counts: np.ndarray, size: int = 512,
248
+ weight_power: float = 0.5, iters: int = 60, seed: int = 0) -> "Palette":
249
+ """Data-driven palette: 1 transparent + size-1 opaque colours."""
250
+ keys = np.asarray(keys, dtype=np.int64)
251
+ counts = np.asarray(counts, dtype=np.float64)
252
+ k = size - 1
253
+ rgb = key_to_rgb(keys)
254
+ if keys.shape[0] <= k:
255
+ colors = np.concatenate([np.zeros((1, 3), np.uint8), rgb], 0)
256
+ return cls._sorted(colors, name=f"exact{len(colors)}")
257
+ x = torch.from_numpy(srgb_to_oklab(rgb))
258
+ w = torch.from_numpy(counts ** weight_power)
259
+ C = weighted_kmeans(x, w, k, iters=iters, seed=seed)
260
+ snap_idx, _ = nearest_centroids(C, x)
261
+ snap_idx = snap_idx.numpy()
262
+ chosen = list(dict.fromkeys(snap_idx.tolist()))
263
+ if len(chosen) < k: # fill duplicates with the worst-represented data colours
264
+ cen = x[torch.as_tensor(chosen)]
265
+ _, dist = nearest_centroids(x, cen)
266
+ order = torch.argsort(w * dist, descending=True).numpy()
267
+ for j in order:
268
+ if len(chosen) >= k:
269
+ break
270
+ if int(j) not in chosen:
271
+ chosen.append(int(j))
272
+ colors = np.concatenate([np.zeros((1, 3), np.uint8), rgb[np.array(chosen[:k])]], 0)
273
+ return cls._sorted(colors, name=f"kmeans{size}")
274
+
275
+ @classmethod
276
+ def _sorted(cls, colors: np.ndarray, name: str) -> "Palette":
277
+ """Order opaque colours by hue bucket then lightness for a readable preview."""
278
+ opaque = colors[1:]
279
+ lab = srgb_to_oklab(opaque)
280
+ chroma = np.sqrt(lab[:, 1] ** 2 + lab[:, 2] ** 2)
281
+ hue = np.arctan2(lab[:, 2], lab[:, 1])
282
+ bucket = np.where(chroma < 0.03, -1, np.floor((hue + np.pi) / (2 * np.pi) * 12)).astype(np.int64)
283
+ order = np.lexsort((lab[:, 0], bucket))
284
+ return cls(np.concatenate([colors[:1], opaque[order]], 0), name=name)
285
+
286
+
287
+ def quantization_report(palette: Palette, rgba: np.ndarray, tokens: np.ndarray,
288
+ max_pixels: int = 2_000_000) -> dict:
289
+ """Mean / p95 OKLab error of quantisation on opaque pixels."""
290
+ flat = rgba.reshape(-1, 4)
291
+ tok = tokens.reshape(-1)
292
+ if flat.shape[0] > max_pixels:
293
+ sel = np.random.default_rng(0).integers(0, flat.shape[0], max_pixels)
294
+ flat, tok = flat[sel], tok[sel]
295
+ op = flat[:, 3] >= 128
296
+ if not op.any():
297
+ return {"mean_dE": 0.0, "p95_dE": 0.0, "exact_frac": 1.0}
298
+ src = srgb_to_oklab(flat[op, :3])
299
+ dst = palette.lab[tok[op].astype(np.int64)]
300
+ d = np.linalg.norm(src - dst, axis=1)
301
+ exact = (palette.colors[tok[op].astype(np.int64)] == flat[op, :3]).all(1)
302
+ return {"mean_dE": float(d.mean()), "p95_dE": float(np.percentile(d, 95)),
303
+ "max_dE": float(d.max()), "exact_frac": float(exact.mean())}