@xprite/pixelate 0.1.3 → 0.2.1

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.
Files changed (55) hide show
  1. package/README.md +14 -0
  2. package/README.zh-CN.md +14 -0
  3. package/dist/base.d.ts +4 -0
  4. package/dist/base.js +33 -0
  5. package/dist/deskew.js +28 -15
  6. package/dist/fft-autocorr.d.ts +12 -0
  7. package/dist/fft-autocorr.js +116 -0
  8. package/dist/float-image.d.ts +25 -0
  9. package/dist/float-image.js +184 -0
  10. package/dist/grid-arbitrate.d.ts +8 -0
  11. package/dist/grid-arbitrate.js +219 -65
  12. package/dist/grid-cut-snap.js +2 -38
  13. package/dist/grid-description-length.js +416 -111
  14. package/dist/grid-edge-coherence.js +4 -46
  15. package/dist/grid-edge-path.js +2 -33
  16. package/dist/grid-frame-lattice.js +109 -14
  17. package/dist/grid-period-comb.js +126 -22
  18. package/dist/grid-period-distance.js +59 -10
  19. package/dist/grid-pitch-lattice.js +21 -9
  20. package/dist/grid-pitch-search.js +38 -18
  21. package/dist/grid-sample.js +2 -2
  22. package/dist/grid-sampling.d.ts +6 -0
  23. package/dist/grid-sampling.js +111 -10
  24. package/dist/grid-step-profiles.d.ts +13 -0
  25. package/dist/grid-step-profiles.js +88 -0
  26. package/dist/grid-strip-shift.js +153 -35
  27. package/dist/index.d.ts +3 -0
  28. package/dist/index.js +3 -0
  29. package/dist/kuwahara.d.ts +9 -0
  30. package/dist/kuwahara.js +287 -0
  31. package/dist/line-guided/pixeloe-entry.d.ts +2 -2
  32. package/dist/line-guided/pixeloe-entry.js +6 -35
  33. package/dist/orphan-pixels.d.ts +7 -0
  34. package/dist/orphan-pixels.js +133 -0
  35. package/dist/palette-snap.d.ts +1 -1
  36. package/dist/palette-snap.js +127 -58
  37. package/dist/pixelate.d.ts +4 -7
  38. package/dist/pixelate.js +133 -98
  39. package/dist/quantization.d.ts +4 -0
  40. package/dist/quantization.js +23 -16
  41. package/dist/resize-crisp.d.ts +11 -0
  42. package/dist/resize-crisp.js +213 -0
  43. package/dist/resize-lanczos.d.ts +7 -0
  44. package/dist/resize-lanczos.js +205 -0
  45. package/dist/sampling.d.ts +2 -1
  46. package/dist/sampling.js +1 -1
  47. package/dist/settings.d.ts +6 -3
  48. package/dist/settings.js +26 -12
  49. package/dist/types.d.ts +14 -2
  50. package/dist/types.js +2 -2
  51. package/package.json +1 -1
  52. package/dist/contours.d.ts +0 -4
  53. package/dist/contours.js +0 -66
  54. package/dist/most-frequent.d.ts +0 -3
  55. package/dist/most-frequent.js +0 -56
@@ -0,0 +1,287 @@
1
+ import { assertDimension, assertPixelBuffer, createBufferMemo, } from "./base.js";
2
+ import { fromFloatRgba, gaussianBlur, resizeAreaFloat, sobelTensor, toFloatRgba, toOklabPlanes, } from "./float-image.js";
3
+ import { oklabToRgbFloat } from "./quantization.js";
4
+ const WORKING_SCALE = 4;
5
+ const MAX_WORKING_PIXELS = 1_048_576;
6
+ const CHANNELS = 4;
7
+ const KUWAHARA_RADIUS = 3.4;
8
+ const KUWAHARA_ALPHA = 1.0;
9
+ const KUWAHARA_SHARPNESS = 8;
10
+ const KUWAHARA_TENSOR_SIGMA = 1.5;
11
+ const KUWAHARA_PASSES = 2;
12
+ const KUWAHARA_SECTORS = 8;
13
+ const DETAIL_PROTECT_RADIUS_DROP = 0.62;
14
+ const CLARITY_AMOUNT = 0.54;
15
+ const CLARITY_SIGMA = 3.2;
16
+ const CLARITY_KNEE = 0.14;
17
+ const CLARITY_POS_GAIN = 0.72;
18
+ const CLARITY_NEG_GAIN = 0.92;
19
+ const S_CURVE_AMOUNT = 0.032;
20
+ const CHROMA_SAT_BOOST = 0.22;
21
+ const PIXEL_ART_EXACT_NEIGHBOR_CUTOFF = 0.45;
22
+ const FLAT_ART_RATIO_START = 0.45;
23
+ const FLAT_ART_SINGLE_PASS_CUTOFF = 0.52;
24
+ const rememberKuwahara = createBufferMemo();
25
+ /** Fast strided neighbor-flatness check so crisp pixel art & flat cel art aren't over-processed. */
26
+ function measureSourceProfile(image) {
27
+ const { width: w, height: h, data } = image;
28
+ if (w < 2 || h < 2)
29
+ return { exactNeighborRatio: 0, nearFlatRatio: 0 };
30
+ const stride = Math.max(1, Math.floor(Math.sqrt((w * h) / 16_384)));
31
+ let exact = 0;
32
+ let nearFlat = 0;
33
+ let pairs = 0;
34
+ for (let y = 0; y < h - 1; y += stride) {
35
+ for (let x = 0; x < w - 1; x += stride) {
36
+ const i = (y * w + x) * CHANNELS;
37
+ if (data[i + 3] < 128)
38
+ continue;
39
+ for (const j of [i + CHANNELS, i + w * CHANNELS]) {
40
+ if (data[j + 3] < 128)
41
+ continue;
42
+ pairs += 1;
43
+ const maxD = Math.max(Math.abs(data[i] - data[j]), Math.abs(data[i + 1] - data[j + 1]), Math.abs(data[i + 2] - data[j + 2]));
44
+ if (maxD === 0)
45
+ exact += 1;
46
+ if (maxD <= 3)
47
+ nearFlat += 1;
48
+ }
49
+ }
50
+ }
51
+ return pairs === 0
52
+ ? { exactNeighborRatio: 0, nearFlatRatio: 0 }
53
+ : { exactNeighborRatio: exact / pairs, nearFlatRatio: nearFlat / pairs };
54
+ }
55
+ function computeOrientation(img, sigma) {
56
+ const { E, F, G } = sobelTensor([img.r, img.g, img.b], img.w, img.h, sigma);
57
+ const n = img.w * img.h;
58
+ const cosT = new Float32Array(n);
59
+ const sinT = new Float32Array(n);
60
+ const aniso = new Float32Array(n);
61
+ for (let i = 0; i < n; i++) {
62
+ const e = E[i];
63
+ const f = F[i];
64
+ const g = G[i];
65
+ const disc = Math.sqrt((e - g) * (e - g) + 4 * f * f);
66
+ const l1 = 0.5 * (e + g + disc);
67
+ const l2 = 0.5 * (e + g - disc);
68
+ aniso[i] = (l1 - l2) / (l1 + l2 + 1e-6);
69
+ const tx = l1 - e;
70
+ const ty = -f;
71
+ const len = Math.hypot(tx, ty);
72
+ cosT[i] = len > 1e-7 ? tx / len : 1;
73
+ sinT[i] = len > 1e-7 ? ty / len : 0;
74
+ }
75
+ return { cosT, sinT, aniso };
76
+ }
77
+ /**
78
+ * OKLab micro-feature protection mask: detects isolated 1-2 output-pixel landmarks (eyes, lips,
79
+ * specular highlights) via Shi-Tomasi cornerness + luminance/chroma blobs while staying 0 on
80
+ * smooth planes and straight edges.
81
+ */
82
+ function computeMicroFeatureMask(img) {
83
+ const { a: srcA, w, h, opaque } = img;
84
+ const { L, A, B } = toOklabPlanes(img);
85
+ const g1 = gaussianBlur(L, w, h, 1.4);
86
+ const g2 = gaussianBlur(L, w, h, 5.0);
87
+ const a1 = gaussianBlur(A, w, h, 1.4);
88
+ const b1 = gaussianBlur(B, w, h, 1.4);
89
+ const a2 = gaussianBlur(A, w, h, 5.0);
90
+ const b2 = gaussianBlur(B, w, h, 5.0);
91
+ const { E, F, G } = sobelTensor([g1], w, h, 2.5);
92
+ const raw = new Float32Array(w * h);
93
+ for (let i = 0; i < raw.length; i++) {
94
+ if (!opaque && srcA[i] <= 1e-4)
95
+ continue;
96
+ const e = E[i];
97
+ const f = F[i];
98
+ const g = G[i];
99
+ const l2 = Math.max(0, 0.5 * (e + g - Math.sqrt((e - g) * (e - g) + 4 * f * f)));
100
+ const score = Math.sqrt(l2) * 5.0 +
101
+ Math.abs(g1[i] - g2[i]) * 2.2 +
102
+ Math.hypot(a1[i] - a2[i], b1[i] - b2[i]) * 4.0;
103
+ raw[i] = Math.min(1.0, Math.max(0, (score - 0.14) / 0.28));
104
+ }
105
+ return gaussianBlur(raw, w, h, 1.5);
106
+ }
107
+ /** Orientation-aligned 8-sector Anisotropic Kuwahara filter with local micro-feature radius protection. */
108
+ function anisotropicKuwahara(img, passes, radius, protect) {
109
+ let cur = img;
110
+ const { w, h, a: srcA, opaque } = img;
111
+ const cosSector = Math.cos(Math.PI / KUWAHARA_SECTORS);
112
+ const invSinSector2 = 1 / Math.sin(Math.PI / KUWAHARA_SECTORS) ** 2;
113
+ const mR = new Float64Array(KUWAHARA_SECTORS);
114
+ const mG = new Float64Array(KUWAHARA_SECTORS);
115
+ const mB = new Float64Array(KUWAHARA_SECTORS);
116
+ const sR = new Float64Array(KUWAHARA_SECTORS);
117
+ const sG = new Float64Array(KUWAHARA_SECTORS);
118
+ const sB = new Float64Array(KUWAHARA_SECTORS);
119
+ const wSum = new Float64Array(KUWAHARA_SECTORS);
120
+ const ws = new Float64Array(KUWAHARA_SECTORS);
121
+ for (let pass = 0; pass < passes; pass++) {
122
+ const { cosT, sinT, aniso } = computeOrientation(cur, KUWAHARA_TENSOR_SIGMA);
123
+ const outR = new Float32Array(w * h);
124
+ const outG = new Float32Array(w * h);
125
+ const outB = new Float32Array(w * h);
126
+ const { r: srcR, g: srcG, b: srcB } = cur;
127
+ for (let y = 0; y < h; y++) {
128
+ for (let x = 0; x < w; x++) {
129
+ const idx = y * w + x;
130
+ if (!opaque && srcA[idx] <= 1e-4)
131
+ continue;
132
+ const localRadius = Math.max(1.1, radius * (1 - DETAIL_PROTECT_RADIUS_DROP * protect[idx]));
133
+ const zeta = 2.0 / localRadius;
134
+ const eta = (zeta + cosSector) * invSinSector2;
135
+ const A = aniso[idx];
136
+ const aAxis = (localRadius * (KUWAHARA_ALPHA + A)) / KUWAHARA_ALPHA;
137
+ const bAxis = (localRadius * KUWAHARA_ALPHA) / (KUWAHARA_ALPHA + A);
138
+ const c = cosT[idx];
139
+ const s = sinT[idx];
140
+ const maxX = Math.ceil(Math.sqrt(aAxis * aAxis * c * c + bAxis * bAxis * s * s));
141
+ const maxY = Math.ceil(Math.sqrt(aAxis * aAxis * s * s + bAxis * bAxis * c * c));
142
+ const invA = 1 / aAxis;
143
+ const invB = 1 / bAxis;
144
+ mR.fill(0);
145
+ mG.fill(0);
146
+ mB.fill(0);
147
+ sR.fill(0);
148
+ sG.fill(0);
149
+ sB.fill(0);
150
+ wSum.fill(0);
151
+ for (let dy = -maxY; dy <= maxY; dy++) {
152
+ const row = Math.max(0, Math.min(h - 1, y + dy)) * w;
153
+ for (let dx = -maxX; dx <= maxX; dx++) {
154
+ const vx = (c * dx + s * dy) * invA;
155
+ const vy = (-s * dx + c * dy) * invB;
156
+ const r2 = vx * vx + vy * vy;
157
+ if (r2 > 1.0)
158
+ continue;
159
+ const p = row + Math.max(0, Math.min(w - 1, x + dx));
160
+ const alphaWeight = opaque ? 1 : srcA[p];
161
+ if (alphaWeight <= 1e-4)
162
+ continue;
163
+ const cr = srcR[p];
164
+ const cg = srcG[p];
165
+ const cb = srcB[p];
166
+ const gauss = Math.exp(-3.125 * r2) * alphaWeight;
167
+ const rx = 0.70710678 * (vx - vy);
168
+ const ry = 0.70710678 * (vx + vy);
169
+ const w0 = Math.max(0, vy + zeta - eta * vx * vx);
170
+ const w1 = Math.max(0, ry + zeta - eta * rx * rx);
171
+ const w2 = Math.max(0, -vx + zeta - eta * vy * vy);
172
+ const w3 = Math.max(0, -rx + zeta - eta * ry * ry);
173
+ const w4 = Math.max(0, -vy + zeta - eta * vx * vx);
174
+ const w5 = Math.max(0, -ry + zeta - eta * rx * rx);
175
+ const w6 = Math.max(0, vx + zeta - eta * vy * vy);
176
+ const w7 = Math.max(0, rx + zeta - eta * ry * ry);
177
+ ws[0] = w0 * w0;
178
+ ws[1] = w1 * w1;
179
+ ws[2] = w2 * w2;
180
+ ws[3] = w3 * w3;
181
+ ws[4] = w4 * w4;
182
+ ws[5] = w5 * w5;
183
+ ws[6] = w6 * w6;
184
+ ws[7] = w7 * w7;
185
+ for (let k = 0; k < KUWAHARA_SECTORS; k++) {
186
+ const wk = ws[k] * gauss;
187
+ if (wk > 1e-6) {
188
+ wSum[k] += wk;
189
+ mR[k] += wk * cr;
190
+ mG[k] += wk * cg;
191
+ mB[k] += wk * cb;
192
+ sR[k] += wk * cr * cr;
193
+ sG[k] += wk * cg * cg;
194
+ sB[k] += wk * cb * cb;
195
+ }
196
+ }
197
+ }
198
+ }
199
+ let accR = 0;
200
+ let accG = 0;
201
+ let accB = 0;
202
+ let accW = 0;
203
+ for (let k = 0; k < KUWAHARA_SECTORS; k++) {
204
+ if (wSum[k] <= 1e-8)
205
+ continue;
206
+ const inv = 1 / wSum[k];
207
+ const mr = mR[k] * inv;
208
+ const mg = mG[k] * inv;
209
+ const mb = mB[k] * inv;
210
+ const vr = Math.max(0, sR[k] * inv - mr * mr);
211
+ const vg = Math.max(0, sG[k] * inv - mg * mg);
212
+ const vb = Math.max(0, sB[k] * inv - mb * mb);
213
+ const wk = 1.0 / (1.0 + (Math.sqrt(vr + vg + vb) * 16.0) ** KUWAHARA_SHARPNESS);
214
+ accR += wk * mr;
215
+ accG += wk * mg;
216
+ accB += wk * mb;
217
+ accW += wk;
218
+ }
219
+ outR[idx] = accW > 0 ? accR / accW : srcR[idx];
220
+ outG[idx] = accW > 0 ? accG / accW : srcG[idx];
221
+ outB[idx] = accW > 0 ? accB / accW : srcB[idx];
222
+ }
223
+ }
224
+ cur = { r: outR, g: outG, b: outB, a: srcA, w, h, opaque };
225
+ }
226
+ return cur;
227
+ }
228
+ /** Neutral anti-halo OKLab local clarity plus shadow-safe chroma lift. */
229
+ function enhanceAntiHaloClarity(img, nearFlatRatio) {
230
+ const { a: srcA, w, h, opaque } = img;
231
+ const { L, A, B } = toOklabPlanes(img);
232
+ const flatScale = Math.max(0.28, Math.min(1.0, 1.0 - (nearFlatRatio - FLAT_ART_RATIO_START) * 2.2));
233
+ const clarityStrength = CLARITY_AMOUNT * flatScale;
234
+ const sCurve = S_CURVE_AMOUNT * flatScale;
235
+ const satBoost = CHROMA_SAT_BOOST * (0.4 + 0.6 * flatScale);
236
+ const blurL = gaussianBlur(L, w, h, CLARITY_SIGMA);
237
+ const n = w * h;
238
+ const oR = new Float32Array(n);
239
+ const oG = new Float32Array(n);
240
+ const oB = new Float32Array(n);
241
+ const invKnee2 = 1 / (CLARITY_KNEE * CLARITY_KNEE);
242
+ for (let i = 0; i < n; i++) {
243
+ if (!opaque && srcA[i] <= 1e-4)
244
+ continue;
245
+ const rawDelta = L[i] - blurL[i];
246
+ let delta = rawDelta / (1.0 + rawDelta * rawDelta * invKnee2);
247
+ delta *=
248
+ delta > 0
249
+ ? CLARITY_POS_GAIN * Math.min(1.0, Math.max(0.0, (0.98 - L[i]) * 5.0))
250
+ : CLARITY_NEG_GAIN;
251
+ let nl = Math.max(0, Math.min(1, L[i] + clarityStrength * delta));
252
+ nl = Math.max(0, Math.min(1, nl - sCurve * Math.sin(2 * Math.PI * (nl - 0.5))));
253
+ const chromaGate = Math.min(1.0, Math.max(0, (Math.hypot(A[i], B[i]) - 0.025) / 0.04));
254
+ const lumGate = Math.min(1.0, Math.max(0, (nl - 0.22) / 0.3));
255
+ const satScale = 1.0 + satBoost * chromaGate * (0.35 + 0.65 * lumGate);
256
+ const [nr, ng, nb] = oklabToRgbFloat(nl, A[i] * satScale, B[i] * satScale);
257
+ oR[i] = nr;
258
+ oG[i] = ng;
259
+ oB[i] = nb;
260
+ }
261
+ return { r: oR, g: oG, b: oB, a: srcA, w, h, opaque };
262
+ }
263
+ /**
264
+ * Cel-shading simplification pre-pass for photo/illustration pixelation:
265
+ * downscales to a 4× target working grid, runs detail-protected Anisotropic Kuwahara to flatten
266
+ * hatching/grain while preserving 1-2 px facial/specular landmarks, then applies neutral anti-halo
267
+ * OKLab clarity. Already-crisp flat pixel art is passed through untouched.
268
+ */
269
+ export function kuwaharaPrepass(image, target) {
270
+ assertPixelBuffer(image);
271
+ assertDimension(target.width, "target.width");
272
+ assertDimension(target.height, "target.height");
273
+ const profile = measureSourceProfile(image);
274
+ if (profile.exactNeighborRatio >= PIXEL_ART_EXACT_NEIGHBOR_CUTOFF) {
275
+ return { width: image.width, height: image.height, data: image.data.slice() };
276
+ }
277
+ const scale = Math.min(WORKING_SCALE, Math.sqrt(MAX_WORKING_PIXELS / (target.width * target.height)));
278
+ const workW = Math.min(image.width, Math.max(target.width, Math.round(target.width * scale)));
279
+ const workH = Math.min(image.height, Math.max(target.height, Math.round(target.height * scale)));
280
+ return rememberKuwahara(image, `c5:${workW}x${workH}`, () => {
281
+ const working = resizeAreaFloat(toFloatRgba(image), workW, workH);
282
+ const protect = computeMicroFeatureMask(working);
283
+ const isFlatArt = profile.nearFlatRatio >= FLAT_ART_SINGLE_PASS_CUTOFF;
284
+ const smoothed = anisotropicKuwahara(working, isFlatArt ? 1 : KUWAHARA_PASSES, isFlatArt ? 2.6 : KUWAHARA_RADIUS, protect);
285
+ return fromFloatRgba(enhanceAntiHaloClarity(smoothed, profile.nearFlatRatio));
286
+ });
287
+ }
@@ -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;