@xprite/pixelate 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- import { rgbToLab, labToRgb } from "./color-lab.js";
1
+ import { oklabToRgb, rgbToOklab } from "./quantization.js";
2
2
  import { PixelationDither } from "./types.js";
3
3
  /**
4
4
  * Optional "snap palette" step for a recovered (small) image: collapse the many near-shades that
5
5
  * AI art and JPEG sources leave behind into a clean, flat palette, or snap to a palette the user
6
6
  * supplies. Rare-but-important colours (skin tones, highlights) are kept by two rules:
7
- * - only near-duplicates (within `MERGE_DELTA` in CIE Lab) are ever merged without a budget, and
7
+ * - only near-duplicates (within the OKLab distance threshold) are ever merged without a budget, and
8
8
  * - k-means is seeded by weighted farthest-point selection, so a colour far from everything else
9
9
  * gets its own palette entry before a frequent shade that is only a little different.
10
10
  * Alpha is never clustered: each pixel keeps its own opacity and fully transparent pixels stay put.
@@ -15,8 +15,8 @@ import { PixelationDither } from "./types.js";
15
15
  const MIN_COLORS = 2;
16
16
  const MAX_COLORS = 256;
17
17
  const DEFAULT_COLORS = 16;
18
- /** CIE76 distance below which two colours are the same shade for practical purposes. */
19
- const MERGE_DELTA = 3;
18
+ /** OKLab Euclidean distance below which two colours are treated as near-duplicates. */
19
+ const NEAR_DUPLICATE_OKLAB_DISTANCE = 0.03;
20
20
  /** Seeding score = distance * count^SEED_WEIGHT: mostly distance, a little frequency. */
21
21
  const SEED_WEIGHT = 0.25;
22
22
  /** Cluster pull = count^PULL_WEIGHT, so large flat areas do not drag centroids off rare colours. */
@@ -51,7 +51,7 @@ function histogram(image) {
51
51
  seen.set(key, at);
52
52
  shades.push({
53
53
  rgb: [data[o], data[o + 1], data[o + 2]],
54
- lab: rgbToLab(data[o], data[o + 1], data[o + 2]),
54
+ oklab: rgbToOklab(data[o], data[o + 1], data[o + 2]),
55
55
  count: 0,
56
56
  });
57
57
  }
@@ -60,17 +60,26 @@ function histogram(image) {
60
60
  }
61
61
  return { shades, index };
62
62
  }
63
- /** Greedy leader clustering, heaviest first: only colours within MERGE_DELTA share a group. */
63
+ /** Greedy leader clustering, heaviest first: only colours within the OKLab threshold share a group. */
64
64
  function mergeNearDuplicates(shades) {
65
65
  const order = shades.map((_, i) => i).sort((a, b) => shades[b].count - shades[a].count || a - b);
66
66
  const groups = [];
67
+ const threshold2 = NEAR_DUPLICATE_OKLAB_DISTANCE ** 2;
67
68
  for (const i of order) {
68
- let best = -1, bestDistance = MERGE_DELTA;
69
+ const oklab = shades[i].oklab;
70
+ let best = -1, bestDistance2 = threshold2;
69
71
  for (let g = 0; g < groups.length; g++) {
70
- const d = distance(shades[i].lab, shades[groups[g][0]].lab);
71
- if (d <= bestDistance) {
72
- bestDistance = d;
72
+ const leader = shades[groups[g][0]].oklab;
73
+ const dx = oklab[0] - leader[0];
74
+ const dy = oklab[1] - leader[1];
75
+ const dz = oklab[2] - leader[2];
76
+ const d2 = dx * dx + dy * dy + dz * dz;
77
+ if (d2 <= bestDistance2) {
78
+ bestDistance2 = d2;
73
79
  best = g;
80
+ // Exact match is optimal; skip remaining groups.
81
+ if (d2 === 0)
82
+ break;
74
83
  }
75
84
  }
76
85
  if (best < 0)
@@ -87,10 +96,11 @@ function toPoints(shades, groups) {
87
96
  for (const m of members) {
88
97
  count += shades[m].count;
89
98
  for (let c = 0; c < 3; c++)
90
- sum[c] += shades[m].lab[c] * shades[m].count;
99
+ sum[c] += shades[m].oklab[c] * shades[m].count;
91
100
  }
101
+ const oklab = [sum[0] / count, sum[1] / count, sum[2] / count];
92
102
  return {
93
- lab: [sum[0] / count, sum[1] / count, sum[2] / count],
103
+ oklab,
94
104
  count,
95
105
  members,
96
106
  };
@@ -103,8 +113,8 @@ function seed(points, k) {
103
113
  for (let i = 1; i < points.length; i++)
104
114
  if (points[i].count > points[first].count)
105
115
  first = i;
106
- const seeds = [points[first].lab];
107
- const nearest = points.map((p) => distance(p.lab, seeds[0]));
116
+ const seeds = [points[first].oklab];
117
+ const nearest = points.map((p) => distance(p.oklab, seeds[0]));
108
118
  while (seeds.length < k) {
109
119
  let pick = -1, pickScore = 0;
110
120
  for (let i = 0; i < points.length; i++) {
@@ -116,21 +126,46 @@ function seed(points, k) {
116
126
  }
117
127
  if (pick < 0)
118
128
  break;
119
- seeds.push(points[pick].lab);
129
+ seeds.push(points[pick].oklab);
120
130
  for (let i = 0; i < points.length; i++)
121
- nearest[i] = Math.min(nearest[i], distance(points[i].lab, points[pick].lab));
131
+ nearest[i] = Math.min(nearest[i], distance(points[i].oklab, points[pick].oklab));
122
132
  }
123
133
  return seeds;
124
134
  }
125
135
  function cluster(points, k) {
126
136
  const centers = seed(points, k);
127
137
  const assign = new Int32Array(points.length).fill(-1);
138
+ // Flatten points and centres into typed arrays so the assignment loop avoids
139
+ // per-access bounds checks and object property lookups in the inner loop.
140
+ const n = points.length;
141
+ const pointData = new Float64Array(n * 3);
142
+ const pointWeight = new Float64Array(n);
143
+ for (let i = 0; i < n; i++) {
144
+ pointData[i * 3] = points[i].oklab[0];
145
+ pointData[i * 3 + 1] = points[i].oklab[1];
146
+ pointData[i * 3 + 2] = points[i].oklab[2];
147
+ pointWeight[i] = points[i].count ** PULL_WEIGHT;
148
+ }
149
+ const centerData = new Float64Array(centers.length * 3);
150
+ const writeCenter = (c, value) => {
151
+ centerData[c * 3] = value[0];
152
+ centerData[c * 3 + 1] = value[1];
153
+ centerData[c * 3 + 2] = value[2];
154
+ };
155
+ for (let c = 0; c < centers.length; c++)
156
+ writeCenter(c, centers[c]);
128
157
  for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
129
158
  let changed = false;
130
- for (let i = 0; i < points.length; i++) {
159
+ for (let i = 0; i < n; i++) {
160
+ const px = pointData[i * 3];
161
+ const py = pointData[i * 3 + 1];
162
+ const pz = pointData[i * 3 + 2];
131
163
  let best = 0, bestDistance = Infinity;
132
164
  for (let c = 0; c < centers.length; c++) {
133
- const d = distance(points[i].lab, centers[c]);
165
+ const dx = px - centerData[c * 3];
166
+ const dy = py - centerData[c * 3 + 1];
167
+ const dz = pz - centerData[c * 3 + 2];
168
+ const d = dx * dx + dy * dy + dz * dz;
134
169
  if (d < bestDistance) {
135
170
  bestDistance = d;
136
171
  best = c;
@@ -144,32 +179,37 @@ function cluster(points, k) {
144
179
  if (!changed)
145
180
  break;
146
181
  const sums = centers.map(() => [0, 0, 0, 0]);
147
- for (let i = 0; i < points.length; i++) {
148
- const weight = points[i].count ** PULL_WEIGHT;
182
+ for (let i = 0; i < n; i++) {
183
+ const weight = pointWeight[i];
149
184
  const s = sums[assign[i]];
150
- for (let c = 0; c < 3; c++)
151
- s[c] += points[i].lab[c] * weight;
185
+ s[0] += pointData[i * 3] * weight;
186
+ s[1] += pointData[i * 3 + 1] * weight;
187
+ s[2] += pointData[i * 3 + 2] * weight;
152
188
  s[3] += weight;
153
189
  }
154
190
  for (let c = 0; c < centers.length; c++)
155
191
  if (sums[c][3] > 0)
156
- centers[c] = [sums[c][0] / sums[c][3], sums[c][1] / sums[c][3], sums[c][2] / sums[c][3]];
192
+ writeCenter(c, [
193
+ sums[c][0] / sums[c][3],
194
+ sums[c][1] / sums[c][3],
195
+ sums[c][2] / sums[c][3],
196
+ ]);
157
197
  }
158
198
  return Array.from(assign);
159
199
  }
160
- function paletteLabs(palette) {
200
+ function paletteOklabs(palette) {
161
201
  const visible = palette.filter((color) => color[3] > 0);
162
202
  if (!visible.length)
163
203
  throw new RangeError("Choose a palette containing a visible color.");
164
204
  return {
165
- labs: visible.map((c) => rgbToLab(c[0], c[1], c[2])),
205
+ oklabs: visible.map((c) => rgbToOklab(c[0], c[1], c[2])),
166
206
  rgb: visible.map((c) => c),
167
207
  };
168
208
  }
169
- function nearestPaletteRgb(lab, labs, rgb) {
209
+ function nearestPaletteRgb(oklab, oklabs, rgb) {
170
210
  let best = 0, bestDistance = Infinity;
171
- for (let i = 0; i < labs.length; i++) {
172
- const d = distance(lab, labs[i]);
211
+ for (let i = 0; i < oklabs.length; i++) {
212
+ const d = distance(oklab, oklabs[i]);
173
213
  if (d < bestDistance) {
174
214
  bestDistance = d;
175
215
  best = i;
@@ -214,7 +254,7 @@ function nearestPaletteRgbEuclidean(r, g, b, palette) {
214
254
  /**
215
255
  * Ordered Bayer 8×8 → palette. Port of tensorhead/dithering `ordered_palette` (MIT):
216
256
  * threshold offset (t − 0.5) scaled by each channel's palette spread, then RGB nearest.
217
- * Unlike ±RGB Bayer then Lab nearest, this still dithers when every pixel is already a palette colour.
257
+ * Unlike ±RGB Bayer then OKLab nearest, this still dithers when every pixel is already a palette colour.
218
258
  */
219
259
  function orderedBayer8ToPalette(image, palette) {
220
260
  const spread = paletteSpread(palette);
@@ -235,11 +275,11 @@ function orderedBayer8ToPalette(image, palette) {
235
275
  return { width, height, data: output };
236
276
  }
237
277
  /**
238
- * Floyd–Steinberg error diffusion to `palette` in Lab-nearest space.
278
+ * Floyd–Steinberg error diffusion to `palette` in OKLab-nearest space.
239
279
  * Transparent pixels are left alone.
240
280
  */
241
281
  function floydSteinbergToPalette(image, palette) {
242
- const { labs, rgb } = paletteLabs(palette);
282
+ const { oklabs, rgb } = paletteOklabs(palette);
243
283
  const output = new Uint8ClampedArray(image.data);
244
284
  const { width, height, data } = image;
245
285
  const error = new Float32Array(width * height * 3);
@@ -254,7 +294,7 @@ function floydSteinbergToPalette(image, palette) {
254
294
  clampByte(data[at + 1] + error[i * 3 + 1]),
255
295
  clampByte(data[at + 2] + error[i * 3 + 2]),
256
296
  ];
257
- const chosen = nearestPaletteRgb(rgbToLab(sample[0], sample[1], sample[2]), labs, rgb);
297
+ const chosen = nearestPaletteRgb(rgbToOklab(sample[0], sample[1], sample[2]), oklabs, rgb);
258
298
  output[at] = chosen[0];
259
299
  output[at + 1] = chosen[1];
260
300
  output[at + 2] = chosen[2];
@@ -282,7 +322,7 @@ function ditherToPalette(image, palette, dither) {
282
322
  /** Build the reduced RGB palette (k-means or the given list); null when the image already fits. */
283
323
  function buildPalette(shades, options) {
284
324
  if (options.palette)
285
- return paletteLabs(options.palette).rgb;
325
+ return paletteOklabs(options.palette).rgb;
286
326
  const groups = mergeNearDuplicates(shades);
287
327
  const colors = options.adaptive
288
328
  ? Math.min(groups.length, MAX_COLORS)
@@ -293,15 +333,15 @@ function buildPalette(shades, options) {
293
333
  const assignment = points.length <= colors ? points.map((_, i) => i) : cluster(points, colors);
294
334
  const sums = new Map();
295
335
  points.forEach((point, i) => {
296
- const entry = sums.get(assignment[i]) ?? { lab: [0, 0, 0], count: 0 };
336
+ const entry = sums.get(assignment[i]) ?? { oklab: [0, 0, 0], count: 0 };
297
337
  for (let c = 0; c < 3; c++)
298
- entry.lab[c] += point.lab[c] * point.count;
338
+ entry.oklab[c] += point.oklab[c] * point.count;
299
339
  entry.count += point.count;
300
340
  sums.set(assignment[i], entry);
301
341
  });
302
342
  const palette = [];
303
- for (const { lab, count } of sums.values()) {
304
- const [r, g, b] = labToRgb(lab[0] / count, lab[1] / count, lab[2] / count);
343
+ for (const { oklab, count } of sums.values()) {
344
+ const [r, g, b] = oklabToRgb(oklab[0] / count, oklab[1] / count, oklab[2] / count);
305
345
  palette.push([r, g, b, 255]);
306
346
  }
307
347
  return palette;
@@ -311,8 +351,8 @@ function remapShades(image, shades, index, options) {
311
351
  const output = new Uint8ClampedArray(image.data);
312
352
  let target;
313
353
  if (options.palette) {
314
- const { labs, rgb } = paletteLabs(options.palette);
315
- target = shades.map((shade) => nearestPaletteRgb(shade.lab, labs, rgb));
354
+ const { oklabs, rgb } = paletteOklabs(options.palette);
355
+ target = shades.map((shade) => nearestPaletteRgb(shade.oklab, oklabs, rgb));
316
356
  }
317
357
  else {
318
358
  const groups = mergeNearDuplicates(shades);
@@ -325,15 +365,15 @@ function remapShades(image, shades, index, options) {
325
365
  const assignment = points.length <= colors ? points.map((_, i) => i) : cluster(points, colors);
326
366
  const sums = new Map();
327
367
  points.forEach((point, i) => {
328
- const entry = sums.get(assignment[i]) ?? { lab: [0, 0, 0], count: 0 };
368
+ const entry = sums.get(assignment[i]) ?? { oklab: [0, 0, 0], count: 0 };
329
369
  for (let c = 0; c < 3; c++)
330
- entry.lab[c] += point.lab[c] * point.count;
370
+ entry.oklab[c] += point.oklab[c] * point.count;
331
371
  entry.count += point.count;
332
372
  sums.set(assignment[i], entry);
333
373
  });
334
374
  const colorOf = new Map();
335
- for (const [id, { lab, count }] of sums)
336
- colorOf.set(id, labToRgb(lab[0] / count, lab[1] / count, lab[2] / count));
375
+ for (const [id, { oklab, count }] of sums)
376
+ colorOf.set(id, oklabToRgb(oklab[0] / count, oklab[1] / count, oklab[2] / count));
337
377
  target = Array.from({ length: shades.length }, () => [0, 0, 0]);
338
378
  points.forEach((point, i) => {
339
379
  for (const member of point.members)
@@ -358,7 +398,7 @@ export function snapPalette(image, options) {
358
398
  const { shades, index } = histogram(image);
359
399
  if (dither === PixelationDither.None)
360
400
  return remapShades(image, shades, index, options);
361
- // Ordered / Floyd–Steinberg need a concrete palette, then per-pixel Lab nearest.
401
+ // Ordered / Floyd–Steinberg need a concrete palette, then per-pixel OKLab nearest.
362
402
  const palette = buildPalette(shades, options);
363
403
  if (!palette) {
364
404
  // Already within budget and no user palette: dither among the image's own shades.
@@ -0,0 +1,10 @@
1
+ import { type PixelBuffer } from "./base.ts";
2
+ /**
3
+ * Settle soft alpha in a converted sprite using the sampled coverage. The
4
+ * source supplies the opacity heuristic so resampling a hard-edged image keeps
5
+ * its coverage alpha. Pass one buffer to settle alpha at its current size.
6
+ * Returns a new buffer when any pixels change.
7
+ */
8
+ export declare function settlePixelAlpha(source: PixelBuffer, sampled?: PixelBuffer): PixelBuffer;
9
+ /** Settle alpha from the source pixels inside each recovered grid cell. */
10
+ export declare function settleEdgeAlpha(image: PixelBuffer, x: readonly number[], y: readonly number[], out: PixelBuffer): void;
@@ -0,0 +1,108 @@
1
+ import { UINT8_MAX } from "./base.js";
2
+ const CHANNELS = 4;
3
+ const ALPHA = 3;
4
+ const HALF_ALPHA = 128;
5
+ const TRANSLUCENT_LOW = 16;
6
+ const TRANSLUCENT_HIGH = 224;
7
+ /** Share of the visible pixels a soft outline around opaque art stays below. */
8
+ const TRANSLUCENT_SHARE = 0.2;
9
+ /** Whether the image's visible pixels are opaque but for a soft edge. */
10
+ function opaqueArt(image, requireSoftAlpha = false) {
11
+ let visible = 0;
12
+ let translucent = 0;
13
+ let solid = 0;
14
+ let fullyOpaque = 0;
15
+ for (let o = ALPHA; o < image.data.length; o += CHANNELS) {
16
+ const alpha = image.data[o];
17
+ if (!alpha)
18
+ continue;
19
+ visible++;
20
+ if (alpha > TRANSLUCENT_HIGH) {
21
+ solid++;
22
+ if (alpha === UINT8_MAX)
23
+ fullyOpaque++;
24
+ }
25
+ else if (alpha >= TRANSLUCENT_LOW)
26
+ translucent++;
27
+ }
28
+ if (visible === 0 || translucent > TRANSLUCENT_SHARE * visible)
29
+ return false;
30
+ if (!requireSoftAlpha)
31
+ return true;
32
+ // A soft sprite has a solid core and some partial alpha. Look for a change
33
+ // in coverage so an evenly translucent image keeps its original alpha.
34
+ const hasEdge = solid < visible || visible < image.width * image.height;
35
+ return hasEdge && solid > 0 && fullyOpaque < visible;
36
+ }
37
+ function hasPartialAlpha(image) {
38
+ const { data } = image;
39
+ for (let alpha = ALPHA; alpha < data.length; alpha += CHANNELS)
40
+ if (data[alpha] > 0 && data[alpha] < UINT8_MAX)
41
+ return true;
42
+ return false;
43
+ }
44
+ function writeBinaryAlpha(data, offset, covered) {
45
+ if (covered)
46
+ data[offset + ALPHA] = UINT8_MAX;
47
+ else
48
+ data.fill(0, offset, offset + CHANNELS);
49
+ }
50
+ /**
51
+ * Settle soft alpha in a converted sprite using the sampled coverage. The
52
+ * source supplies the opacity heuristic so resampling a hard-edged image keeps
53
+ * its coverage alpha. Pass one buffer to settle alpha at its current size.
54
+ * Returns a new buffer when any pixels change.
55
+ */
56
+ export function settlePixelAlpha(source, sampled = source) {
57
+ if (!hasPartialAlpha(sampled) || !opaqueArt(source, true))
58
+ return sampled;
59
+ const data = sampled.data.slice();
60
+ for (let offset = 0; offset < data.length; offset += CHANNELS) {
61
+ const alpha = data[offset + ALPHA];
62
+ if (alpha > 0 && alpha < UINT8_MAX)
63
+ writeBinaryAlpha(data, offset, alpha >= HALF_ALPHA);
64
+ }
65
+ return { ...sampled, data };
66
+ }
67
+ /** Settle alpha from the source pixels inside each recovered grid cell. */
68
+ export function settleEdgeAlpha(image, x, y, out) {
69
+ const opaque = opaqueArt(image);
70
+ for (let row = 0; row < out.height; row++)
71
+ for (let column = 0; column < out.width; column++) {
72
+ const offset = (row * out.width + column) * CHANNELS;
73
+ if (!out.data[offset + ALPHA])
74
+ continue;
75
+ const left = Math.max(0, Math.ceil(x[column])), right = Math.min(image.width, Math.ceil(x[column + 1])), top = Math.max(0, Math.ceil(y[row])), bottom = Math.min(image.height, Math.ceil(y[row + 1]));
76
+ let covered = 0, coveredAlpha = 0;
77
+ const alphas = [];
78
+ for (let py = top; py < bottom; py++)
79
+ for (let px = left; px < right; px++) {
80
+ const alpha = image.data[(py * image.width + px) * CHANNELS + ALPHA];
81
+ alphas.push(alpha);
82
+ if (alpha < HALF_ALPHA)
83
+ continue;
84
+ covered++;
85
+ coveredAlpha += alpha;
86
+ }
87
+ const area = (right - left) * (bottom - top);
88
+ if (!covered && !opaque) {
89
+ // Translucent art fills its cell evenly; a soft outline leaves most of the cell clear.
90
+ alphas.sort((a, b) => a - b);
91
+ const median = alphas[alphas.length >> 1] ?? 0;
92
+ if (median < TRANSLUCENT_LOW)
93
+ out.data.fill(0, offset, offset + CHANNELS);
94
+ else
95
+ out.data[offset + ALPHA] = median;
96
+ continue;
97
+ }
98
+ const outside = covered < area / 2;
99
+ if (opaque || outside)
100
+ writeBinaryAlpha(out.data, offset, !outside);
101
+ else {
102
+ // Translucent art (a shadow, a glow) keeps its alpha, but a covered cell above
103
+ // TRANSLUCENT_HIGH is opaque art drawn a little below 255, as everywhere else.
104
+ const alpha = covered < area ? coveredAlpha / covered : out.data[offset + ALPHA];
105
+ out.data[offset + ALPHA] = alpha > TRANSLUCENT_HIGH ? UINT8_MAX : Math.round(alpha);
106
+ }
107
+ }
108
+ }
package/dist/pixelate.js CHANGED
@@ -6,11 +6,13 @@ import { prepareGridSampling } from "./grid-sampling.js";
6
6
  import { runPixeloe } from "./line-guided/pixeloe-entry.js";
7
7
  import { resizeMostFrequent } from "./most-frequent.js";
8
8
  import { applyOutlinePrepass, DEFAULT_LINE_GUIDE, runsStockPixeloe, } from "./outline-prepass.js";
9
+ import { removeOrphanPixels } from "./orphan-pixels.js";
9
10
  import { snapPalette } from "./palette-snap.js";
11
+ import { settlePixelAlpha } from "./pixel-alpha.js";
10
12
  import { detectWithAlgorithm, detectWithAlgorithmAsync, recoverWithGrid, } from "./pixelation-algorithm-registry.js";
11
13
  import { resizeBox, resizeNearest } from "./resize.js";
12
14
  import { samplePixelation } from "./sampling.js";
13
- import { OutlinePrepass, PixelationMethod, PixelationMode, PixelationAlgorithm, } from "./types.js";
15
+ import { OutlinePrepass, PixelationDither, PixelationMethod, PixelationMode, PixelationAlgorithm, } from "./types.js";
14
16
  const WORKING_SCALE = 4;
15
17
  const MAX_WORKING_PIXELS = 1_048_576;
16
18
  const MAX_OUTLINE_STRENGTH = 100;
@@ -77,13 +79,22 @@ function sampleImage(image, options, method) {
77
79
  const prepared = strength || method === PixelationMethod.Dominant || method === PixelationMethod.Structure
78
80
  ? prepareSource(image, target, strength)
79
81
  : image;
80
- if (method === PixelationMethod.Nearest)
81
- return resizeNearest(prepared, target.width, target.height);
82
- if (method === PixelationMethod.Box)
83
- return resizeBox(prepared, target.width, target.height, alphaMode);
84
- if (method === PixelationMethod.MostFrequent)
85
- return resizeMostFrequent(prepared, target.width, target.height);
86
- return samplePixelation(prepared, target.width, target.height, method);
82
+ const { width, height } = target;
83
+ let sampled;
84
+ switch (method) {
85
+ case PixelationMethod.Nearest:
86
+ sampled = resizeNearest(prepared, width, height);
87
+ break;
88
+ case PixelationMethod.Box:
89
+ sampled = resizeBox(prepared, width, height, alphaMode);
90
+ break;
91
+ case PixelationMethod.MostFrequent:
92
+ sampled = resizeMostFrequent(prepared, width, height);
93
+ break;
94
+ default:
95
+ sampled = samplePixelation(prepared, width, height, method);
96
+ }
97
+ return settlePixelAlpha(image, sampled);
87
98
  }
88
99
  function sizeFromBlock(blockSize, image) {
89
100
  if (typeof blockSize === "number") {
@@ -145,6 +156,19 @@ function validateMethod(value) {
145
156
  throw new RangeError("Unknown pixelation method.");
146
157
  return method;
147
158
  }
159
+ function finishPixelation(sampled, source, { removeNoise, paletteSnap, preserveDimensions }) {
160
+ let result = removeNoise ? smoothPixelation(sampled) : sampled;
161
+ if (paletteSnap)
162
+ result = snapPalette(result, paletteSnap);
163
+ if (removeNoise) {
164
+ const dither = paletteSnap?.dither;
165
+ const dithered = dither === PixelationDither.Ordered || dither === PixelationDither.FloydSteinberg;
166
+ result = removeOrphanPixels(result, { absorbInterior: !dithered });
167
+ }
168
+ if (preserveDimensions && (result.width !== source.width || result.height !== source.height))
169
+ result = resizeNearest(result, source.width, source.height);
170
+ return result;
171
+ }
148
172
  /**
149
173
  * Pixelate an RGBA buffer without touching the source. Nearest mode follows
150
174
  * nearest-neighbor `floor(dst * src / dst)` mapping. Box mode averages the
@@ -155,15 +179,7 @@ function validateMethod(value) {
155
179
  export function pixelateImage(image, options = {}) {
156
180
  assertPixelBuffer(image);
157
181
  const method = validateMethod(options.method);
158
- const sampled = sampleImage(image, options, method);
159
- const smoothed = options.removeNoise ? smoothPixelation(sampled) : sampled;
160
- // Limit colors: Lab k-means that keeps rare colours, or snapping to a loaded palette.
161
- let result = options.paletteSnap ? snapPalette(smoothed, options.paletteSnap) : smoothed;
162
- if (options.preserveDimensions &&
163
- (result.width !== image.width || result.height !== image.height)) {
164
- result = resizeNearest(result, image.width, image.height);
165
- }
166
- return result;
182
+ return finishPixelation(sampleImage(image, options, method), image, options);
167
183
  }
168
184
  async function sampleImageAsync(image, options, method) {
169
185
  const wantsGrid = options.mode === PixelationMode.RecoverGrid ||
@@ -204,11 +220,5 @@ export async function pixelateImageAsync(image, options = {}) {
204
220
  assertPixelBuffer(image);
205
221
  const method = validateMethod(options.method);
206
222
  const sampled = await sampleImageAsync(image, options, method);
207
- const smoothed = options.removeNoise ? smoothPixelation(sampled) : sampled;
208
- let result = options.paletteSnap ? snapPalette(smoothed, options.paletteSnap) : smoothed;
209
- if (options.preserveDimensions &&
210
- (result.width !== image.width || result.height !== image.height)) {
211
- result = resizeNearest(result, image.width, image.height);
212
- }
213
- return result;
223
+ return finishPixelation(sampled, image, options);
214
224
  }
@@ -1,6 +1,11 @@
1
1
  import type { Rgba } from "./base.ts";
2
2
  import type { PaletteEntry } from "./types.ts";
3
- /** Oklab plus opacity; invisible RGB never participates in matching. */
3
+ export type Oklab = readonly [lightness: number, a: number, b: number];
4
+ /** OKLab plus opacity; invisible RGB never participates in matching. */
4
5
  export declare function paletteCoordinates(color: Rgba): Rgba;
6
+ /** Convert opaque sRGB bytes to OKLab coordinates. Cached per packed RGB. */
7
+ export declare function rgbToOklab(r: number, g: number, b: number): Oklab;
8
+ /** Convert OKLab coordinates back to 8-bit sRGB. */
9
+ export declare function oklabToRgb(lightness: number, a: number, b: number): [number, number, number];
5
10
  /** Variance-driven color partitioning keeps accents instead of selecting only frequent shades. */
6
11
  export declare function optimizePalette(entries: PaletteEntry[], limit: number): PaletteEntry[];
@@ -3,6 +3,7 @@ import { clampByte } from "./base.js";
3
3
  const CHANNELS = 4;
4
4
  const COLOR_CHANNELS = 3;
5
5
  const LINEAR_THRESHOLD = 0.04045;
6
+ const LINEAR_TO_SRGB_THRESHOLD = 0.0031308;
6
7
  const LINEAR_DIVISOR = 12.92;
7
8
  const GAMMA_OFFSET = 0.055;
8
9
  const GAMMA_SCALE = 1.055;
@@ -27,23 +28,64 @@ const LMS_TO_OKLAB = [
27
28
  [1.9779984951, -2.428592205, 0.4505937099],
28
29
  [0.0259040371, 0.7827717662, -0.808675766],
29
30
  ];
31
+ const OKLAB_TO_LMS = [
32
+ [1, 0.3963377774, 0.2158037573],
33
+ [1, -0.1055613458, -0.0638541728],
34
+ [1, -0.0894841775, -1.291485548],
35
+ ];
36
+ const LMS_TO_LINEAR_SRGB = [
37
+ [4.0767416621, -3.3077115913, 0.2309699292],
38
+ [-1.2684380046, 2.6097574011, -0.3413193965],
39
+ [-0.0041960863, -0.7034186147, 1.707614701],
40
+ ];
30
41
  function dot(row, a, b, c) {
31
42
  return row[0] * a + row[1] * b + row[2] * c;
32
43
  }
33
- /** Oklab plus opacity; invisible RGB never participates in matching. */
44
+ function linearRgbToOklab(r, g, b) {
45
+ const l = Math.cbrt(dot(LINEAR_SRGB_TO_LMS[0], r, g, b));
46
+ const m = Math.cbrt(dot(LINEAR_SRGB_TO_LMS[1], r, g, b));
47
+ const s = Math.cbrt(dot(LINEAR_SRGB_TO_LMS[2], r, g, b));
48
+ return [
49
+ dot(LMS_TO_OKLAB[0], l, m, s),
50
+ dot(LMS_TO_OKLAB[1], l, m, s),
51
+ dot(LMS_TO_OKLAB[2], l, m, s),
52
+ ];
53
+ }
54
+ /** OKLab plus opacity; invisible RGB never participates in matching. */
34
55
  export function paletteCoordinates(color) {
35
56
  const opacity = color[3] / UINT8_MAX;
36
57
  const r = linearChannel(color[0]);
37
58
  const g = linearChannel(color[1]);
38
59
  const b = linearChannel(color[2]);
39
- const l = Math.cbrt(dot(LINEAR_SRGB_TO_LMS[0], r, g, b));
40
- const m = Math.cbrt(dot(LINEAR_SRGB_TO_LMS[1], r, g, b));
41
- const s = Math.cbrt(dot(LINEAR_SRGB_TO_LMS[2], r, g, b));
60
+ const [lightness, a, blueYellow] = linearRgbToOklab(r, g, b);
61
+ return [lightness * opacity, a * opacity, blueYellow * opacity, opacity];
62
+ }
63
+ const oklabCache = new Map();
64
+ /** Convert opaque sRGB bytes to OKLab coordinates. Cached per packed RGB. */
65
+ export function rgbToOklab(r, g, b) {
66
+ const key = (r << 16) | (g << 8) | b;
67
+ const hit = oklabCache.get(key);
68
+ if (hit !== undefined)
69
+ return hit;
70
+ const value = linearRgbToOklab(linearChannel(r), linearChannel(g), linearChannel(b));
71
+ oklabCache.set(key, value);
72
+ return value;
73
+ }
74
+ function srgbByteFromLinear(value) {
75
+ const encoded = value <= LINEAR_TO_SRGB_THRESHOLD
76
+ ? value * LINEAR_DIVISOR
77
+ : GAMMA_SCALE * value ** (1 / GAMMA_EXPONENT) - GAMMA_OFFSET;
78
+ return clampByte(encoded * UINT8_MAX);
79
+ }
80
+ /** Convert OKLab coordinates back to 8-bit sRGB. */
81
+ export function oklabToRgb(lightness, a, b) {
82
+ const l = dot(OKLAB_TO_LMS[0], lightness, a, b) ** 3;
83
+ const m = dot(OKLAB_TO_LMS[1], lightness, a, b) ** 3;
84
+ const s = dot(OKLAB_TO_LMS[2], lightness, a, b) ** 3;
42
85
  return [
43
- dot(LMS_TO_OKLAB[0], l, m, s) * opacity,
44
- dot(LMS_TO_OKLAB[1], l, m, s) * opacity,
45
- dot(LMS_TO_OKLAB[2], l, m, s) * opacity,
46
- opacity,
86
+ srgbByteFromLinear(dot(LMS_TO_LINEAR_SRGB[0], l, m, s)),
87
+ srgbByteFromLinear(dot(LMS_TO_LINEAR_SRGB[1], l, m, s)),
88
+ srgbByteFromLinear(dot(LMS_TO_LINEAR_SRGB[2], l, m, s)),
47
89
  ];
48
90
  }
49
91
  function box(samples) {
package/dist/types.d.ts CHANGED
@@ -92,7 +92,7 @@ export declare enum PixelationDither {
92
92
  export declare enum PaletteColorMode {
93
93
  /** User-specified fixed count (e.g. 16). */
94
94
  Fixed = "fixed",
95
- /** One colour per group of near-duplicate shades (Lab ΔE) in the recovered image. */
95
+ /** One colour per group of near-duplicate shades (OKLab distance) in the recovered image. */
96
96
  Adaptive = "adaptive"
97
97
  }
98
98
  /** How a line drawing changes PixelOE's outline weight (1 = spread dark, 0 = spread bright). */
@@ -167,7 +167,7 @@ export interface PaletteSnapOptions {
167
167
  colors?: number;
168
168
  /** Estimate color count from the image instead of using a fixed count. */
169
169
  adaptive?: boolean;
170
- /** Snap every visible pixel to its nearest entry (CIE Lab) instead of clustering. */
170
+ /** Snap every visible pixel to its nearest entry (OKLab) instead of clustering. */
171
171
  palette?: readonly Rgba[];
172
172
  /** Ordered / Floyd–Steinberg while snapping; None (nearest) when omitted. */
173
173
  dither?: PixelationDither;
@@ -201,11 +201,11 @@ export interface PixelateOptions {
201
201
  /** Nearest-neighbor upscale to the source dimensions after pixelation. */
202
202
  preserveDimensions?: boolean;
203
203
  /**
204
- * Limit colors: Lab k-means to a colour count that keeps rare colours, or snapping to a given
204
+ * Limit colors: OKLab k-means to a colour count that keeps rare colours, or snapping to a given
205
205
  * palette. Alpha stays per pixel. Off when omitted.
206
206
  */
207
207
  paletteSnap?: PaletteSnapOptions;
208
- /** Light smoothing of similar neighboring colors on the working grid. */
208
+ /** Smooth similar colors and remove isolated pixels on the working grid. */
209
209
  removeNoise?: boolean;
210
210
  /** Box mode defaults to straight channel means; premultiplied is useful for compositing. */
211
211
  alphaMode?: "straight" | "premultiplied";
package/dist/types.js CHANGED
@@ -56,7 +56,7 @@ export var PaletteColorMode;
56
56
  (function (PaletteColorMode) {
57
57
  /** User-specified fixed count (e.g. 16). */
58
58
  PaletteColorMode["Fixed"] = "fixed";
59
- /** One colour per group of near-duplicate shades (Lab ΔE) in the recovered image. */
59
+ /** One colour per group of near-duplicate shades (OKLab distance) in the recovered image. */
60
60
  PaletteColorMode["Adaptive"] = "adaptive";
61
61
  })(PaletteColorMode || (PaletteColorMode = {}));
62
62
  /** How a line drawing changes PixelOE's outline weight (1 = spread dark, 0 = spread bright). */