@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.
- package/README.md +14 -0
- package/README.zh-CN.md +14 -0
- package/dist/base.d.ts +4 -0
- package/dist/base.js +33 -0
- package/dist/deskew.js +28 -15
- package/dist/fft-autocorr.d.ts +12 -0
- package/dist/fft-autocorr.js +116 -0
- package/dist/float-image.d.ts +25 -0
- package/dist/float-image.js +184 -0
- package/dist/grid-arbitrate.d.ts +8 -0
- package/dist/grid-arbitrate.js +219 -65
- package/dist/grid-cut-snap.js +2 -38
- package/dist/grid-description-length.js +416 -111
- package/dist/grid-edge-coherence.js +4 -46
- package/dist/grid-edge-path.js +2 -33
- package/dist/grid-frame-lattice.js +109 -14
- package/dist/grid-period-comb.js +126 -22
- package/dist/grid-period-distance.js +59 -10
- package/dist/grid-pitch-lattice.js +21 -9
- package/dist/grid-pitch-search.js +38 -18
- package/dist/grid-sample.js +2 -2
- package/dist/grid-sampling.d.ts +6 -0
- package/dist/grid-sampling.js +111 -10
- package/dist/grid-step-profiles.d.ts +13 -0
- package/dist/grid-step-profiles.js +88 -0
- package/dist/grid-strip-shift.js +153 -35
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/kuwahara.d.ts +9 -0
- package/dist/kuwahara.js +287 -0
- package/dist/line-guided/pixeloe-entry.d.ts +2 -2
- package/dist/line-guided/pixeloe-entry.js +6 -35
- package/dist/orphan-pixels.d.ts +7 -0
- package/dist/orphan-pixels.js +133 -0
- package/dist/palette-snap.d.ts +1 -1
- package/dist/palette-snap.js +127 -58
- package/dist/pixelate.d.ts +4 -7
- package/dist/pixelate.js +133 -98
- package/dist/quantization.d.ts +4 -0
- package/dist/quantization.js +23 -16
- package/dist/resize-crisp.d.ts +11 -0
- package/dist/resize-crisp.js +213 -0
- package/dist/resize-lanczos.d.ts +7 -0
- package/dist/resize-lanczos.js +205 -0
- package/dist/sampling.d.ts +2 -1
- package/dist/sampling.js +1 -1
- package/dist/settings.d.ts +6 -3
- package/dist/settings.js +26 -12
- package/dist/types.d.ts +14 -2
- package/dist/types.js +2 -2
- package/package.json +1 -1
- package/dist/contours.d.ts +0 -4
- package/dist/contours.js +0 -66
- package/dist/most-frequent.d.ts +0 -3
- package/dist/most-frequent.js +0 -56
package/dist/palette-snap.js
CHANGED
|
@@ -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
|
-
|
|
37
|
-
function
|
|
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 (
|
|
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
|
-
/**
|
|
323
|
-
function
|
|
324
|
-
|
|
325
|
-
|
|
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],
|
|
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] *
|
|
339
|
-
entry.
|
|
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
|
-
|
|
344
|
-
|
|
345
|
-
|
|
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
|
-
|
|
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
|
|
359
|
-
|
|
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
|
-
|
|
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
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
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)
|
package/dist/pixelate.d.ts
CHANGED
|
@@ -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.
|
|
5
|
-
*
|
|
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
|
|
13
|
-
*
|
|
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>;
|
package/dist/pixelate.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
import { assertDimension, assertPixelBuffer } from "./base.js";
|
|
2
|
-
import { protectPixelationContours } from "./contours.js";
|
|
3
2
|
import { smoothPixelation } from "./denoise.js";
|
|
4
3
|
import { blockPartition } from "./grid.js";
|
|
5
4
|
import { prepareGridSampling } from "./grid-sampling.js";
|
|
5
|
+
import { kuwaharaPrepass } from "./kuwahara.js";
|
|
6
6
|
import { runPixeloe } from "./line-guided/pixeloe-entry.js";
|
|
7
|
-
import { resizeMostFrequent } from "./most-frequent.js";
|
|
8
7
|
import { applyOutlinePrepass, DEFAULT_LINE_GUIDE, runsStockPixeloe, } from "./outline-prepass.js";
|
|
9
|
-
import { removeOrphanPixels } from "./orphan-pixels.js";
|
|
8
|
+
import { cleanStraySpeckles, removeOrphanPixels } from "./orphan-pixels.js";
|
|
10
9
|
import { snapPalette } from "./palette-snap.js";
|
|
11
10
|
import { settlePixelAlpha } from "./pixel-alpha.js";
|
|
12
11
|
import { detectWithAlgorithm, detectWithAlgorithmAsync, recoverWithGrid, } from "./pixelation-algorithm-registry.js";
|
|
12
|
+
import { resizeCrisp2Means } from "./resize-crisp.js";
|
|
13
|
+
import { resizeLanczos } from "./resize-lanczos.js";
|
|
13
14
|
import { resizeBox, resizeNearest } from "./resize.js";
|
|
14
15
|
import { samplePixelation } from "./sampling.js";
|
|
15
|
-
import { OutlinePrepass, PixelationDither, PixelationMethod, PixelationMode,
|
|
16
|
+
import { OutlinePrepass, PixelationAlgorithm, PixelationDither, PixelationMethod, PixelationMode, } from "./types.js";
|
|
16
17
|
const WORKING_SCALE = 4;
|
|
17
18
|
const MAX_WORKING_PIXELS = 1_048_576;
|
|
18
19
|
const MAX_OUTLINE_STRENGTH = 100;
|
|
19
|
-
function
|
|
20
|
+
function capWorkingSize(image, target) {
|
|
20
21
|
const scale = Math.min(WORKING_SCALE, Math.sqrt(MAX_WORKING_PIXELS / (target.width * target.height)));
|
|
21
22
|
const width = Math.min(image.width, Math.max(1, Math.ceil(target.width * scale)));
|
|
22
23
|
const height = Math.min(image.height, Math.max(1, Math.ceil(target.height * scale)));
|
|
23
|
-
|
|
24
|
+
return image.width === width && image.height === height
|
|
24
25
|
? image
|
|
25
26
|
: resizeBox(image, width, height, "premultiplied");
|
|
26
|
-
return protectPixelationContours(working, outlineStrength);
|
|
27
27
|
}
|
|
28
28
|
function uniformBlocks(image, target) {
|
|
29
29
|
return {
|
|
@@ -33,68 +33,127 @@ function uniformBlocks(image, target) {
|
|
|
33
33
|
algorithm: PixelationAlgorithm.UniformGrid,
|
|
34
34
|
};
|
|
35
35
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
36
|
+
/**
|
|
37
|
+
* Strategy table for target-size samplers (`Working Image -> Target Grid`).
|
|
38
|
+
* Adding a new resize algorithm only requires registering an entry here.
|
|
39
|
+
*/
|
|
40
|
+
const RESIZE_SAMPLERS = {
|
|
41
|
+
[PixelationMethod.Crisp]: (image, ctx) => resizeCrisp2Means(image, ctx.plan.target.width, ctx.plan.target.height, ctx.outlineStrength),
|
|
42
|
+
[PixelationMethod.Lanczos]: (image, ctx) => resizeLanczos(image, ctx.plan.target.width, ctx.plan.target.height, Boolean(ctx.options.kuwahara)),
|
|
43
|
+
[PixelationMethod.Nearest]: (image, ctx) => resizeNearest(image, ctx.plan.target.width, ctx.plan.target.height),
|
|
44
|
+
[PixelationMethod.Box]: (image, ctx) => resizeBox(image, ctx.plan.target.width, ctx.plan.target.height, ctx.alphaMode),
|
|
45
|
+
[PixelationMethod.Dominant]: (image, ctx) => samplePixelation(capWorkingSize(image, ctx.plan.target), ctx.plan.target.width, ctx.plan.target.height, PixelationMethod.Dominant),
|
|
46
|
+
[PixelationMethod.Structure]: (image, ctx) => samplePixelation(capWorkingSize(image, ctx.plan.target), ctx.plan.target.width, ctx.plan.target.height, PixelationMethod.Structure),
|
|
47
|
+
};
|
|
48
|
+
/** Stage 0: normalize Convert, CustomSize, and RecoverGrid into one of two concrete plans. */
|
|
49
|
+
function buildPlan(image, options, method, detectedGrid) {
|
|
44
50
|
const mode = options.mode ??
|
|
45
|
-
(
|
|
51
|
+
(detectedGrid && (!("reliable" in detectedGrid) || detectedGrid.reliable)
|
|
46
52
|
? PixelationMode.RecoverGrid
|
|
47
53
|
: PixelationMode.Convert);
|
|
48
54
|
if (mode !== PixelationMode.Convert && mode !== PixelationMode.RecoverGrid)
|
|
49
55
|
throw new RangeError("Unknown pixelation mode.");
|
|
50
|
-
const prepass = options.prepass ?? OutlinePrepass.None;
|
|
51
|
-
const guide = prepass === OutlinePrepass.PixeloeLines ? (options.lineGuide ?? DEFAULT_LINE_GUIDE) : undefined;
|
|
52
56
|
if (mode === PixelationMode.RecoverGrid) {
|
|
53
|
-
|
|
54
|
-
if ("reliable" in found && !found.reliable)
|
|
57
|
+
if (!detectedGrid || ("reliable" in detectedGrid && !detectedGrid.reliable))
|
|
55
58
|
throw new Error("No consistent pixel grid was detected. Turn off Automatic grid and choose cell sizes.");
|
|
56
|
-
const
|
|
57
|
-
const
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
59
|
+
const upright = prepareGridSampling(image, detectedGrid);
|
|
60
|
+
const gridForRecover = { ...detectedGrid, rotation: undefined, sampling: undefined };
|
|
61
|
+
const target = { width: detectedGrid.width, height: detectedGrid.height };
|
|
62
|
+
if (detectedGrid.algorithm === PixelationAlgorithm.CustomSize) {
|
|
63
|
+
const prepass = options.prepass ?? OutlinePrepass.None;
|
|
64
|
+
const usesDirectResize = prepass === OutlinePrepass.None &&
|
|
65
|
+
(options.blockPicker === false ||
|
|
66
|
+
(Boolean(options.kuwahara) &&
|
|
67
|
+
(method === PixelationMethod.Crisp || method === PixelationMethod.Lanczos)));
|
|
68
|
+
return {
|
|
69
|
+
kind: "resize",
|
|
70
|
+
source: upright,
|
|
71
|
+
working: upright,
|
|
72
|
+
target,
|
|
73
|
+
preferBlockPicker: !usesDirectResize,
|
|
74
|
+
grid: gridForRecover,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
kind: "grid",
|
|
79
|
+
source: image,
|
|
80
|
+
working: upright,
|
|
81
|
+
target,
|
|
82
|
+
grid: gridForRecover,
|
|
83
|
+
};
|
|
64
84
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
85
|
+
return {
|
|
86
|
+
kind: "resize",
|
|
87
|
+
source: image,
|
|
88
|
+
working: image,
|
|
89
|
+
target: resolveTargetSize(image, options),
|
|
90
|
+
preferBlockPicker: Boolean(options.blockPicker),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function wantsGridDetection(options) {
|
|
94
|
+
return (options.mode === PixelationMode.RecoverGrid ||
|
|
95
|
+
(options.mode === undefined && options.algorithm !== undefined));
|
|
96
|
+
}
|
|
97
|
+
/** Stage 1-3: unified synchronous pipeline shared by `pixelateImage` and `pixelateImageAsync`. */
|
|
98
|
+
function runPipeline(plan, options, method) {
|
|
99
|
+
const prepass = options.prepass ?? OutlinePrepass.None;
|
|
100
|
+
const guide = prepass === OutlinePrepass.PixeloeLines ? (options.lineGuide ?? DEFAULT_LINE_GUIDE) : undefined;
|
|
76
101
|
const alphaMode = options.alphaMode ?? "straight";
|
|
77
102
|
if (alphaMode !== "straight" && alphaMode !== "premultiplied")
|
|
78
103
|
throw new RangeError("alphaMode must be 'straight' or 'premultiplied'");
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const {
|
|
104
|
+
const outlineStrength = options.outlineStrength ?? 0;
|
|
105
|
+
if (!Number.isFinite(outlineStrength) || outlineStrength < 0 || outlineStrength > MAX_OUTLINE_STRENGTH)
|
|
106
|
+
throw new RangeError("Outline protection must be between 0 and 100.");
|
|
107
|
+
const ctx = { plan, options, method, prepass, alphaMode, outlineStrength };
|
|
108
|
+
const stockPixeloe = plan.kind === "resize" &&
|
|
109
|
+
runsStockPixeloe({
|
|
110
|
+
prepass,
|
|
111
|
+
colorPicker: options.colorPicker,
|
|
112
|
+
mode: plan.grid ? PixelationMode.RecoverGrid : PixelationMode.Convert,
|
|
113
|
+
}, plan.grid);
|
|
114
|
+
// Stage 1: Prepass strategy (optional Kuwahara simplification, then optional independent PixelOE prepass).
|
|
115
|
+
let working = plan.working;
|
|
116
|
+
if (plan.kind === "resize" && options.kuwahara) {
|
|
117
|
+
working = kuwaharaPrepass(working, plan.target);
|
|
118
|
+
}
|
|
119
|
+
if (!stockPixeloe && prepass !== OutlinePrepass.None) {
|
|
120
|
+
const cell = plan.kind === "grid"
|
|
121
|
+
? (plan.grid.cellWidth + plan.grid.cellHeight) / 2
|
|
122
|
+
: (working.width / plan.target.width + working.height / plan.target.height) / 2;
|
|
123
|
+
working = applyOutlinePrepass(working, cell, prepass, options.lineGuide);
|
|
124
|
+
}
|
|
125
|
+
// Stage 2: Sampler strategy (end-to-end PixelOE, grid cell picker, or target-size sampler table).
|
|
83
126
|
let sampled;
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
break;
|
|
91
|
-
case PixelationMethod.MostFrequent:
|
|
92
|
-
sampled = resizeMostFrequent(prepared, width, height);
|
|
93
|
-
break;
|
|
94
|
-
default:
|
|
95
|
-
sampled = samplePixelation(prepared, width, height, method);
|
|
127
|
+
let needsAlphaSettle = false;
|
|
128
|
+
if (stockPixeloe) {
|
|
129
|
+
sampled = runPixeloe(working, plan.target, guide);
|
|
130
|
+
}
|
|
131
|
+
else if (plan.kind === "grid") {
|
|
132
|
+
sampled = recoverWithGrid(working, plan.grid, options.colorPicker);
|
|
96
133
|
}
|
|
97
|
-
|
|
134
|
+
else if (plan.preferBlockPicker) {
|
|
135
|
+
const grid = !plan.grid || working.width !== plan.working.width || working.height !== plan.working.height
|
|
136
|
+
? uniformBlocks(working, plan.target)
|
|
137
|
+
: plan.grid;
|
|
138
|
+
sampled = recoverWithGrid(working, grid, options.colorPicker);
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
sampled = RESIZE_SAMPLERS[method](working, ctx);
|
|
142
|
+
needsAlphaSettle = true;
|
|
143
|
+
}
|
|
144
|
+
// Stage 3: Unified alpha settlement for direct resize samplers.
|
|
145
|
+
if (needsAlphaSettle) {
|
|
146
|
+
sampled = settlePixelAlpha(plan.source, sampled);
|
|
147
|
+
}
|
|
148
|
+
// Stage 4: Postprocess + Quantizer strategy.
|
|
149
|
+
const crispSpeckleDeltaE = plan.kind === "resize" &&
|
|
150
|
+
!stockPixeloe &&
|
|
151
|
+
!plan.preferBlockPicker &&
|
|
152
|
+
method === PixelationMethod.Crisp &&
|
|
153
|
+
outlineStrength < 75
|
|
154
|
+
? 0.22 * (1 - 0.7 * (outlineStrength / 100))
|
|
155
|
+
: 0;
|
|
156
|
+
return finishPixelation(sampled, plan.source, options, crispSpeckleDeltaE);
|
|
98
157
|
}
|
|
99
158
|
function sizeFromBlock(blockSize, image) {
|
|
100
159
|
if (typeof blockSize === "number") {
|
|
@@ -156,13 +215,16 @@ function validateMethod(value) {
|
|
|
156
215
|
throw new RangeError("Unknown pixelation method.");
|
|
157
216
|
return method;
|
|
158
217
|
}
|
|
159
|
-
function finishPixelation(sampled, source, { removeNoise, paletteSnap, preserveDimensions }) {
|
|
218
|
+
function finishPixelation(sampled, source, { removeNoise, paletteSnap, preserveDimensions }, crispSpeckleDeltaE = 0) {
|
|
160
219
|
let result = removeNoise ? smoothPixelation(sampled) : sampled;
|
|
161
220
|
if (paletteSnap)
|
|
162
221
|
result = snapPalette(result, paletteSnap);
|
|
222
|
+
const dither = paletteSnap?.dither;
|
|
223
|
+
const dithered = dither === PixelationDither.Ordered || dither === PixelationDither.FloydSteinberg;
|
|
224
|
+
if (crispSpeckleDeltaE > 0 && !dithered) {
|
|
225
|
+
result = cleanStraySpeckles(result, crispSpeckleDeltaE);
|
|
226
|
+
}
|
|
163
227
|
if (removeNoise) {
|
|
164
|
-
const dither = paletteSnap?.dither;
|
|
165
|
-
const dithered = dither === PixelationDither.Ordered || dither === PixelationDither.FloydSteinberg;
|
|
166
228
|
result = removeOrphanPixels(result, { absorbInterior: !dithered });
|
|
167
229
|
}
|
|
168
230
|
if (preserveDimensions && (result.width !== source.width || result.height !== source.height))
|
|
@@ -170,55 +232,28 @@ function finishPixelation(sampled, source, { removeNoise, paletteSnap, preserveD
|
|
|
170
232
|
return result;
|
|
171
233
|
}
|
|
172
234
|
/**
|
|
173
|
-
* Pixelate an RGBA buffer without touching the source.
|
|
174
|
-
*
|
|
175
|
-
* source area covered by each destination pixel. Local dominant and structural
|
|
176
|
-
* sampling preserve contrasting regions; grid recovery restores one RGBA pixel
|
|
177
|
-
* per detected cell. Limiting colours keeps each pixel's own alpha.
|
|
235
|
+
* Pixelate an RGBA buffer without touching the source.
|
|
236
|
+
* Uses a 4-stage strategy pipeline: Plan -> Prepass -> Sampler -> Alpha & Postprocess.
|
|
178
237
|
*/
|
|
179
238
|
export function pixelateImage(image, options = {}) {
|
|
180
239
|
assertPixelBuffer(image);
|
|
181
240
|
const method = validateMethod(options.method);
|
|
182
|
-
return finishPixelation(sampleImage(image, options, method), image, options);
|
|
183
|
-
}
|
|
184
|
-
async function sampleImageAsync(image, options, method) {
|
|
185
|
-
const wantsGrid = options.mode === PixelationMode.RecoverGrid ||
|
|
186
|
-
(options.mode === undefined && options.algorithm !== undefined);
|
|
187
241
|
const grid = options.grid ??
|
|
188
|
-
(
|
|
189
|
-
?
|
|
242
|
+
(wantsGridDetection(options)
|
|
243
|
+
? detectWithAlgorithm(image, options.algorithm ?? PixelationAlgorithm.Auto)
|
|
190
244
|
: undefined);
|
|
191
|
-
|
|
192
|
-
(grid && (!("reliable" in grid) || grid.reliable)
|
|
193
|
-
? PixelationMode.RecoverGrid
|
|
194
|
-
: PixelationMode.Convert);
|
|
195
|
-
if (mode !== PixelationMode.Convert && mode !== PixelationMode.RecoverGrid)
|
|
196
|
-
throw new RangeError("Unknown pixelation mode.");
|
|
197
|
-
const prepass = options.prepass ?? OutlinePrepass.None;
|
|
198
|
-
const guide = prepass === OutlinePrepass.PixeloeLines ? (options.lineGuide ?? DEFAULT_LINE_GUIDE) : undefined;
|
|
199
|
-
if (mode === PixelationMode.RecoverGrid) {
|
|
200
|
-
const found = grid ??
|
|
201
|
-
(await detectWithAlgorithmAsync(image, options.algorithm ?? PixelationAlgorithm.Auto));
|
|
202
|
-
if ("reliable" in found && !found.reliable)
|
|
203
|
-
throw new Error("No consistent pixel grid was detected. Turn off Automatic grid and choose cell sizes.");
|
|
204
|
-
const cell = (found.cellWidth + found.cellHeight) / 2;
|
|
205
|
-
const analysis = found;
|
|
206
|
-
const upright = prepareGridSampling(image, analysis);
|
|
207
|
-
const gridForRecover = { ...analysis, rotation: undefined, sampling: undefined };
|
|
208
|
-
if (runsStockPixeloe({ ...options, mode }, found))
|
|
209
|
-
return runPixeloe(upright, { width: found.width, height: found.height }, guide);
|
|
210
|
-
return recoverWithGrid(applyOutlinePrepass(upright, cell, prepass, options.lineGuide), gridForRecover, options.colorPicker);
|
|
211
|
-
}
|
|
212
|
-
// Convert path is sync — reuse sampleImage body for non-recover.
|
|
213
|
-
return sampleImage(image, { ...options, grid: undefined, mode: PixelationMode.Convert }, method);
|
|
245
|
+
return runPipeline(buildPlan(image, options, method, grid), options, method);
|
|
214
246
|
}
|
|
215
247
|
/**
|
|
216
|
-
* Async
|
|
217
|
-
*
|
|
248
|
+
* Async counterpart of `pixelateImage`: only grid detection runs asynchronously (WASM consensus
|
|
249
|
+
* on a worker), then feeds the identical synchronous 4-stage pipeline.
|
|
218
250
|
*/
|
|
219
251
|
export async function pixelateImageAsync(image, options = {}) {
|
|
220
252
|
assertPixelBuffer(image);
|
|
221
253
|
const method = validateMethod(options.method);
|
|
222
|
-
const
|
|
223
|
-
|
|
254
|
+
const grid = options.grid ??
|
|
255
|
+
(wantsGridDetection(options)
|
|
256
|
+
? await detectWithAlgorithmAsync(image, options.algorithm ?? PixelationAlgorithm.Auto)
|
|
257
|
+
: undefined);
|
|
258
|
+
return runPipeline(buildPlan(image, options, method, grid), options, method);
|
|
224
259
|
}
|