@xprite/pixelate 0.1.3 → 0.2.0

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 type { PixelBuffer } from "../base.ts";
1
+ import { type PixelBuffer } from "../base.ts";
2
2
  import { LineGuideMode, type PixelationSize } from "../types.ts";
3
3
  /**
4
4
  * A recent PixelOE result for `image` under `variant` (the step and its settings), else computed
5
5
  * and remembered. Callers get their own copy of the pixels.
6
6
  */
7
- export declare function rememberPixeloe(image: PixelBuffer, variant: string, compute: () => PixelBuffer): PixelBuffer;
7
+ export declare const rememberPixeloe: (image: PixelBuffer, variant: string, compute: () => PixelBuffer) => PixelBuffer;
8
8
  /** Stock PixelOE pixelize (optionally line-guided) of the whole image to `size`. */
9
9
  export declare function runPixeloe(image: PixelBuffer, grid: PixelationSize, guide?: LineGuideMode): PixelBuffer;
10
10
  /**
@@ -1,3 +1,4 @@
1
+ import { createBufferMemo } from "../base.js";
1
2
  import { resizeArea8 } from "./cv-ops.js";
2
3
  import { legacyPixeloe, legacyPixeloeSizes, } from "./pixeloe-legacy.js";
3
4
  import { otsuThreshold, xdogLines } from "./xdog.js";
@@ -12,25 +13,11 @@ const LINE_SOURCE_MAX = 512;
12
13
  const OPAQUE = 255;
13
14
  const ALPHA_CUTOFF = 128;
14
15
  const PAPER = 255;
15
- /** Recent results, so changing only colour settings does not rerun PixelOE. */
16
- const MEMO_SIZE = 4;
17
- /** Larger results (full-size pre-passes of big photos, 8 MB and up) are not kept. */
18
- const MAX_REMEMBERED_PIXELS = 2_097_152;
19
- const memo = [];
20
- const FNV_OFFSET = 0x811c9dc5;
21
- const FNV_PRIME = 0x01000193;
22
- const MIX_PRIME = 0x9e3779b1;
23
- /** Two independent 32-bit hashes of the pixels (FNV-1a and a multiplicative mix). */
24
- function fingerprint(data) {
25
- const bytes = data.byteOffset % 4 ? data.slice() : data;
26
- const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength >> 2);
27
- let a = FNV_OFFSET, b = 0;
28
- for (let i = 0; i < words.length; i++) {
29
- a = Math.imul(a ^ words[i], FNV_PRIME);
30
- b = Math.imul(b + words[i], MIX_PRIME) ^ (b >>> 15);
31
- }
32
- return `${(a >>> 0).toString(36)}${(b >>> 0).toString(36)}`;
33
- }
16
+ /**
17
+ * A recent PixelOE result for `image` under `variant` (the step and its settings), else computed
18
+ * and remembered. Callers get their own copy of the pixels.
19
+ */
20
+ export const rememberPixeloe = createBufferMemo();
34
21
  /** RGB composited over white (transparent pixels would otherwise read as dark outlines). */
35
22
  function opaqueRgb(image) {
36
23
  const { data } = image;
@@ -56,22 +43,6 @@ function lineGuide(rgb, width, height, workLongSide, mode) {
56
43
  const lines = xdogLines(source, lw, lh);
57
44
  return { lines, width: lw, height: lh, threshold: otsuThreshold(lines), mode };
58
45
  }
59
- /**
60
- * A recent PixelOE result for `image` under `variant` (the step and its settings), else computed
61
- * and remembered. Callers get their own copy of the pixels.
62
- */
63
- export function rememberPixeloe(image, variant, compute) {
64
- const key = `${image.width}x${image.height}:${fingerprint(image.data)}:${variant}`;
65
- const known = memo.find((entry) => entry.key === key);
66
- if (known)
67
- return { ...known.result, data: known.result.data.slice() };
68
- const result = compute();
69
- if (result.width * result.height > MAX_REMEMBERED_PIXELS)
70
- return result;
71
- memo.unshift({ key, result: { ...result, data: result.data.slice() } });
72
- memo.length = Math.min(memo.length, MEMO_SIZE);
73
- return result;
74
- }
75
46
  /** Stock PixelOE pixelize (optionally line-guided) of the whole image to `size`. */
76
47
  export function runPixeloe(image, grid, guide) {
77
48
  return rememberPixeloe(image, `${grid.width}x${grid.height}:${guide ?? ""}`, () => pixeloe(image, grid, guide));
@@ -9,3 +9,10 @@ export interface RemoveOrphanPixelsOptions {
9
9
  * majority color. Decisions use the original pixels and never change the input buffer.
10
10
  */
11
11
  export declare function removeOrphanPixels(image: PixelBuffer, { absorbInterior }?: RemoveOrphanPixelsOptions): PixelBuffer;
12
+ /**
13
+ * Contrast-aware stray speckle cleanup: absorbs isolated 1-pixel interior speckles whose OKLab
14
+ * distance to the surrounding majority cluster is below `maxDeltaE`, while keeping high-contrast
15
+ * focal landmarks (eye pupils, 1 px white sclera, pearl/lantern highlights) and diagonal 1 px
16
+ * strokes intact.
17
+ */
18
+ export declare function cleanStraySpeckles(image: PixelBuffer, maxDeltaE?: number): PixelBuffer;
@@ -1,4 +1,5 @@
1
1
  import { assertPixelBuffer, UINT8_MAX } from "./base.js";
2
+ import { rgbToOklab } from "./quantization.js";
2
3
  const CHANNELS = 4;
3
4
  const ALPHA = 3;
4
5
  function rgbAt(data, offset) {
@@ -72,3 +73,135 @@ export function removeOrphanPixels(image, { absorbInterior = true } = {}) {
72
73
  }
73
74
  return output ? { ...image, data: output } : image;
74
75
  }
76
+ const DEFAULT_SPECKLE_DELTA_E = 0.22;
77
+ const ISOLATED_NEAREST_DELTA_E = 0.14;
78
+ /**
79
+ * Contrast-aware stray speckle cleanup: absorbs isolated 1-pixel interior speckles whose OKLab
80
+ * distance to the surrounding majority cluster is below `maxDeltaE`, while keeping high-contrast
81
+ * focal landmarks (eye pupils, 1 px white sclera, pearl/lantern highlights) and diagonal 1 px
82
+ * strokes intact.
83
+ */
84
+ export function cleanStraySpeckles(image, maxDeltaE = DEFAULT_SPECKLE_DELTA_E) {
85
+ assertPixelBuffer(image);
86
+ const { width: w, height: h, data } = image;
87
+ if (w < 3 || h < 3)
88
+ return image;
89
+ const stride = w * CHANNELS;
90
+ const labCache = new Map();
91
+ const labOf = (key) => {
92
+ let v = labCache.get(key);
93
+ if (!v) {
94
+ v = rgbToOklab((key >> 16) & 255, (key >> 8) & 255, key & 255);
95
+ labCache.set(key, v);
96
+ }
97
+ return v;
98
+ };
99
+ const dE = (k1, k2) => {
100
+ const a = labOf(k1);
101
+ const b = labOf(k2);
102
+ return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
103
+ };
104
+ let output;
105
+ const n4 = new Int32Array(4);
106
+ const n8 = new Int32Array(8);
107
+ for (let y = 1; y < h - 1; y++) {
108
+ for (let x = 1; x < w - 1; x++) {
109
+ const o = y * stride + x * CHANNELS;
110
+ if (data[o + ALPHA] !== UINT8_MAX)
111
+ continue;
112
+ // Only clean interior pixels whose 4 cardinal neighbors are also opaque.
113
+ const oL = o - CHANNELS;
114
+ const oR = o + CHANNELS;
115
+ const oU = o - stride;
116
+ const oD = o + stride;
117
+ if (data[oL + ALPHA] !== UINT8_MAX ||
118
+ data[oR + ALPHA] !== UINT8_MAX ||
119
+ data[oU + ALPHA] !== UINT8_MAX ||
120
+ data[oD + ALPHA] !== UINT8_MAX) {
121
+ continue;
122
+ }
123
+ const k = rgbAt(data, o);
124
+ n4[0] = rgbAt(data, oL);
125
+ n4[1] = rgbAt(data, oR);
126
+ n4[2] = rgbAt(data, oU);
127
+ n4[3] = rgbAt(data, oD);
128
+ if (n4[0] === k || n4[1] === k || n4[2] === k || n4[3] === k)
129
+ continue;
130
+ const oUL = oU - CHANNELS;
131
+ const oUR = oU + CHANNELS;
132
+ const oDL = oD - CHANNELS;
133
+ const oDR = oD + CHANNELS;
134
+ const d0 = data[oUL + ALPHA] === UINT8_MAX ? rgbAt(data, oUL) : -1;
135
+ const d1 = data[oUR + ALPHA] === UINT8_MAX ? rgbAt(data, oUR) : -1;
136
+ const d2 = data[oDL + ALPHA] === UINT8_MAX ? rgbAt(data, oDL) : -1;
137
+ const d3 = data[oDR + ALPHA] === UINT8_MAX ? rgbAt(data, oDR) : -1;
138
+ const diagSame = (d0 === k ? 1 : 0) + (d1 === k ? 1 : 0) + (d2 === k ? 1 : 0) + (d3 === k ? 1 : 0);
139
+ if (diagSame >= 2)
140
+ continue;
141
+ // Majority vote across 4-neighbors
142
+ let best4 = n4[0];
143
+ let best4C = 0;
144
+ for (let i = 0; i < 4; i++) {
145
+ let cnt = 1;
146
+ for (let j = i + 1; j < 4; j++)
147
+ if (n4[j] === n4[i])
148
+ cnt++;
149
+ if (cnt > best4C) {
150
+ best4C = cnt;
151
+ best4 = n4[i];
152
+ }
153
+ }
154
+ let replace = -1;
155
+ if (best4C >= 3 && dE(k, best4) < maxDeltaE) {
156
+ replace = best4;
157
+ }
158
+ else if (diagSame === 0) {
159
+ n8[0] = n4[0];
160
+ n8[1] = n4[1];
161
+ n8[2] = n4[2];
162
+ n8[3] = n4[3];
163
+ n8[4] = d0;
164
+ n8[5] = d1;
165
+ n8[6] = d2;
166
+ n8[7] = d3;
167
+ let best8 = n8[0];
168
+ let best8C = 0;
169
+ for (let i = 0; i < 8; i++) {
170
+ if (n8[i] < 0)
171
+ continue;
172
+ let cnt = 1;
173
+ for (let j = i + 1; j < 8; j++)
174
+ if (n8[j] === n8[i])
175
+ cnt++;
176
+ if (cnt > best8C) {
177
+ best8C = cnt;
178
+ best8 = n8[i];
179
+ }
180
+ }
181
+ if (best8C >= 5 && dE(k, best8) < maxDeltaE) {
182
+ replace = best8;
183
+ }
184
+ else {
185
+ let nearest = n4[0];
186
+ let minD = Infinity;
187
+ for (let i = 0; i < 4; i++) {
188
+ const dist = dE(k, n4[i]);
189
+ if (dist < minD) {
190
+ minD = dist;
191
+ nearest = n4[i];
192
+ }
193
+ }
194
+ if (minD < ISOLATED_NEAREST_DELTA_E)
195
+ replace = nearest;
196
+ }
197
+ }
198
+ if (replace >= 0) {
199
+ output ??= data.slice();
200
+ output[o] = (replace >> 16) & 255;
201
+ output[o + 1] = (replace >> 8) & 255;
202
+ output[o + 2] = replace & 255;
203
+ }
204
+ }
205
+ }
206
+ return output ? { ...image, data: output } : image;
207
+ }
@@ -1,4 +1,4 @@
1
- import type { PixelBuffer } from "./base.ts";
1
+ import { type PixelBuffer } from "./base.ts";
2
2
  import { type PaletteSnapOptions } from "./types.ts";
3
3
  /** The recovered image with its colours snapped; the source is never modified. */
4
4
  export declare function snapPalette(image: PixelBuffer, options: PaletteSnapOptions): PixelBuffer;
@@ -1,3 +1,5 @@
1
+ import { clampByte } from "./base.js";
2
+ import { gaussianBlur } from "./float-image.js";
1
3
  import { oklabToRgb, rgbToOklab } from "./quantization.js";
2
4
  import { PixelationDither } from "./types.js";
3
5
  /**
@@ -21,6 +23,9 @@ const NEAR_DUPLICATE_OKLAB_DISTANCE = 0.03;
21
23
  const SEED_WEIGHT = 0.25;
22
24
  /** Cluster pull = count^PULL_WEIGHT, so large flat areas do not drag centroids off rare colours. */
23
25
  const PULL_WEIGHT = 0.5;
26
+ const SALIENCY_SIGMA = 2.5;
27
+ const SALIENCY_BOOST = 3.5;
28
+ const SALIENCY_CHROMA_WEIGHT = 2.4;
24
29
  const MAX_ITERATIONS = 32;
25
30
  const CHANNELS = 4;
26
31
  /**
@@ -32,9 +37,66 @@ const BAYER_8 = [
32
37
  52, 20, 62, 30, 54, 22, 3, 35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57, 25, 15, 47, 7,
33
38
  39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21,
34
39
  ];
35
- const distance = (a, b) => Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2);
36
- const clampByte = (value) => Math.max(0, Math.min(255, Math.round(value)));
37
- function histogram(image) {
40
+ const distance = (a, b, chromaWeight = 1) => Math.sqrt((a[0] - b[0]) ** 2 + chromaWeight * ((a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2));
41
+ /** Local OKLab brightness + chroma distinctiveness so rare focal accents win palette slots. */
42
+ function computePixelSalience(image, shades, index) {
43
+ const { width: w, height: h } = image;
44
+ const n = w * h;
45
+ const L = new Float32Array(n);
46
+ const A = new Float32Array(n);
47
+ const B = new Float32Array(n);
48
+ let meanL = 0;
49
+ let meanA = 0;
50
+ let meanB = 0;
51
+ let vis = 0;
52
+ for (let i = 0; i < n; i++) {
53
+ const si = index[i];
54
+ if (si < 0)
55
+ continue;
56
+ const ok = shades[si].oklab;
57
+ L[i] = ok[0];
58
+ A[i] = ok[1];
59
+ B[i] = ok[2];
60
+ meanL += ok[0];
61
+ meanA += ok[1];
62
+ meanB += ok[2];
63
+ vis += 1;
64
+ }
65
+ if (vis > 0 && vis < n) {
66
+ meanL /= vis;
67
+ meanA /= vis;
68
+ meanB /= vis;
69
+ for (let i = 0; i < n; i++) {
70
+ if (index[i] < 0) {
71
+ L[i] = meanL;
72
+ A[i] = meanA;
73
+ B[i] = meanB;
74
+ }
75
+ }
76
+ }
77
+ const L2 = gaussianBlur(L, w, h, SALIENCY_SIGMA, 2.5);
78
+ const A2 = gaussianBlur(A, w, h, SALIENCY_SIGMA, 2.5);
79
+ const B2 = gaussianBlur(B, w, h, SALIENCY_SIGMA, 2.5);
80
+ const sal = new Float32Array(n);
81
+ let maxS = 1e-6;
82
+ for (let i = 0; i < n; i++) {
83
+ if (index[i] < 0)
84
+ continue;
85
+ const s = Math.abs(L[i] - L2[i]) * 1.4 +
86
+ Math.hypot(A[i] - A2[i], B[i] - B2[i]) * 4.5 +
87
+ Math.hypot(A[i], B[i]) * 1.2;
88
+ sal[i] = s;
89
+ if (s > maxS)
90
+ maxS = s;
91
+ }
92
+ const invMax = 1 / maxS;
93
+ for (let i = 0; i < n; i++) {
94
+ if (index[i] >= 0)
95
+ sal[i] = 1 + SALIENCY_BOOST * (sal[i] * invMax) ** 1.25;
96
+ }
97
+ return sal;
98
+ }
99
+ function histogram(image, useSaliency) {
38
100
  const { data } = image;
39
101
  const pixels = data.length / CHANNELS;
40
102
  const seen = new Map();
@@ -53,15 +115,28 @@ function histogram(image) {
53
115
  rgb: [data[o], data[o + 1], data[o + 2]],
54
116
  oklab: rgbToOklab(data[o], data[o + 1], data[o + 2]),
55
117
  count: 0,
118
+ salienceSum: 0,
56
119
  });
57
120
  }
58
121
  shades[at].count += 1;
59
122
  index[i] = at;
60
123
  }
124
+ if (useSaliency && image.width * image.height >= 16 && shades.length > 2) {
125
+ const sal = computePixelSalience(image, shades, index);
126
+ for (let i = 0; i < pixels; i++) {
127
+ const si = index[i];
128
+ if (si >= 0)
129
+ shades[si].salienceSum += sal[i];
130
+ }
131
+ }
132
+ else {
133
+ for (const shade of shades)
134
+ shade.salienceSum = shade.count;
135
+ }
61
136
  return { shades, index };
62
137
  }
63
138
  /** Greedy leader clustering, heaviest first: only colours within the OKLab threshold share a group. */
64
- function mergeNearDuplicates(shades) {
139
+ function mergeNearDuplicates(shades, chromaWeight = 1) {
65
140
  const order = shades.map((_, i) => i).sort((a, b) => shades[b].count - shades[a].count || a - b);
66
141
  const groups = [];
67
142
  const threshold2 = NEAR_DUPLICATE_OKLAB_DISTANCE ** 2;
@@ -73,7 +148,7 @@ function mergeNearDuplicates(shades) {
73
148
  const dx = oklab[0] - leader[0];
74
149
  const dy = oklab[1] - leader[1];
75
150
  const dz = oklab[2] - leader[2];
76
- const d2 = dx * dx + dy * dy + dz * dz;
151
+ const d2 = dx * dx + chromaWeight * (dy * dy + dz * dz);
77
152
  if (d2 <= bestDistance2) {
78
153
  bestDistance2 = d2;
79
154
  best = g;
@@ -92,9 +167,11 @@ function mergeNearDuplicates(shades) {
92
167
  function toPoints(shades, groups) {
93
168
  return groups.map((members) => {
94
169
  let count = 0;
170
+ let salience = 0;
95
171
  const sum = [0, 0, 0];
96
172
  for (const m of members) {
97
173
  count += shades[m].count;
174
+ salience += shades[m].salienceSum;
98
175
  for (let c = 0; c < 3; c++)
99
176
  sum[c] += shades[m].oklab[c] * shades[m].count;
100
177
  }
@@ -102,23 +179,24 @@ function toPoints(shades, groups) {
102
179
  return {
103
180
  oklab,
104
181
  count,
182
+ salience: count > 0 ? salience / count : 1,
105
183
  members,
106
184
  };
107
185
  });
108
186
  }
109
187
  /** Weighted farthest-point seeding: start from the commonest colour, then keep adding the colour
110
- * that is farthest from every seed so far (lightly favouring frequent ones). */
111
- function seed(points, k) {
188
+ * that is farthest from every seed so far (weighted by count and local visual salience). */
189
+ function seed(points, k, chromaWeight) {
112
190
  let first = 0;
113
191
  for (let i = 1; i < points.length; i++)
114
192
  if (points[i].count > points[first].count)
115
193
  first = i;
116
194
  const seeds = [points[first].oklab];
117
- const nearest = points.map((p) => distance(p.oklab, seeds[0]));
195
+ const nearest = points.map((p) => distance(p.oklab, seeds[0], chromaWeight));
118
196
  while (seeds.length < k) {
119
197
  let pick = -1, pickScore = 0;
120
198
  for (let i = 0; i < points.length; i++) {
121
- const score = nearest[i] * points[i].count ** SEED_WEIGHT;
199
+ const score = nearest[i] * points[i].count ** SEED_WEIGHT * points[i].salience ** 0.5;
122
200
  if (score > pickScore) {
123
201
  pickScore = score;
124
202
  pick = i;
@@ -128,12 +206,12 @@ function seed(points, k) {
128
206
  break;
129
207
  seeds.push(points[pick].oklab);
130
208
  for (let i = 0; i < points.length; i++)
131
- nearest[i] = Math.min(nearest[i], distance(points[i].oklab, points[pick].oklab));
209
+ nearest[i] = Math.min(nearest[i], distance(points[i].oklab, points[pick].oklab, chromaWeight));
132
210
  }
133
211
  return seeds;
134
212
  }
135
- function cluster(points, k) {
136
- const centers = seed(points, k);
213
+ function cluster(points, k, chromaWeight) {
214
+ const centers = seed(points, k, chromaWeight);
137
215
  const assign = new Int32Array(points.length).fill(-1);
138
216
  // Flatten points and centres into typed arrays so the assignment loop avoids
139
217
  // per-access bounds checks and object property lookups in the inner loop.
@@ -144,7 +222,7 @@ function cluster(points, k) {
144
222
  pointData[i * 3] = points[i].oklab[0];
145
223
  pointData[i * 3 + 1] = points[i].oklab[1];
146
224
  pointData[i * 3 + 2] = points[i].oklab[2];
147
- pointWeight[i] = points[i].count ** PULL_WEIGHT;
225
+ pointWeight[i] = points[i].count ** PULL_WEIGHT * points[i].salience;
148
226
  }
149
227
  const centerData = new Float64Array(centers.length * 3);
150
228
  const writeCenter = (c, value) => {
@@ -165,7 +243,7 @@ function cluster(points, k) {
165
243
  const dx = px - centerData[c * 3];
166
244
  const dy = py - centerData[c * 3 + 1];
167
245
  const dz = pz - centerData[c * 3 + 2];
168
- const d = dx * dx + dy * dy + dz * dz;
246
+ const d = dx * dx + chromaWeight * (dy * dy + dz * dz);
169
247
  if (d < bestDistance) {
170
248
  bestDistance = d;
171
249
  best = c;
@@ -206,10 +284,10 @@ function paletteOklabs(palette) {
206
284
  rgb: visible.map((c) => c),
207
285
  };
208
286
  }
209
- function nearestPaletteRgb(oklab, oklabs, rgb) {
287
+ function nearestPaletteRgb(oklab, oklabs, rgb, chromaWeight = 1) {
210
288
  let best = 0, bestDistance = Infinity;
211
289
  for (let i = 0; i < oklabs.length; i++) {
212
- const d = distance(oklab, oklabs[i]);
290
+ const d = distance(oklab, oklabs[i], chromaWeight);
213
291
  if (d < bestDistance) {
214
292
  bestDistance = d;
215
293
  best = i;
@@ -319,35 +397,41 @@ function ditherToPalette(image, palette, dither) {
319
397
  ? orderedBayer8ToPalette(image, palette)
320
398
  : floydSteinbergToPalette(image, palette);
321
399
  }
322
- /** Build the reduced RGB palette (k-means or the given list); null when the image already fits. */
323
- function buildPalette(shades, options) {
324
- if (options.palette)
325
- return paletteOklabs(options.palette).rgb;
326
- const groups = mergeNearDuplicates(shades);
400
+ /** Cluster shades into a reduced OKLab palette (shared by flat remap and dither paths). */
401
+ function clusterShades(shades, options, chromaWeight) {
402
+ const mergeChromaWeight = options.adaptive ? 1 : chromaWeight;
403
+ const groups = mergeNearDuplicates(shades, mergeChromaWeight);
327
404
  const colors = options.adaptive
328
405
  ? Math.min(groups.length, MAX_COLORS)
329
406
  : Math.max(MIN_COLORS, Math.min(MAX_COLORS, Math.round(options.colors ?? DEFAULT_COLORS)));
330
407
  if (shades.length <= colors)
331
408
  return null;
332
409
  const points = toPoints(shades, groups);
333
- const assignment = points.length <= colors ? points.map((_, i) => i) : cluster(points, colors);
410
+ const assignment = points.length <= colors ? points.map((_, i) => i) : cluster(points, colors, chromaWeight);
334
411
  const sums = new Map();
335
412
  points.forEach((point, i) => {
336
- const entry = sums.get(assignment[i]) ?? { oklab: [0, 0, 0], count: 0 };
413
+ const entry = sums.get(assignment[i]) ?? { oklab: [0, 0, 0], weight: 0 };
414
+ const wt = point.count * point.salience;
337
415
  for (let c = 0; c < 3; c++)
338
- entry.oklab[c] += point.oklab[c] * point.count;
339
- entry.count += point.count;
416
+ entry.oklab[c] += point.oklab[c] * wt;
417
+ entry.weight += wt;
340
418
  sums.set(assignment[i], entry);
341
419
  });
342
420
  const palette = [];
343
- for (const { oklab, count } of sums.values()) {
344
- const [r, g, b] = oklabToRgb(oklab[0] / count, oklab[1] / count, oklab[2] / count);
345
- palette.push([r, g, b, 255]);
421
+ const paletteLabs = [];
422
+ for (const { oklab, weight } of sums.values()) {
423
+ const centerLab = [oklab[0] / weight, oklab[1] / weight, oklab[2] / weight];
424
+ const rgb = oklabToRgb(centerLab[0], centerLab[1], centerLab[2]);
425
+ palette.push([rgb[0], rgb[1], rgb[2], 255]);
426
+ paletteLabs.push(rgbToOklab(rgb[0], rgb[1], rgb[2]));
346
427
  }
347
- return palette;
428
+ // Reassign every shade directly to its closest final palette colour in chroma-weighted OKLab
429
+ // instead of locking shades to their greedy pre-merge leader group.
430
+ const shadeTargets = shades.map((shade) => nearestPaletteRgb(shade.oklab, paletteLabs, palette, chromaWeight));
431
+ return { palette, shadeTargets };
348
432
  }
349
433
  /** Flat nearest-shade remap (no positional dither). */
350
- function remapShades(image, shades, index, options) {
434
+ function remapShades(image, shades, index, options, chromaWeight) {
351
435
  const output = new Uint8ClampedArray(image.data);
352
436
  let target;
353
437
  if (options.palette) {
@@ -355,30 +439,10 @@ function remapShades(image, shades, index, options) {
355
439
  target = shades.map((shade) => nearestPaletteRgb(shade.oklab, oklabs, rgb));
356
440
  }
357
441
  else {
358
- const groups = mergeNearDuplicates(shades);
359
- const colors = options.adaptive
360
- ? Math.min(groups.length, MAX_COLORS)
361
- : Math.max(MIN_COLORS, Math.min(MAX_COLORS, Math.round(options.colors ?? DEFAULT_COLORS)));
362
- if (shades.length <= colors)
442
+ const clustered = clusterShades(shades, options, chromaWeight);
443
+ if (!clustered)
363
444
  return { width: image.width, height: image.height, data: output };
364
- const points = toPoints(shades, groups);
365
- const assignment = points.length <= colors ? points.map((_, i) => i) : cluster(points, colors);
366
- const sums = new Map();
367
- points.forEach((point, i) => {
368
- const entry = sums.get(assignment[i]) ?? { oklab: [0, 0, 0], count: 0 };
369
- for (let c = 0; c < 3; c++)
370
- entry.oklab[c] += point.oklab[c] * point.count;
371
- entry.count += point.count;
372
- sums.set(assignment[i], entry);
373
- });
374
- const colorOf = new Map();
375
- for (const [id, { oklab, count }] of sums)
376
- colorOf.set(id, oklabToRgb(oklab[0] / count, oklab[1] / count, oklab[2] / count));
377
- target = Array.from({ length: shades.length }, () => [0, 0, 0]);
378
- points.forEach((point, i) => {
379
- for (const member of point.members)
380
- target[member] = colorOf.get(assignment[i]);
381
- });
445
+ target = clustered.shadeTargets;
382
446
  }
383
447
  for (let i = 0; i < index.length; i++) {
384
448
  if (index[i] < 0)
@@ -395,11 +459,16 @@ export function snapPalette(image, options) {
395
459
  const dither = Object.values(PixelationDither).includes(options.dither)
396
460
  ? options.dither
397
461
  : PixelationDither.None;
398
- const { shades, index } = histogram(image);
399
- if (dither === PixelationDither.None)
400
- return remapShades(image, shades, index, options);
401
- // Ordered / Floyd–Steinberg need a concrete palette, then per-pixel OKLab nearest.
402
- const palette = buildPalette(shades, options);
462
+ const useSaliency = options.saliency !== false && !options.palette;
463
+ const chromaWeight = useSaliency ? SALIENCY_CHROMA_WEIGHT : 1;
464
+ const { shades, index } = histogram(image, useSaliency);
465
+ if (dither === PixelationDither.None) {
466
+ return remapShades(image, shades, index, options, chromaWeight);
467
+ }
468
+ // Ordered / Floyd–Steinberg need a concrete palette, then per-pixel nearest.
469
+ const palette = options.palette
470
+ ? paletteOklabs(options.palette).rgb
471
+ : (clusterShades(shades, options, chromaWeight)?.palette ?? null);
403
472
  if (!palette) {
404
473
  // Already within budget and no user palette: dither among the image's own shades.
405
474
  if (!shades.length)
@@ -1,15 +1,12 @@
1
1
  import type { PixelBuffer } from "./base.ts";
2
2
  import type { PixelateOptions } from "./types.ts";
3
3
  /**
4
- * Pixelate an RGBA buffer without touching the source. Nearest mode follows
5
- * nearest-neighbor `floor(dst * src / dst)` mapping. Box mode averages the
6
- * source area covered by each destination pixel. Local dominant and structural
7
- * sampling preserve contrasting regions; grid recovery restores one RGBA pixel
8
- * per detected cell. Limiting colours keeps each pixel's own alpha.
4
+ * Pixelate an RGBA buffer without touching the source.
5
+ * Uses a 4-stage strategy pipeline: Plan -> Prepass -> Sampler -> Alpha & Postprocess.
9
6
  */
10
7
  export declare function pixelateImage(image: PixelBuffer, options?: PixelateOptions): PixelBuffer;
11
8
  /**
12
- * Async pixelate for product Auto path (import-worker). Same output as pixelateImage;
13
- * Auto detect overlaps WASM AC+RL with proposers via Promise join (no COOP/COEP).
9
+ * Async counterpart of `pixelateImage`: only grid detection runs asynchronously (WASM consensus
10
+ * on a worker), then feeds the identical synchronous 4-stage pipeline.
14
11
  */
15
12
  export declare function pixelateImageAsync(image: PixelBuffer, options?: PixelateOptions): Promise<PixelBuffer>;