agglomerative-clustering 3.7.1 → 3.8.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.
- package/README.md +8 -7
- package/dist/choose.cjs +166 -0
- package/dist/choose.mjs +160 -0
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +60 -4
- package/dist/index.d.cts +37 -10
- package/dist/index.d.ts +37 -10
- package/dist/index.mjs +59 -3
- package/dist/shared.cjs +11 -3
- package/dist/shared.mjs +11 -3
- package/dist/worker-thread.mjs +13 -2
- package/dist/worker.cjs +176 -65
- package/dist/worker.d.cts +51 -8
- package/dist/worker.d.ts +51 -8
- package/dist/worker.mjs +177 -66
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -96,19 +96,20 @@ The one-shot functions (`buildPalette`, `quantize`, …) do every step for you.
|
|
|
96
96
|
|
|
97
97
|
| You want | from the image | from a clustering you hold¹ | with a palette you supply |
|
|
98
98
|
|---|---|---|---|
|
|
99
|
-
| a palette (flat RGB) | `buildPalette` | `clustering.getPalette(k)`
|
|
100
|
-
| a palette with each colour's share | `buildSwatches` | `clustering.getSwatches(k)`
|
|
101
|
-
| the image reduced to those colours | `quantize` | `clustering.quantize(image, k)`
|
|
102
|
-
| palette indices (GIF, PNG-8) | `quantizeToIndices` | `clustering.quantizeToIndices(image, k)`
|
|
103
|
-
| its error curve, for choosing a palette size | | `clustering.getClusteringInfo()`
|
|
99
|
+
| a palette (flat RGB) | `buildPalette` | `clustering.getPalette(k)` | |
|
|
100
|
+
| a palette with each colour's share | `buildSwatches` | `clustering.getSwatches(k)` | |
|
|
101
|
+
| the image reduced to those colours | `quantize` | `clustering.quantize(image, k)` | `quantizeWithPalette` |
|
|
102
|
+
| palette indices (GIF, PNG-8) | `quantizeToIndices` | `clustering.quantizeToIndices(image, k)` | `quantizeToIndicesWithPalette` |
|
|
103
|
+
| its error curve, for choosing a palette size | | `clustering.getClusteringInfo()` | |
|
|
104
|
+
| the `k` entries of a fixed palette (threads, bricks) that best fit | | `clustering.chooseFrom(palette, k)` | |
|
|
104
105
|
|
|
105
106
|
A clustering you hold has **methods** that take the colours from it, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `buildClustering` builds a clustering, and `init` loads the WebAssembly module (optional). Most code only needs the first column.
|
|
106
107
|
|
|
107
108
|
The verb says how much work a call does. `build…` clusters an image (tens of milliseconds for a photo). `get…` reads or cuts what a clustering or a worker handle already holds (well under a millisecond). `quantize…` maps pixels. So `buildPalette(image, k)` and `clustering.getPalette(k)` give the same kind of result from different starting points. The `build…` names arrived in 3.4.0; [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md) has the old ones.
|
|
108
109
|
|
|
109
|
-
**
|
|
110
|
+
**Where to call them.** On the main thread, or in a Node script, use the methods: they are the shortest way to cut one clustering many times. **Off the thread, use a handle**: `worker.cluster(image)` keeps an image and its clustering in the worker, and `worker.load(clustering)` keeps a stored clustering (`await using loaded = await worker.load(stored)`, then `loaded.getPalette(k)` and `loaded.quantize(image, k)`). The methods always run on the thread that calls them, with the main entry, and reject with `wasm-load-failed` where only the worker entry is imported.
|
|
110
111
|
|
|
111
|
-
¹
|
|
112
|
+
¹ The `…FromClustering` functions (`getPaletteFromClustering(clustering, k)`, `quantizeFromClustering(image, clustering, k)` and the rest) do the same as the methods. They are deprecated from 3.8 and removed in 4.0: see [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md#deprecated-in-38-removed-in-40) for the replacement of each, and [Clustering methods](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#clustering-methods).
|
|
112
113
|
|
|
113
114
|
Palettes come in **split order**: the palette for `k + 1` is the one for `k` with one colour split in two, so entries keep their place as `k` grows (they are not sorted by share). The options are `precision` (6 is about 3× faster at practically the same quality), `colorSpace` (`'rgb'` or `'oklab'`), `alpha`, `transparent`, `dither` (Floyd–Steinberg, Atkinson, or ordered for animation, which keeps still areas still), `width`, `signal` and `onProgress`: see the [API reference](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md).
|
|
114
115
|
|
package/dist/choose.cjs
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.choose = choose;
|
|
7
|
+
// The search behind clustering.chooseFrom: k entries of a fixed palette that represent a clustered image well. It is the
|
|
8
|
+
// guides' chooseThreads + improveThreads (docs/guides.md), plus a fill step so the result always has k entries. It runs
|
|
9
|
+
// on whatever thread calls it and reaches the WebAssembly only through the functions it is given.
|
|
10
|
+
|
|
11
|
+
// Colours (3 bytes each) as coordinates to measure distance in: OKLab, or the sRGB values themselves.
|
|
12
|
+
function coordinates(rgb, space) {
|
|
13
|
+
if (space === 'rgb') {
|
|
14
|
+
return Float64Array.from(rgb);
|
|
15
|
+
}
|
|
16
|
+
const linear = v => (v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
|
|
17
|
+
const out = new Float64Array(rgb.length);
|
|
18
|
+
for (let i = 0; i < rgb.length; i += 3) {
|
|
19
|
+
const r = linear(rgb[i]),
|
|
20
|
+
g = linear(rgb[i + 1]),
|
|
21
|
+
b = linear(rgb[i + 2]);
|
|
22
|
+
const l = Math.cbrt(0.4122214708 * r + 0.5363329343 * g + 0.0514459929 * b);
|
|
23
|
+
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
24
|
+
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
25
|
+
out[i] = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s;
|
|
26
|
+
out[i + 1] = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s;
|
|
27
|
+
out[i + 2] = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s;
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Positions in `entries`, in search order (unsorted), exactly k of them.
|
|
33
|
+
// cut(k) → the k-colour palette; swatches() → {palette, weights} of the 1024 cut; snap(colours) → the nearest entry of
|
|
34
|
+
// each colour (RGB); pause() → checks the signal, and yields when one was given.
|
|
35
|
+
async function choose({
|
|
36
|
+
cut,
|
|
37
|
+
swatches,
|
|
38
|
+
snap,
|
|
39
|
+
pause
|
|
40
|
+
}, entries, k, space) {
|
|
41
|
+
const t = entries.length / 3;
|
|
42
|
+
const {
|
|
43
|
+
palette: colors,
|
|
44
|
+
weights
|
|
45
|
+
} = await swatches();
|
|
46
|
+
const m = weights.length;
|
|
47
|
+
// Nothing to fit (an empty image): the first k entries, the only choice there is.
|
|
48
|
+
if (m === 0) {
|
|
49
|
+
return Array.from({
|
|
50
|
+
length: k
|
|
51
|
+
}, (_, j) => j);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Snap: the cuts from k up, each colour to its nearest entry; the first k distinct, in split order.
|
|
55
|
+
let chosen = [];
|
|
56
|
+
for (let c = k; c <= 4 * k && chosen.length < k; c++) {
|
|
57
|
+
await pause();
|
|
58
|
+
chosen = [...new Set(await snap(await cut(c)))].slice(0, k);
|
|
59
|
+
}
|
|
60
|
+
const a = coordinates(entries, space),
|
|
61
|
+
b = coordinates(colors, space);
|
|
62
|
+
const distance = new Float64Array(t * m); // distance[j * m + i]: squared, from entry j to swatch i
|
|
63
|
+
for (let j = 0; j < t; j++) {
|
|
64
|
+
for (let i = 0; i < m; i++) {
|
|
65
|
+
const dx = a[3 * j] - b[3 * i],
|
|
66
|
+
dy = a[3 * j + 1] - b[3 * i + 1],
|
|
67
|
+
dz = a[3 * j + 2] - b[3 * i + 2];
|
|
68
|
+
distance[j * m + i] = dx * dx + dy * dy + dz * dz;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Fill: with fewer than k distinct entries, add the entry that lowers the error most, one at a time (ties: lower j).
|
|
73
|
+
chosen = [...chosen];
|
|
74
|
+
if (chosen.length < k) {
|
|
75
|
+
const nearestDistance = new Float64Array(m).fill(Infinity);
|
|
76
|
+
for (const j of chosen) {
|
|
77
|
+
for (let i = 0; i < m; i++) {
|
|
78
|
+
nearestDistance[i] = Math.min(nearestDistance[i], distance[j * m + i]);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
while (chosen.length < k) {
|
|
82
|
+
await pause();
|
|
83
|
+
let best = -1,
|
|
84
|
+
lowest = Infinity;
|
|
85
|
+
for (let j = 0; j < t; j++) {
|
|
86
|
+
if (chosen.includes(j)) {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
let sum = 0;
|
|
90
|
+
for (let i = 0; i < m; i++) {
|
|
91
|
+
sum += weights[i] * Math.min(nearestDistance[i], distance[j * m + i]);
|
|
92
|
+
}
|
|
93
|
+
if (best < 0 || sum < lowest) {
|
|
94
|
+
lowest = sum;
|
|
95
|
+
best = j;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
chosen.push(best);
|
|
99
|
+
for (let i = 0; i < m; i++) {
|
|
100
|
+
nearestDistance[i] = Math.min(nearestDistance[i], distance[best * m + i]);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Swap: entries in and out of `chosen` while that brings the image closer, measured on the swatches.
|
|
106
|
+
const n = chosen.length;
|
|
107
|
+
const nearest = new Int32Array(m),
|
|
108
|
+
first = new Float64Array(m),
|
|
109
|
+
second = new Float64Array(m),
|
|
110
|
+
change = new Float64Array(n);
|
|
111
|
+
for (;;) {
|
|
112
|
+
await pause();
|
|
113
|
+
// Each swatch's nearest chosen entry (its position in `chosen`) and the distances to the nearest two.
|
|
114
|
+
let current = 0;
|
|
115
|
+
for (let i = 0; i < m; i++) {
|
|
116
|
+
let f = Infinity,
|
|
117
|
+
g = Infinity,
|
|
118
|
+
near = 0;
|
|
119
|
+
for (let s = 0; s < n; s++) {
|
|
120
|
+
const d = distance[chosen[s] * m + i];
|
|
121
|
+
if (d < f) {
|
|
122
|
+
g = f;
|
|
123
|
+
f = d;
|
|
124
|
+
near = s;
|
|
125
|
+
} else if (d < g) {
|
|
126
|
+
g = d;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
nearest[i] = near;
|
|
130
|
+
first[i] = f;
|
|
131
|
+
second[i] = g;
|
|
132
|
+
current += weights[i] * f;
|
|
133
|
+
}
|
|
134
|
+
// For each unchosen entry j, one pass over the swatches gives the error after swapping j in at every position s:
|
|
135
|
+
// current + shared + change[s]. Keep the best swap, if any is better.
|
|
136
|
+
let best = null,
|
|
137
|
+
lowest = current * (1 - 1e-9);
|
|
138
|
+
for (let j = 0; j < t; j++) {
|
|
139
|
+
if (j % 64 === 63) {
|
|
140
|
+
await pause();
|
|
141
|
+
}
|
|
142
|
+
if (chosen.includes(j)) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
let shared = 0;
|
|
146
|
+
change.fill(0);
|
|
147
|
+
for (let i = 0; i < m; i++) {
|
|
148
|
+
const d = distance[j * m + i],
|
|
149
|
+
gain = d < first[i] ? weights[i] * (d - first[i]) : 0;
|
|
150
|
+
shared += gain;
|
|
151
|
+
change[nearest[i]] += weights[i] * (Math.min(d, second[i]) - first[i]) - gain;
|
|
152
|
+
}
|
|
153
|
+
for (let s = 0; s < n; s++) {
|
|
154
|
+
const error = current + shared + change[s];
|
|
155
|
+
if (error < lowest) {
|
|
156
|
+
lowest = error;
|
|
157
|
+
best = [s, j];
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (!best) {
|
|
162
|
+
return chosen;
|
|
163
|
+
}
|
|
164
|
+
chosen[best[0]] = best[1];
|
|
165
|
+
}
|
|
166
|
+
}
|
package/dist/choose.mjs
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// The search behind clustering.chooseFrom: k entries of a fixed palette that represent a clustered image well. It is the
|
|
2
|
+
// guides' chooseThreads + improveThreads (docs/guides.md), plus a fill step so the result always has k entries. It runs
|
|
3
|
+
// on whatever thread calls it and reaches the WebAssembly only through the functions it is given.
|
|
4
|
+
|
|
5
|
+
// Colours (3 bytes each) as coordinates to measure distance in: OKLab, or the sRGB values themselves.
|
|
6
|
+
function coordinates(rgb, space) {
|
|
7
|
+
if (space === 'rgb') {
|
|
8
|
+
return Float64Array.from(rgb);
|
|
9
|
+
}
|
|
10
|
+
const linear = v => (v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
|
|
11
|
+
const out = new Float64Array(rgb.length);
|
|
12
|
+
for (let i = 0; i < rgb.length; i += 3) {
|
|
13
|
+
const r = linear(rgb[i]),
|
|
14
|
+
g = linear(rgb[i + 1]),
|
|
15
|
+
b = linear(rgb[i + 2]);
|
|
16
|
+
const l = Math.cbrt(0.4122214708 * r + 0.5363329343 * g + 0.0514459929 * b);
|
|
17
|
+
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
18
|
+
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
19
|
+
out[i] = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s;
|
|
20
|
+
out[i + 1] = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s;
|
|
21
|
+
out[i + 2] = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s;
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Positions in `entries`, in search order (unsorted), exactly k of them.
|
|
27
|
+
// cut(k) → the k-colour palette; swatches() → {palette, weights} of the 1024 cut; snap(colours) → the nearest entry of
|
|
28
|
+
// each colour (RGB); pause() → checks the signal, and yields when one was given.
|
|
29
|
+
export async function choose({
|
|
30
|
+
cut,
|
|
31
|
+
swatches,
|
|
32
|
+
snap,
|
|
33
|
+
pause
|
|
34
|
+
}, entries, k, space) {
|
|
35
|
+
const t = entries.length / 3;
|
|
36
|
+
const {
|
|
37
|
+
palette: colors,
|
|
38
|
+
weights
|
|
39
|
+
} = await swatches();
|
|
40
|
+
const m = weights.length;
|
|
41
|
+
// Nothing to fit (an empty image): the first k entries, the only choice there is.
|
|
42
|
+
if (m === 0) {
|
|
43
|
+
return Array.from({
|
|
44
|
+
length: k
|
|
45
|
+
}, (_, j) => j);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Snap: the cuts from k up, each colour to its nearest entry; the first k distinct, in split order.
|
|
49
|
+
let chosen = [];
|
|
50
|
+
for (let c = k; c <= 4 * k && chosen.length < k; c++) {
|
|
51
|
+
await pause();
|
|
52
|
+
chosen = [...new Set(await snap(await cut(c)))].slice(0, k);
|
|
53
|
+
}
|
|
54
|
+
const a = coordinates(entries, space),
|
|
55
|
+
b = coordinates(colors, space);
|
|
56
|
+
const distance = new Float64Array(t * m); // distance[j * m + i]: squared, from entry j to swatch i
|
|
57
|
+
for (let j = 0; j < t; j++) {
|
|
58
|
+
for (let i = 0; i < m; i++) {
|
|
59
|
+
const dx = a[3 * j] - b[3 * i],
|
|
60
|
+
dy = a[3 * j + 1] - b[3 * i + 1],
|
|
61
|
+
dz = a[3 * j + 2] - b[3 * i + 2];
|
|
62
|
+
distance[j * m + i] = dx * dx + dy * dy + dz * dz;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Fill: with fewer than k distinct entries, add the entry that lowers the error most, one at a time (ties: lower j).
|
|
67
|
+
chosen = [...chosen];
|
|
68
|
+
if (chosen.length < k) {
|
|
69
|
+
const nearestDistance = new Float64Array(m).fill(Infinity);
|
|
70
|
+
for (const j of chosen) {
|
|
71
|
+
for (let i = 0; i < m; i++) {
|
|
72
|
+
nearestDistance[i] = Math.min(nearestDistance[i], distance[j * m + i]);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
while (chosen.length < k) {
|
|
76
|
+
await pause();
|
|
77
|
+
let best = -1,
|
|
78
|
+
lowest = Infinity;
|
|
79
|
+
for (let j = 0; j < t; j++) {
|
|
80
|
+
if (chosen.includes(j)) {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
let sum = 0;
|
|
84
|
+
for (let i = 0; i < m; i++) {
|
|
85
|
+
sum += weights[i] * Math.min(nearestDistance[i], distance[j * m + i]);
|
|
86
|
+
}
|
|
87
|
+
if (best < 0 || sum < lowest) {
|
|
88
|
+
lowest = sum;
|
|
89
|
+
best = j;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
chosen.push(best);
|
|
93
|
+
for (let i = 0; i < m; i++) {
|
|
94
|
+
nearestDistance[i] = Math.min(nearestDistance[i], distance[best * m + i]);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Swap: entries in and out of `chosen` while that brings the image closer, measured on the swatches.
|
|
100
|
+
const n = chosen.length;
|
|
101
|
+
const nearest = new Int32Array(m),
|
|
102
|
+
first = new Float64Array(m),
|
|
103
|
+
second = new Float64Array(m),
|
|
104
|
+
change = new Float64Array(n);
|
|
105
|
+
for (;;) {
|
|
106
|
+
await pause();
|
|
107
|
+
// Each swatch's nearest chosen entry (its position in `chosen`) and the distances to the nearest two.
|
|
108
|
+
let current = 0;
|
|
109
|
+
for (let i = 0; i < m; i++) {
|
|
110
|
+
let f = Infinity,
|
|
111
|
+
g = Infinity,
|
|
112
|
+
near = 0;
|
|
113
|
+
for (let s = 0; s < n; s++) {
|
|
114
|
+
const d = distance[chosen[s] * m + i];
|
|
115
|
+
if (d < f) {
|
|
116
|
+
g = f;
|
|
117
|
+
f = d;
|
|
118
|
+
near = s;
|
|
119
|
+
} else if (d < g) {
|
|
120
|
+
g = d;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
nearest[i] = near;
|
|
124
|
+
first[i] = f;
|
|
125
|
+
second[i] = g;
|
|
126
|
+
current += weights[i] * f;
|
|
127
|
+
}
|
|
128
|
+
// For each unchosen entry j, one pass over the swatches gives the error after swapping j in at every position s:
|
|
129
|
+
// current + shared + change[s]. Keep the best swap, if any is better.
|
|
130
|
+
let best = null,
|
|
131
|
+
lowest = current * (1 - 1e-9);
|
|
132
|
+
for (let j = 0; j < t; j++) {
|
|
133
|
+
if (j % 64 === 63) {
|
|
134
|
+
await pause();
|
|
135
|
+
}
|
|
136
|
+
if (chosen.includes(j)) {
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
let shared = 0;
|
|
140
|
+
change.fill(0);
|
|
141
|
+
for (let i = 0; i < m; i++) {
|
|
142
|
+
const d = distance[j * m + i],
|
|
143
|
+
gain = d < first[i] ? weights[i] * (d - first[i]) : 0;
|
|
144
|
+
shared += gain;
|
|
145
|
+
change[nearest[i]] += weights[i] * (Math.min(d, second[i]) - first[i]) - gain;
|
|
146
|
+
}
|
|
147
|
+
for (let s = 0; s < n; s++) {
|
|
148
|
+
const error = current + shared + change[s];
|
|
149
|
+
if (error < lowest) {
|
|
150
|
+
lowest = error;
|
|
151
|
+
best = [s, j];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (!best) {
|
|
156
|
+
return chosen;
|
|
157
|
+
}
|
|
158
|
+
chosen[best[0]] = best[1];
|
|
159
|
+
}
|
|
160
|
+
}
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|
package/dist/index.cjs
CHANGED
|
@@ -75,6 +75,7 @@ var _clustering = _interopRequireDefault((() => {
|
|
|
75
75
|
return require("./clustering.cjs");
|
|
76
76
|
}
|
|
77
77
|
})());
|
|
78
|
+
var _choose = require("./choose.cjs");
|
|
78
79
|
var _shared = require("./shared.cjs");
|
|
79
80
|
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
80
81
|
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
|
|
@@ -168,6 +169,10 @@ const wasmSettings = (wasm, onError) => {
|
|
|
168
169
|
throw (0, _shared.fail)('invalid-argument', "Invalid wasm: must be a URL or path string, a URL, an ArrayBuffer or typed array of the .wasm bytes, or a WebAssembly.Module.", 'options.wasm');
|
|
169
170
|
};
|
|
170
171
|
|
|
172
|
+
// How each engine words a URL that can't be resolved: Chromium and Node "Invalid URL", Firefox "… is not a valid URL",
|
|
173
|
+
// WebKit "… cannot be parsed as a URL".
|
|
174
|
+
const badUrl = /Invalid URL|not a valid URL|cannot be parsed as a URL/i;
|
|
175
|
+
|
|
171
176
|
// A module that cannot be loaded is the commonest first-run failure: a 404, a Content-Security-Policy that blocks it, a
|
|
172
177
|
// bundler that moved the file, an engine without WebAssembly SIMD. The engine's own error (a CompileError, a failed fetch)
|
|
173
178
|
// says little about which, so the message leads with what happened and then gives the likely fix for where it ran.
|
|
@@ -260,16 +265,21 @@ const wasmLoadFailed = (cause, given, gzipped = false) => {
|
|
|
260
265
|
advice = `Check what init({ wasm }) was given${where}: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).`;
|
|
261
266
|
} else if (isNodeLike) {
|
|
262
267
|
// The glue's `new URL('clustering.wasm', import.meta.url)`, with import.meta emptied by a CommonJS bundle.
|
|
263
|
-
if (
|
|
268
|
+
if (badUrl.test(reason)) {
|
|
264
269
|
reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
|
|
265
270
|
}
|
|
266
271
|
advice = `If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes. ${deployAdvice}`;
|
|
267
272
|
} else if (!isBrowserLike()) {
|
|
268
273
|
// A server runtime that isn't Node (an edge runtime, Deno Deploy): it has no page, so a CSP or a 404 page are unlikely.
|
|
269
|
-
if (
|
|
274
|
+
if (badUrl.test(reason)) {
|
|
270
275
|
reason = "the package can't tell where clustering.wasm is in this runtime";
|
|
271
276
|
}
|
|
272
277
|
advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the docs show how for Cloudflare Workers and Next.js: https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md); elsewhere its bytes or URL.";
|
|
278
|
+
} else if (badUrl.test(reason) && /^(data|blob|about):$/.test(String(globalThis.location && globalThis.location.protocol))) {
|
|
279
|
+
// The code runs from a data: or blob: URL (a bundled worker script in a single-file host) or an about:srcdoc page, so
|
|
280
|
+
// there is nothing to find clustering.wasm next to. (In a worker, location is the worker script's own URL.)
|
|
281
|
+
reason = `the package can't tell where clustering.wasm is: it runs from a ${globalThis.location.protocol} URL, with nothing next to it (${reason})`;
|
|
282
|
+
advice = "Pass the module itself: createWorker({ script, wasm: bytes }) for a worker you start, init({ wasm: bytes }) for the main entry or the worker entry's shared worker (the bytes, a URL, or a compiled module; see \"Plugins and single-file hosts\" in https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).";
|
|
273
283
|
} else {
|
|
274
284
|
advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
|
|
275
285
|
}
|
|
@@ -1320,12 +1330,58 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1320
1330
|
return result;
|
|
1321
1331
|
};
|
|
1322
1332
|
|
|
1323
|
-
//
|
|
1333
|
+
// clustering.chooseFrom: validates everything before its first await (the palette is copied, so the caller may change it
|
|
1334
|
+
// at once), then runs the search in choose.js on this thread with the cuts above.
|
|
1324
1335
|
exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
|
|
1336
|
+
const chooseFrom = async (name, clustering, palette, k, options) => {
|
|
1337
|
+
const header = (0, _shared.readHeader)(clustering);
|
|
1338
|
+
(0, _shared.checkPalette)(palette);
|
|
1339
|
+
if (palette.length === 0) {
|
|
1340
|
+
throw (0, _shared.fail)('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
|
|
1341
|
+
}
|
|
1342
|
+
const entries = Uint8Array.from(palette);
|
|
1343
|
+
const count = entries.length / 3;
|
|
1344
|
+
k = check(k);
|
|
1345
|
+
if (k > count) {
|
|
1346
|
+
throw (0, _shared.fail)('invalid-argument', `Invalid k: ${k} is more than the ${count} entries in the palette; use ${count} or fewer.`, 'k');
|
|
1347
|
+
}
|
|
1348
|
+
const o = parseOptions(options, ['colorSpace', 'signal']);
|
|
1349
|
+
needsWeights(header);
|
|
1350
|
+
clustering = held(clustering);
|
|
1351
|
+
checkAborted(o.signal);
|
|
1352
|
+
const pause = async () => {
|
|
1353
|
+
checkAborted(o.signal);
|
|
1354
|
+
if (o.signal) {
|
|
1355
|
+
await yieldNow();
|
|
1356
|
+
checkAborted(o.signal);
|
|
1357
|
+
}
|
|
1358
|
+
};
|
|
1359
|
+
const indices = await (0, _choose.choose)({
|
|
1360
|
+
cut: size => cutPalette(name, clustering, size, []),
|
|
1361
|
+
swatches: () => cutSwatches(name, clustering, 1024, []),
|
|
1362
|
+
snap: async colours => (await quantizeToIndicesWithPalette({
|
|
1363
|
+
data: colours,
|
|
1364
|
+
format: 'rgb'
|
|
1365
|
+
}, entries, {
|
|
1366
|
+
colorSpace: 'rgb'
|
|
1367
|
+
})).indices,
|
|
1368
|
+
pause
|
|
1369
|
+
}, entries, k, (0, _shared.colorSpaceName)(o.colorSpace));
|
|
1370
|
+
indices.sort((x, y) => x - y);
|
|
1371
|
+
const chosen = new Uint8Array(3 * indices.length);
|
|
1372
|
+
indices.forEach((j, s) => chosen.set(entries.subarray(3 * j, 3 * j + 3), 3 * s));
|
|
1373
|
+
return {
|
|
1374
|
+
indices,
|
|
1375
|
+
palette: (0, _shared.markPalette)(chosen, 'rgb')
|
|
1376
|
+
};
|
|
1377
|
+
};
|
|
1378
|
+
|
|
1379
|
+
// The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
|
|
1325
1380
|
(0, _shared.setEngine)({
|
|
1326
1381
|
cut: cutPalette,
|
|
1327
1382
|
cutSwatches,
|
|
1328
1383
|
info: readInfo,
|
|
1329
1384
|
quantizeFromClustering,
|
|
1330
|
-
quantizeToIndicesFromClustering
|
|
1385
|
+
quantizeToIndicesFromClustering,
|
|
1386
|
+
chooseFrom
|
|
1331
1387
|
});
|
package/dist/index.d.cts
CHANGED
|
@@ -147,16 +147,33 @@ export class Clustering extends Uint8Array {
|
|
|
147
147
|
constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
|
|
148
148
|
/** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
|
|
149
149
|
readonly [clusteringBrand]: true;
|
|
150
|
-
/** The k-colour palette
|
|
150
|
+
/** The k-colour palette of this clustering. Takes no options. Runs on the calling thread, with the main entry. */
|
|
151
151
|
getPalette(this: Clustering, k: number): Promise<Palette>;
|
|
152
|
-
/** Palette, weights and shares
|
|
152
|
+
/** Palette, weights and shares of the k-colour cut. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
|
|
153
153
|
getSwatches(this: Clustering, k: number): Promise<Swatches>;
|
|
154
|
-
/** The error curve and totals
|
|
154
|
+
/** The error curve and totals of this clustering. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
|
|
155
155
|
getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
|
|
156
|
-
/** Maps `image` to
|
|
156
|
+
/** Maps `image` to this clustering's k-colour palette, returning the image's type. Runs on the calling thread, with the main entry. */
|
|
157
157
|
quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
|
|
158
|
-
/**
|
|
158
|
+
/** Maps `image` to this clustering's k-colour palette as palette indices. Runs on the calling thread, with the main entry. */
|
|
159
159
|
quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
160
|
+
/** Chooses the k entries of `palette` that best represent the clustered image: their positions and colours. Runs on the calling thread, with the main entry. */
|
|
161
|
+
chooseFrom(this: Clustering, palette: PaletteLike, k: number, options?: ChooseOptions): Promise<PaletteChoice>;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Options of `clustering.chooseFrom`. */
|
|
165
|
+
export interface ChooseOptions {
|
|
166
|
+
/** The space the search measures distance in: 'rgb' (default) or 'oklab'. It doesn't follow the clustering's space. */
|
|
167
|
+
colorSpace?: ColorSpace | undefined;
|
|
168
|
+
signal?: AbortSignal | undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** What `clustering.chooseFrom` returns. */
|
|
172
|
+
export interface PaletteChoice {
|
|
173
|
+
/** Exactly k positions in the palette given, ascending: no ranking (count the mapped pixels for a legend). */
|
|
174
|
+
indices: number[];
|
|
175
|
+
/** The chosen colours, in the order of `indices`: map with it, and index s of the result is entry indices[s]. */
|
|
176
|
+
palette: Palette;
|
|
160
177
|
}
|
|
161
178
|
|
|
162
179
|
/** What is not a clustering: a `Clustering` is not accepted where a palette is. */
|
|
@@ -375,7 +392,7 @@ export function getClustering(image: ImageLike, options?: ClusteringOptions): Pr
|
|
|
375
392
|
|
|
376
393
|
/**
|
|
377
394
|
* A palette of at most `k` colours for `image` (fewer if it has fewer distinct colours), as flat RGB bytes in split
|
|
378
|
-
* order (see `
|
|
395
|
+
* order (see `clustering.getPalette(k)`). It clusters the image each time: to try several sizes, call `buildClustering`
|
|
379
396
|
* once and cut it.
|
|
380
397
|
*
|
|
381
398
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
@@ -392,6 +409,8 @@ export function getPalette(image: ImageLike, k: number, options?: ClusteringOpti
|
|
|
392
409
|
*
|
|
393
410
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
394
411
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
412
|
+
*
|
|
413
|
+
* @deprecated Use `clustering.getPalette(k)`; off the main thread, `(await worker.load(clustering)).getPalette(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
395
414
|
*/
|
|
396
415
|
export function getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
|
|
397
416
|
|
|
@@ -400,7 +419,7 @@ export function getPaletteFromClustering(clustering: Clustering, k: number): Pro
|
|
|
400
419
|
* from one cut of one clustering, so they line up by construction: entry `i` of each describes the same colour.
|
|
401
420
|
*/
|
|
402
421
|
export interface Swatches {
|
|
403
|
-
/** The colours in split order, exactly what `
|
|
422
|
+
/** The colours in split order, exactly what `clustering.getPalette(k)` gives for the same `k`. */
|
|
404
423
|
palette: Palette;
|
|
405
424
|
/**
|
|
406
425
|
* Pixels per colour, counted as in clustering: by default fully transparent pixels count 0 and partly transparent ones
|
|
@@ -414,7 +433,7 @@ export interface Swatches {
|
|
|
414
433
|
|
|
415
434
|
/**
|
|
416
435
|
* The palette for `image` at `k` colours with each colour's weight and share: one call for swatches with percentages.
|
|
417
|
-
* It clusters the image each time; if you already have a clustering, use `
|
|
436
|
+
* It clusters the image each time; if you already have a clustering, use `clustering.getSwatches(k)`.
|
|
418
437
|
*
|
|
419
438
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
420
439
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
@@ -429,6 +448,8 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
|
|
|
429
448
|
*
|
|
430
449
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
431
450
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
451
|
+
*
|
|
452
|
+
* @deprecated Use `clustering.getSwatches(k)`; off the main thread, `(await worker.load(clustering)).getSwatches(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
432
453
|
*/
|
|
433
454
|
export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
|
|
434
455
|
|
|
@@ -470,8 +491,10 @@ export interface ClusteringInfo {
|
|
|
470
491
|
|
|
471
492
|
/**
|
|
472
493
|
* Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
|
|
473
|
-
* clustering recorded no weights, so it is rejected with `unsupported-version` (as `
|
|
494
|
+
* clustering recorded no weights, so it is rejected with `unsupported-version` (as `clustering.getSwatches(k)` rejects it);
|
|
474
495
|
* the palette and mapping functions still read it.
|
|
496
|
+
*
|
|
497
|
+
* @deprecated Use `clustering.getClusteringInfo()`; off the main thread, `(await worker.load(clustering)).getClusteringInfo()` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
475
498
|
*/
|
|
476
499
|
export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
|
|
477
500
|
|
|
@@ -492,6 +515,8 @@ export function quantize<I extends ImageLike>(image: I, k: number, options?: Qua
|
|
|
492
515
|
*
|
|
493
516
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
494
517
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
518
|
+
*
|
|
519
|
+
* @deprecated Use `clustering.quantize(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantize(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
495
520
|
*/
|
|
496
521
|
export function quantizeFromClustering<I extends ImageLike>(image: I, clustering: Clustering, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
|
|
497
522
|
|
|
@@ -516,12 +541,14 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
|
|
|
516
541
|
export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
|
|
517
542
|
|
|
518
543
|
/**
|
|
519
|
-
* Like `quantizeFromClustering`, but returns palette indices. The palette is `
|
|
544
|
+
* Like `quantizeFromClustering`, but returns palette indices. The palette is `clustering.getPalette(k)`'s.
|
|
520
545
|
*
|
|
521
546
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
|
522
547
|
* if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
|
|
523
548
|
* A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
|
|
524
549
|
* `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
|
|
550
|
+
*
|
|
551
|
+
* @deprecated Use `clustering.quantizeToIndices(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantizeToIndices(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
525
552
|
*/
|
|
526
553
|
export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
527
554
|
|