agglomerative-clustering 3.0.0-beta.7 → 3.1.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 +40 -841
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +61 -23
- package/dist/index.d.cts +53 -8
- package/dist/index.d.ts +53 -8
- package/dist/index.mjs +31 -24
- package/dist/shared.cjs +97 -5
- package/dist/shared.mjs +94 -3
- package/dist/worker-thread.mjs +20 -1
- package/dist/worker.cjs +40 -1
- package/dist/worker.d.cts +5 -2
- package/dist/worker.d.ts +5 -2
- package/dist/worker.mjs +10 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,22 +15,20 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
|
|
|
15
15
|
- **It knows each colour's share of the image,** so you can show swatches with percentages, or pick the smallest palette that meets an error target.
|
|
16
16
|
- **Transparency-aware.** A logo's transparent background never ends up in its palette. GIF and palette PNG output are built in.
|
|
17
17
|
- **Off the main thread.** `agglomerative-clustering/worker` runs the same API in a Web Worker or Node worker thread.
|
|
18
|
-
- **Accurate and fast.** The lowest average error of the six JavaScript quantizers we benchmarked, at about the speed of libimagequant ([
|
|
18
|
+
- **Accurate and fast.** The lowest average error of the six JavaScript quantizers we benchmarked, at about the speed of libimagequant ([benchmarks](#benchmarks)).
|
|
19
19
|
- **Small and portable.** 91 KB of WebAssembly, Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
|
|
20
20
|
|
|
21
|
-
[Install](#install) · [Quick start](#quick-start) · [The idea](#the-idea-in-one-minute) · [Guides](#guides) · [Reference](#reference) · [API](#api) · [Troubleshooting](#troubleshooting)
|
|
22
|
-
|
|
23
21
|
## Install
|
|
24
22
|
|
|
25
23
|
```sh
|
|
26
|
-
npm install agglomerative-clustering
|
|
24
|
+
npm install agglomerative-clustering
|
|
27
25
|
```
|
|
28
26
|
|
|
29
|
-
|
|
27
|
+
Upgrading from 2.x? See [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md): one function was renamed, and palettes and images are the same as 2.0's, with one documented exception.
|
|
30
28
|
|
|
31
|
-
It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (see [
|
|
29
|
+
It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (Chrome and Edge 91, Firefox 89, Safari 16.4). Deno, Bun, Cloudflare Workers, serverless functions, Electron and browser extensions work too: see [Environments](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).
|
|
32
30
|
|
|
33
|
-
##
|
|
31
|
+
## Usage
|
|
34
32
|
|
|
35
33
|
**In Node, with [sharp](https://sharp.pixelplumbing.com/):**
|
|
36
34
|
|
|
@@ -69,9 +67,22 @@ shares.forEach((share, i) => {
|
|
|
69
67
|
});
|
|
70
68
|
```
|
|
71
69
|
|
|
72
|
-
|
|
70
|
+
**A colour-count slider:** cluster once, then cut and map as often as you like.
|
|
71
|
+
|
|
72
|
+
```js
|
|
73
|
+
import { getClustering, getPaletteFromClustering, quantizeWithPalette } from 'agglomerative-clustering';
|
|
74
|
+
|
|
75
|
+
const clustering = await getClustering(imageData); // the expensive step, done once
|
|
76
|
+
|
|
77
|
+
slider.oninput = async () => {
|
|
78
|
+
const palette = await getPaletteFromClustering(clustering, Number(slider.value)); // ~0.4 ms for any k
|
|
79
|
+
ctx.putImageData(await quantizeWithPalette(imageData, palette), 0, 0); // ~5-12 ms at 768×512
|
|
80
|
+
};
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba', width?, height? }`. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use the same functions from `agglomerative-clustering/worker` (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)).
|
|
73
84
|
|
|
74
|
-
##
|
|
85
|
+
## How it works
|
|
75
86
|
|
|
76
87
|
```
|
|
77
88
|
image ──▶ getClustering ──▶ a clustering ──▶ cut to k colours ──▶ a palette ──▶ map the pixels ──▶ reduced image
|
|
@@ -79,7 +90,7 @@ Those three are all you need to get started. The rest of this page is organised
|
|
|
79
90
|
store any k bytes any palette
|
|
80
91
|
```
|
|
81
92
|
|
|
82
|
-
The one-shot functions (`getPalette`, `quantize`, …) do
|
|
93
|
+
The one-shot functions (`getPalette`, `quantize`, …) do every step for you. To try many palette sizes, call `getClustering` once and cut it as often as you like.
|
|
83
94
|
|
|
84
95
|
| You want | from the image | from a clustering you hold | with a palette you supply |
|
|
85
96
|
|---|---|---|---|
|
|
@@ -88,29 +99,23 @@ The one-shot functions (`getPalette`, `quantize`, …) do the first steps for yo
|
|
|
88
99
|
| the image reduced to those colours | `quantize` | `quantizeFromClustering` | `quantizeWithPalette` |
|
|
89
100
|
| palette indices (GIF, PNG-8) | `quantizeToIndices` | `quantizeToIndicesFromClustering` | `quantizeToIndicesWithPalette` |
|
|
90
101
|
|
|
91
|
-
|
|
102
|
+
**`…FromClustering`** takes the colours from a clustering you already hold, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `getClustering` builds a clustering, `getClusteringInfo` reads one (including its error curve, for choosing a palette size), and `init` loads the WebAssembly module (optional). Most code only needs the first column.
|
|
92
103
|
|
|
93
|
-
|
|
104
|
+
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).
|
|
94
105
|
|
|
95
|
-
|
|
96
|
-
- **palette**: flat RGB bytes, `[r, g, b, r, g, b, …]`. A `Palette` knows the colour space it was made in.
|
|
97
|
-
- **k**: the most palette entries in what you get back, in every function. A flat palette has no transparent entry, so its entries are all colours; in indexed output with `transparent`, the transparent entry is one of the `k`, so `256` is the most a GIF holds. Fewer come back when the image has fewer distinct colours. The one exception: indexed output always keeps a colour for the visible pixels, so `k = 1` with a transparent entry gives 2.
|
|
98
|
-
- **split order**: palettes come out so that the palette for `k + 1` is the one for `k` with one colour split in two. Entries keep their place as `k` grows, but the palette is not sorted by share.
|
|
99
|
-
- **precision**: an option that groups similar colours before clustering, about 3× faster at practically the same quality.
|
|
106
|
+
## Use cases
|
|
100
107
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
**A good fit:**
|
|
108
|
+
**Good fits:**
|
|
104
109
|
- **Interactive tools where people choose the number of colours:** palette editors, posterisers, pixel art, embroidery, paint-by-number and knitting pattern generators, and LED, e-ink or limited-palette displays.
|
|
105
110
|
- **Several palette sizes for the same image,** or storing one clustering and cutting it later.
|
|
106
111
|
- **The most accurate palette for a given size,** for example as a starting point for vectorisation or flat-colour art.
|
|
107
112
|
|
|
108
|
-
**
|
|
113
|
+
**Better served by something else:**
|
|
109
114
|
- **Shrinking PNG files in a build pipeline.** Use [sharp](https://sharp.pixelplumbing.com/) or pngquant, which run libimagequant natively and are tuned for compression.
|
|
110
|
-
- **A handful of "dominant" swatches for a UI theme.** [color-thief](https://lokeshdhakar.com/projects/color-thief/) or [node-vibrant](https://github.com/Vibrant-Colors/node-vibrant) are lighter and pick vivid or salient colours rather than the lowest-error ones.
|
|
115
|
+
- **A handful of vivid "dominant" swatches for a UI theme.** [color-thief](https://lokeshdhakar.com/projects/color-thief/) or [node-vibrant](https://github.com/Vibrant-Colors/node-vibrant) are lighter and pick vivid or salient colours rather than the lowest-error ones.
|
|
111
116
|
- **Palettes that need their own alpha values,** as palette PNGs with translucent entries do. Pixels are weighted by opacity, but palette colours are opaque RGB, and each pixel keeps its own alpha.
|
|
112
117
|
|
|
113
|
-
|
|
118
|
+
## Benchmarks
|
|
114
119
|
|
|
115
120
|
The 24 Kodak photos (768×512) at 64 colours. "Error vs ours" is mean squared error relative to this library, so 1.08× means 8% more error. Every palette is mapped to pixels the same way, so palettes are compared like for like. Times are medians per image, in WASM on Node 24 on a laptop (Intel Core i7-1185G7).
|
|
116
121
|
|
|
@@ -124,827 +129,21 @@ The 24 Kodak photos (768×512) at 64 colours. "Error vs ours" is mean squared er
|
|
|
124
129
|
| MMCQ (color-thief's algorithm) | 32.53 dB | 2.08× | 19 ms | 98 ms |
|
|
125
130
|
| image-q RgbQuant | 31.95 dB | 2.38× | 242 ms | 1006 ms |
|
|
126
131
|
|
|
127
|
-
All rows are from one run. Full results at every palette size, on synthetic images too, with ΔE2000 and the method, are in [bench/COMPARISON.md](bench/COMPARISON.md); reproduce them with `node bench/run.js`. These numbers are a snapshot, so expect them to move with the hardware and the versions.
|
|
128
|
-
|
|
129
|
-
## Guides
|
|
130
|
-
|
|
131
|
-
### Cluster once, cut anywhere
|
|
132
|
-
|
|
133
|
-
```js
|
|
134
|
-
import { getClustering, getPaletteFromClustering, quantizeWithPalette } from 'agglomerative-clustering';
|
|
135
|
-
|
|
136
|
-
const clustering = await getClustering(imageData); // the expensive step, done once
|
|
137
|
-
|
|
138
|
-
slider.oninput = async () => {
|
|
139
|
-
const k = Number(slider.value);
|
|
140
|
-
const palette = await getPaletteFromClustering(clustering, k); // ~0.4 ms for any k
|
|
141
|
-
const result = await quantizeWithPalette(imageData, palette); // ~5-12 ms for a 768×512 image
|
|
142
|
-
ctx.putImageData(result, 0, 0);
|
|
143
|
-
};
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
A clustering of a 768×512 photo is 0.3 to 1.5 MB, typically 0.7 MB (0.2 MB with `precision: 6`). Store it next to the image if you like: its format is versioned, and `new Clustering(bytes)` gives stored bytes their type back (see [Palette and Clustering](#palette-and-clustering)).
|
|
147
|
-
|
|
148
|
-
### Swatches, and choosing a palette size
|
|
149
|
-
|
|
150
|
-
```js
|
|
151
|
-
import { getSwatches, getClustering, getSwatchesFromClustering, getClusteringInfo } from 'agglomerative-clustering';
|
|
152
|
-
|
|
153
|
-
// Colours with their share of the image, in one call
|
|
154
|
-
const { palette, weights, shares } = await getSwatches(image, 8);
|
|
155
|
-
// palette: flat RGB bytes, weights: pixels per colour, shares: each colour's share of the image (they sum to 1)
|
|
156
|
-
|
|
157
|
-
// Or cluster once and cut it as often as you like (well under a millisecond each)
|
|
158
|
-
const clustering = await getClustering(image);
|
|
159
|
-
const eight = await getSwatchesFromClustering(clustering, 8);
|
|
160
|
-
|
|
161
|
-
// The smallest palette that keeps 99% of the image's colour variance (works the same in 'rgb' and 'oklab')
|
|
162
|
-
const { explained } = await getClusteringInfo(clustering);
|
|
163
|
-
const k = explained.findIndex((share) => share >= 0.99) + 1;
|
|
164
|
-
```
|
|
165
|
-
|
|
166
|
-
How many to ask for: 5 to 8 for a set of swatches to show. To *pick* from them (an accent colour, a theme), ask for more, 12 to 16: a small vivid area, such as a red sign in a street scene, only gets a colour of its own once the bigger areas have been split. Each colour is the average of its cluster, so it is a little less saturated than the image's most vivid pixels, and a white background comes back as a near-white such as `[254, 254, 254]` rather than exactly `#ffffff`. On a smooth single-hue photo no colour has a large share (the shares fall as `k` grows), so judge the heaviest swatch against the others, not by a fixed share. See [Picking colours from swatches](#picking-colours-from-swatches).
|
|
167
|
-
|
|
168
|
-
### GIFs and palette PNGs
|
|
169
|
-
|
|
170
|
-
`quantizeToIndices` returns a palette and one index per pixel, which is what these formats store. With `transparent`, pixels below an alpha cutoff share one transparent entry, which counts in `k`; a colour is always kept besides it, so `k = 1` can give 2 entries.
|
|
171
|
-
|
|
172
|
-
**A GIF** with [gifenc](https://github.com/mattdesl/gifenc), keeping a transparent background:
|
|
173
|
-
|
|
174
|
-
```js
|
|
175
|
-
import * as gifenc from 'gifenc';
|
|
176
|
-
// Bundlers read gifenc's ES module, which has the named export; plain Node reads its CommonJS build, which has it on the default.
|
|
177
|
-
const GIFEncoder = gifenc.GIFEncoder ?? gifenc.default.GIFEncoder;
|
|
178
|
-
import { quantizeToIndices } from 'agglomerative-clustering';
|
|
179
|
-
|
|
180
|
-
// k counts the transparent entry, so 256 is the most a GIF holds. `image` is { data, format: 'rgba', width, height }.
|
|
181
|
-
const { palette, indices, indexBits, transparentIndex } = await quantizeToIndices(image, 256, { transparent: true });
|
|
182
|
-
if (indexBits !== 8) {throw new Error('unreachable: 256 entries or fewer have 8-bit indices');} // tells TypeScript `indices` is a Uint8Array
|
|
183
|
-
const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
|
|
184
|
-
|
|
185
|
-
const gif = GIFEncoder();
|
|
186
|
-
gif.writeFrame(indices, image.width, image.height, { palette: colors, transparent: transparentIndex !== null, transparentIndex: transparentIndex ?? 0 });
|
|
187
|
-
gif.finish();
|
|
188
|
-
const bytes = gif.bytes();
|
|
189
|
-
```
|
|
190
|
-
|
|
191
|
-
**A palette PNG** with [fast-png](https://github.com/image-js/fast-png): the same call, then move the transparent entry to the front and give it alpha 0. A PNG lists alpha for the first palette entries, in order, and fast-png writes only the alphas below 255, so the transparent entry has to come first or the alpha lands on the wrong colour:
|
|
192
|
-
|
|
193
|
-
```js
|
|
194
|
-
import { encode } from 'fast-png';
|
|
195
|
-
|
|
196
|
-
// Swap the transparent entry with entry 0 (when there is one), in the palette and in the indices.
|
|
197
|
-
const t = transparentIndex ?? 0;
|
|
198
|
-
const swap = (i) => (i === t ? 0 : i === 0 ? t : i);
|
|
199
|
-
const png = encode({
|
|
200
|
-
width: image.width, height: image.height, depth: 8, channels: 1,
|
|
201
|
-
data: indices.map(swap),
|
|
202
|
-
palette: colors.map((_, i) => [...colors[swap(i)], i === 0 && transparentIndex !== null ? 0 : 255]),
|
|
203
|
-
});
|
|
204
|
-
```
|
|
205
|
-
|
|
206
|
-
With at most 256 entries, `indices` is a `Uint8Array`, as these formats need (`indexBits` says so).
|
|
207
|
-
|
|
208
|
-
### Animated GIFs and sets of images
|
|
209
|
-
|
|
210
|
-
One palette for a whole animation (or a set of images that should share colours) keeps colours from flickering between frames. Cluster a sample of the frames as one image, by putting their pixels end to end, then map every frame with that clustering:
|
|
211
|
-
|
|
212
|
-
```js
|
|
213
|
-
import { getClustering, quantizeToIndicesFromClustering } from 'agglomerative-clustering';
|
|
214
|
-
|
|
215
|
-
// `frames` are { data, format: 'rgba', width, height }. Every 5th one, end to end, is one image to cluster.
|
|
216
|
-
const sample = frames.filter((_, i) => i % 5 === 0);
|
|
217
|
-
const pixels = new Uint8Array(sample.reduce((n, frame) => n + frame.data.length, 0));
|
|
218
|
-
let offset = 0;
|
|
219
|
-
for (const frame of sample) {pixels.set(frame.data, offset); offset += frame.data.length;}
|
|
220
|
-
const clustering = await getClustering({ data: pixels, format: 'rgba' }, { precision: 6, transparent: true });
|
|
221
|
-
|
|
222
|
-
for (const frame of frames) {
|
|
223
|
-
// The same 256 entries for every frame (transparent one included), dithered lightly to limit shimmer between frames.
|
|
224
|
-
const { palette, indices, transparentIndex } = await quantizeToIndicesFromClustering(frame, clustering, 256, { dither: 0.5 });
|
|
225
|
-
// … gif.writeFrame(indices, width, height, { palette: …, transparent: transparentIndex !== null, transparentIndex: transparentIndex ?? 0 })
|
|
226
|
-
}
|
|
227
|
-
```
|
|
228
|
-
|
|
229
|
-
Cutting the clustering keeps `k` counting the transparent entry, so the palette fits a GIF. (A palette passed to `quantizeToIndicesWithPalette` has the transparent entry added to it, so 256 colours become 257 entries: cut 255.) A frame with no transparent pixels has no transparent entry, so its palette can be one entry shorter than another frame's; a GIF with one global palette should reserve a slot for it. With the worker entry, a few `createWorker()`s map frames in parallel; on small frames (320×240) the cost of sending them across outweighs the gain.
|
|
230
|
-
|
|
231
|
-
### Live video and camera frames
|
|
232
|
-
|
|
233
|
-
For a palette that follows a video or a camera (ambient light, a live theme), take each frame small and **skip frames while the worker is busy**:
|
|
234
|
-
|
|
235
|
-
```js
|
|
236
|
-
import { createWorker } from 'agglomerative-clustering/worker';
|
|
237
|
-
|
|
238
|
-
const worker = createWorker({ transfer: true }); // each frame's pixels are fresh, so move them rather than copy
|
|
239
|
-
const canvas = new OffscreenCanvas(160, 90); // a small copy is plenty for a palette
|
|
240
|
-
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
|
241
|
-
let busy = false;
|
|
242
|
-
|
|
243
|
-
const onFrame = () => {
|
|
244
|
-
if (!busy) {
|
|
245
|
-
busy = true;
|
|
246
|
-
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
|
247
|
-
worker.getPalette(ctx.getImageData(0, 0, canvas.width, canvas.height), 6, { precision: 6 })
|
|
248
|
-
.then(show, console.error)
|
|
249
|
-
.finally(() => {busy = false;});
|
|
250
|
-
}
|
|
251
|
-
video.requestVideoFrameCallback(onFrame);
|
|
252
|
-
};
|
|
253
|
-
video.requestVideoFrameCallback(onFrame);
|
|
254
|
-
```
|
|
255
|
-
|
|
256
|
-
- **Don't abort the running call when a new frame arrives**, as the slider example does. A slider stops; frames keep coming, so when each palette takes longer than a frame, every call is aborted before it finishes and no palette ever arrives (none in 6 seconds at 640×360 and 30 frames a second, in testing). Each abort also costs the worker a little. Skip frames instead, or keep only the newest one waiting.
|
|
257
|
-
- **Size.** In a worker with `precision: 6` a palette took about 20 ms at 160×90, 50 ms at 320×180, 100 ms at 640×360 and 185 ms at 1280×720 (on a busy machine, so a ceiling); exact precision is 3 to 7 times slower. 160×90 keeps up with 30 frames a second.
|
|
258
|
-
- **Flicker.** Each frame is clustered on its own, so even a still scene with a little noise gives palettes whose colours shift, swap places or split differently from frame to frame. Follow the previous palette and smooth it; in testing this cut the flicker about fourfold, for a lag of two or three frames:
|
|
259
|
-
|
|
260
|
-
```js
|
|
261
|
-
// Match each colour of the previous (smoothed) palette to its nearest new colour, then move a quarter of the way there.
|
|
262
|
-
const follow = (previous, next, weight = 0.25) => {
|
|
263
|
-
if (!previous || previous.length !== next.length) {return Array.from(next);}
|
|
264
|
-
const free = new Set(Array.from({ length: next.length / 3 }, (_, i) => i));
|
|
265
|
-
const smoothed = [];
|
|
266
|
-
for (let i = 0; i < previous.length; i += 3) {
|
|
267
|
-
let best = 0, bestDistance = Infinity;
|
|
268
|
-
for (const j of free) {
|
|
269
|
-
const d = (previous[i] - next[3 * j]) ** 2 + (previous[i + 1] - next[3 * j + 1]) ** 2 + (previous[i + 2] - next[3 * j + 2]) ** 2;
|
|
270
|
-
if (d < bestDistance) {bestDistance = d; best = j;}
|
|
271
|
-
}
|
|
272
|
-
free.delete(best);
|
|
273
|
-
for (let c = 0; c < 3; c++) {smoothed.push(previous[i + c] + weight * (next[3 * best + c] - previous[i + c]));}
|
|
274
|
-
}
|
|
275
|
-
return smoothed; // fractional values: round them for display
|
|
276
|
-
};
|
|
277
|
-
```
|
|
278
|
-
- **One palette for a whole clip** (no flicker at all) is the animated-GIF recipe above: cluster a sample of frames once.
|
|
279
|
-
- **In Node**, pipe ffmpeg's raw output (`-f rawvideo -pix_fmt rgba`) and hand each frame to a few `createWorker()`s; memory stayed flat over thousands of frames in testing.
|
|
280
|
-
|
|
281
|
-
### Off the main thread
|
|
282
|
-
|
|
283
|
-
Clustering a photo takes about 70 ms, too long to run on a page's main thread while someone drags a slider. The worker entry has the same functions, run in a Web Worker (or a worker thread in Node):
|
|
284
|
-
|
|
285
|
-
```js
|
|
286
|
-
import { quantize } from 'agglomerative-clustering/worker'; // same API, one shared worker
|
|
287
|
-
const reduced = await quantize(imageData, 16);
|
|
288
|
-
```
|
|
289
|
-
|
|
290
|
-
For live re-cutting, `createWorker().cluster(image)` keeps the image and its clustering in the worker, so each new palette size sends only `k` across:
|
|
291
|
-
|
|
292
|
-
```js
|
|
293
|
-
import { createWorker } from 'agglomerative-clustering/worker';
|
|
294
|
-
|
|
295
|
-
const worker = createWorker();
|
|
296
|
-
const handle = await worker.cluster(imageData, { precision: 6 });
|
|
297
|
-
|
|
298
|
-
let controller = null;
|
|
299
|
-
slider.oninput = async () => {
|
|
300
|
-
controller?.abort(); // a size the slider has already moved past isn't worth finishing
|
|
301
|
-
const mine = (controller = new AbortController());
|
|
302
|
-
try {
|
|
303
|
-
ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true, signal: mine.signal }), 0, 0);
|
|
304
|
-
} catch (error) {
|
|
305
|
-
if (!mine.signal.aborted) {throw error;} // an abort is expected; anything else is a real failure
|
|
306
|
-
}
|
|
307
|
-
};
|
|
308
|
-
```
|
|
309
|
-
|
|
310
|
-
Calls to one worker run in order, and re-mapping a large image takes a while (0.2 to 0.3 s at 12 megapixels, about 1 s dithered), so without the `signal` a fast drag queues up every size it passed through and the picture keeps changing after the slider stops. Aborting the previous call drops it from the queue. Re-cutting alone (`handle.getPalette(k)`, `handle.getSwatches(k)`) takes well under a millisecond and needs none of this. This suits a slider, which stops; for a stream that never does, such as video frames, see [Live video and camera frames](#live-video-and-camera-frames).
|
|
311
|
-
|
|
312
|
-
It starts the worker with `new Worker(new URL('./worker-thread.mjs', import.meta.url))`, the form bundlers look for: CI tests Vite and webpack 5, Parcel 2 works with its `packageExports` option on (see [below](#angular-esbuild-rollup-and-other-bundlers)), and for Next.js see [Next.js](#nextjs). Bundlers that don't emit that script (Angular's `application` builder, plain esbuild or Rollup) need it given to them: see [Angular, esbuild, Rollup and other bundlers](#angular-esbuild-rollup-and-other-bundlers). Loaded from a CDN (another origin than the page), it starts the worker through a small `blob:` script, as browsers don't start workers from other origins' scripts. In TypeScript a handle keeps the image type it was made from: a variable that holds one is `ClusteringHandle<ImageData> | null`, not a bare `ClusteringHandle`, whose `quantize` returns the general image type. In Node an idle worker never keeps the process alive. See the [worker reference](#worker-entry).
|
|
313
|
-
|
|
314
|
-
### Fixed palettes: e-ink, thread, bricks
|
|
315
|
-
|
|
316
|
-
Hardware, craft and print often have a palette you didn't choose. `quantizeToIndicesWithPalette(image, palette, options?)` maps to it and gives indices in *your* palette's order (what firmware, thread charts and parts lists need):
|
|
317
|
-
|
|
318
|
-
```js
|
|
319
|
-
const eink = [0,0,0, 255,255,255, 0,255,0, 0,0,255, 255,0,0, 255,255,0, 255,128,0]; // black white green blue red yellow orange
|
|
320
|
-
const { indices } = await quantizeToIndicesWithPalette({ data, format: 'rgba', width }, eink, { dither: true });
|
|
321
|
-
// indices[i] is the entry of `eink` for pixel i: pack it to 4 bits per pixel for the panel
|
|
322
|
-
```
|
|
323
|
-
|
|
324
|
-
- **Undithered, every pixel gets its nearest entry** (ties go to the smaller RGB value, and a repeated entry gets its first index). Dithering diffuses the error to the neighbours, and keeps working when the palette can't reach the image's colours: saturated cyan with the seven e-ink inks comes out as an even mix of white, green and blue, not solid blue.
|
|
325
|
-
- **Colour space is a choice here too, and the answer differs from clustering.** `'oklab'` keeps skin tones from going olive when mapping *without* dithering; with small palettes of widely spaced inks (e-ink, grey levels) `'rgb'` dithers better, and OKLab brightens black and white. Try both on your panel.
|
|
326
|
-
- **Choosing N colours from a fixed set** (the 12 threads that best represent a photo out of 400) has no function of its own, but a few lines do it: cut the clustering, snap each cut colour to its nearest thread, and cut finer until N distinct threads appear. In testing it beat "the N most used threads" by 3 to 8 dB PSNR for N up to 12; the gain shrinks as N grows (under 1 dB at 24).
|
|
327
|
-
|
|
328
|
-
```js
|
|
329
|
-
import { getClustering, getPaletteFromClustering, quantizeToIndicesWithPalette } from 'agglomerative-clustering';
|
|
330
|
-
|
|
331
|
-
// The indices (into `threads`, flat RGB) of the n threads that best represent `image`.
|
|
332
|
-
async function chooseThreads(image, threads, n) {
|
|
333
|
-
const clustering = await getClustering(image);
|
|
334
|
-
let chosen = [];
|
|
335
|
-
for (let k = n; k <= 4 * n && chosen.length < n; k++) {
|
|
336
|
-
const cut = await getPaletteFromClustering(clustering, k);
|
|
337
|
-
// The cut palette as an image of one pixel per colour, mapped to the threads.
|
|
338
|
-
const { indices } = await quantizeToIndicesWithPalette({ data: cut, format: 'rgb' }, threads);
|
|
339
|
-
// Split order puts the coarsest colours first, so when a cut gives more than n threads, the first n are kept.
|
|
340
|
-
chosen = [...new Set(indices)].slice(0, n);
|
|
341
|
-
}
|
|
342
|
-
return chosen; // can be fewer than n for an image with few colours
|
|
343
|
-
}
|
|
344
|
-
```
|
|
345
|
-
- **Transparent pixels** map to black unless you pass `transparent`, which appends an entry for them (so a 1- or 2-bit panel has no room for it): composite the image onto your background first.
|
|
346
|
-
- **Index width:** up to 256 entries give 8-bit indices; more give 16-bit ones (`indexBits` says which), so a 257-colour palette doesn't fit an 8-bit format.
|
|
347
|
-
- **Speed:** a palette of more than 1024 colours is mapped about three times slower than one of 1024 or fewer, and dithered about four to six times slower (at 12 megapixels, about 2 s with 1024 colours against 8 to 13 s with 1025 to 2000).
|
|
348
|
-
|
|
349
|
-
### Swatches for many images (a build step)
|
|
350
|
-
|
|
351
|
-
For placeholders, theming or colour search over a site's images, one call each is fast enough, and most of the time goes to decoding:
|
|
352
|
-
|
|
353
|
-
- **Downscale first.** 512 px on the long side changes the palette by about 2% (256 px by 6%, 64 px by half) and is 3 to 8 times faster; with `precision: 6` a photo takes about 20 ms.
|
|
354
|
-
- **Use a few workers, not one per image.** The main entry runs one call at a time, so throughput comes from several `createWorker()`s (the pool in [Performance and limits](#performance-and-limits)). About four is the sweet spot; more mostly adds memory.
|
|
355
|
-
- **Cache palettes, not clusterings:** 1,500 palettes are about half a megabyte of JSON, and 1,500 clusterings are 0.2 to 1 GB. Key the cache by the image's content hash, plus the library's major version and your options; palettes are the same for every 3.x release (see [stability](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/stability.md)).
|
|
356
|
-
- "Dominant colour" is up to you: the heaviest swatch of `getSwatches(image, 5)` (sort by `shares`) is a good one. These colours are averages of regions, so they are muted: for vivid accents, a library built for them (node-vibrant, colorthief) suits better.
|
|
357
|
-
- A sharp `Buffer` from `.raw()` can be passed as it is, with `{ data, format: 'rgba', width }`.
|
|
358
|
-
|
|
359
|
-
### Using the output
|
|
360
|
-
|
|
361
|
-
Palettes are flat RGB bytes, the compact form; each format an encoder or UI wants is a line or two away. Given a `palette` (and `weights` and `shares` from `getSwatches`):
|
|
362
|
-
|
|
363
|
-
```js
|
|
364
|
-
// [[r, g, b], …]: what gifenc, fast-png, color-thief and libimagequant use
|
|
365
|
-
const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
|
|
366
|
-
|
|
367
|
-
// A CSS colour, a '#rrggbb' string and a 0xRRGGBB number
|
|
368
|
-
const css = (i) => `rgb(${palette[3 * i]} ${palette[3 * i + 1]} ${palette[3 * i + 2]})`;
|
|
369
|
-
const hexString = (i) => '#' + Array.from(palette.subarray(3 * i, 3 * i + 3), (v) => v.toString(16).padStart(2, '0')).join('');
|
|
370
|
-
const hex = (i) => (palette[3 * i] << 16) | (palette[3 * i + 1] << 8) | palette[3 * i + 2];
|
|
371
|
-
|
|
372
|
-
// Swatches with their share of the image (the palette is in split order, not sorted by share: sort `swatches` by `share` to put the biggest first)
|
|
373
|
-
const swatches = Array.from(shares, (share, i) => ({ color: css(i), share }));
|
|
374
|
-
```
|
|
375
|
-
|
|
376
|
-
**Heaviest first.** Palettes come in split order, so the biggest colour isn't necessarily first. To rank them, sort; sorted palettes of different sizes no longer nest.
|
|
377
|
-
|
|
378
|
-
```js
|
|
379
|
-
// A palette and its weights, heaviest first
|
|
380
|
-
const order = Array.from(weights.keys()).sort((a, b) => weights[b] - weights[a]); // old index of the 1st, 2nd, … entry
|
|
381
|
-
const rankedColors = order.map((i) => colors[i]);
|
|
382
|
-
const rankedShares = order.map((i) => shares[i]);
|
|
383
|
-
|
|
384
|
-
// An indexed image, heaviest first: count how many pixels use each entry (that is what "heaviest" means for the image),
|
|
385
|
-
// sort, and renumber the indices
|
|
386
|
-
const used = new Uint32Array(palette.length / 3);
|
|
387
|
-
for (const index of indices) {used[index]++;}
|
|
388
|
-
const byUse = Array.from(used.keys()).sort((a, b) => used[b] - used[a]);
|
|
389
|
-
const rank = new Uint32Array(used.length);
|
|
390
|
-
byUse.forEach((old, position) => {rank[old] = position;});
|
|
391
|
-
const rankedPalette = byUse.map((old) => colors[old]);
|
|
392
|
-
const rankedIndices = indices.map((index) => rank[index]); // same typed-array type as `indices`
|
|
393
|
-
const rankedTransparentIndex = transparentIndex === null ? null : rank[transparentIndex];
|
|
394
|
-
```
|
|
395
|
-
|
|
396
|
-
#### Picking colours from swatches
|
|
397
|
-
|
|
398
|
-
The library answers which colours an image has and how much of each; choosing among them (a vivid accent, text that contrasts with a background) is colour arithmetic that a colour library already does well. With [culori](https://culorijs.org/):
|
|
399
|
-
|
|
400
|
-
```js
|
|
401
|
-
import { getSwatches } from 'agglomerative-clustering';
|
|
402
|
-
import { converter, wcagContrast, formatHex } from 'culori';
|
|
403
|
-
|
|
404
|
-
const oklch = converter('oklch');
|
|
405
|
-
const { palette, shares } = await getSwatches(image, 12);
|
|
406
|
-
const swatches = Array.from(shares, (share, i) => {
|
|
407
|
-
const color = { mode: 'rgb', r: palette[3 * i] / 255, g: palette[3 * i + 1] / 255, b: palette[3 * i + 2] / 255 };
|
|
408
|
-
return { hex: formatHex(color), share, ...oklch(color) }; // l (0-1), c (chroma), h (hue)
|
|
409
|
-
}).sort((a, b) => b.share - a.share); // heaviest first
|
|
410
|
-
|
|
411
|
-
const background = swatches[0];
|
|
412
|
-
// The most colourful swatch that covers at least 2% of the image, as an accent
|
|
413
|
-
const accent = swatches.filter((s) => s.share >= 0.02 && s !== background).sort((a, b) => b.c - a.c)[0];
|
|
414
|
-
// Text: black or white, whichever contrasts more with the background
|
|
415
|
-
const text = wcagContrast(background.hex, '#000') > wcagContrast(background.hex, '#fff') ? '#000' : '#fff';
|
|
416
|
-
```
|
|
417
|
-
|
|
418
|
-
The colours come back as sRGB bytes whatever `colorSpace` they were clustered in; that option only changes how pixels are grouped. For picks by lightness, chroma or hue, convert them as above (OKLCH is the perceptual form of OKLab). Choose the colour space you cluster in as in [Choosing a colour space](#choosing-a-colour-space): the picks can differ between the two, since each gives different averages.
|
|
419
|
-
|
|
420
|
-
### Coming from color-thief, node-vibrant, image-q or get-image-colors
|
|
421
|
-
|
|
422
|
-
This library takes **decoded pixels**, not files, URLs or image elements: decode first (sharp or pngjs in Node, a canvas or `createImageBitmap` in a browser). Pixels without alpha go in as `{ data, format: 'rgb' }`; passed bare they are read as RGBA, so sharp's `.raw()` without `.ensureAlpha()` gives a palette that is quietly wrong.
|
|
423
|
-
|
|
424
|
-
| You used | Use | Notes |
|
|
425
|
-
|---|---|---|
|
|
426
|
-
| color-thief `getColor(image)` | `getSwatches(image, 5, { precision: 6 })`, then the entry with the largest `shares` | The heaviest cluster's average colour. |
|
|
427
|
-
| color-thief `getPalette(image, n)` | `getPalette(image, n, { precision: 6 })` | Flat bytes; `[[r, g, b], …]` is one line ("Using the output"). |
|
|
428
|
-
| get-image-colors | `getSwatches(image, n)`, and hex strings from the palette | Sort by `shares` for most-used first. |
|
|
429
|
-
| node-vibrant's named swatches (Vibrant, Muted, …) | `getSwatches(image, 16)`, then choose by saturation and lightness yourself | There are no named roles: these colours are averages, more muted than node-vibrant's picks. |
|
|
430
|
-
| image-q `buildPalette` and `applyPalette` | `quantize(image, k, { dither })`, or `getPalette` then `quantizeWithPalette` | Same idea, one call; `quantizeToIndices` for indexed output. |
|
|
431
|
-
|
|
432
|
-
- **Expect different colours.** The palettes are the ones with the least error, not the most vivid or the most frequent, so they won't match what you had (a mean ΔE2000 of 12 to 14 between matched colours, against color-thief, get-image-colors and node-vibrant, in testing).
|
|
433
|
-
- **Speed.** color-thief and node-vibrant sample pixels, so they are quick on photos; the exact default here is several times slower at photo sizes. With `precision: 6` it was level with color-thief at 12 megapixels; downscaling helps both. Against image-q it was 4 to 6 times faster.
|
|
434
|
-
- **Quality.** Undithered, the error was lower than image-q's Wu (at 16 colours, MSE 71 against 84). `dither: true` diffuses the whole error, so per-pixel error is higher than with image-q's Floyd–Steinberg while the image looks closer from a distance; a strength such as `dither: 0.5` sits between.
|
|
435
|
-
- **Missing pieces** are a few lines each: hex strings and ranking by share in [Using the output](#using-the-output), and a dominant colour above.
|
|
436
|
-
|
|
437
|
-
## Reference
|
|
438
|
-
|
|
439
|
-
### Input and output
|
|
440
|
-
Every function that takes an image accepts:
|
|
441
|
-
|
|
442
|
-
```ts
|
|
443
|
-
Uint8Array // raw RGBA bytes
|
|
444
|
-
ImageData // from a canvas: always RGBA, width included
|
|
445
|
-
{ data: Uint8Array | Uint8ClampedArray, // explicit format, for RGB data or clamped arrays
|
|
446
|
-
format: 'rgb' | 'rgba',
|
|
447
|
-
width?: number, height?: number } // optional: used for dithering, copied to results
|
|
448
|
-
```
|
|
449
|
-
|
|
450
|
-
`width` and `height` must be whole numbers, and when both are given they must account for exactly the pixels in `data`.
|
|
451
|
-
|
|
452
|
-
> **A bare `Uint8Array` is read as RGBA**, like `ImageData`. RGB bytes passed bare are misread, with no error when their length happens to be a multiple of 4. Pass them as `{ data, format: 'rgb', width }`, or add an alpha channel (sharp's `.ensureAlpha()`).
|
|
453
|
-
|
|
454
|
-
> **Pixels are 8-bit sRGB with straight alpha**, as `getImageData()` gives them. Convert anything else first: premultiplied pixels (from some native and WebGL APIs) back to straight alpha, 16-bit or floating-point pixels (16-bit PNGs, HDR) to 8 bits (sharp: `.toColourspace('srgb').raw({ depth: 'uchar' })`; pngjs: `inputHasAlpha` and its 8-bit output), and gray or gray-and-alpha pixels to RGBA (sharp's `.toColourspace('srgb').ensureAlpha()`). A gray buffer passed as it is gets misread, with no error when its length is a multiple of 4. Apply a photo's EXIF orientation (sharp's `.rotate()`) and colour profile when decoding; the library doesn't read either. An `ImageData` in another pixel format (Chromium's `pixelFormat: 'rgba-float16'`) is rejected with `invalid-argument`: ask for `getImageData(x, y, w, h, { pixelFormat: 'rgba-unorm8' })`.
|
|
455
|
-
|
|
456
|
-
> **Image files are not pixels.** A bare `Uint8Array` that starts like a PNG, JPEG, GIF, WebP, BMP, TIFF, AVIF or HEIC file (from `fs.readFile` or `fetch`) is rejected with `invalid-argument` naming the format. Decode it first: a canvas or `createImageBitmap` in a browser, sharp or pngjs in Node. Only bare arrays are checked, so if raw pixels really do begin like a file header, pass `{ data, format: 'rgba' }`. Decoding is [planned](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/ROADMAP.md).
|
|
457
|
-
|
|
458
|
-
The functions that return an image give back the type they were given: a `Uint8Array`, `ImageData`, or an object with the same `format` (and `width` and `height`). In TypeScript the result type follows the input (`ImageResult<I>`). Palettes come back as a `Palette`, clusterings as a `Clustering`, and the other results are `Swatches`, `IndexedImage` and `ClusteringInfo` objects.
|
|
459
|
-
|
|
460
|
-
### Options
|
|
461
|
-
|
|
462
|
-
Every function that takes an image also takes an optional last argument of options. They are all off by default, and the defaults give the exact results shown above.
|
|
463
|
-
|
|
464
|
-
| Option | Applies to | Values | What it does |
|
|
465
|
-
|---|---|---|---|
|
|
466
|
-
| `precision` | clustering | `1`–`8`, default `8` | Groups colours that share their top `precision` bits per channel before clustering, at their mean colour. **`6` is about 3× faster on photos at practically the same quality** (−0.02 dB), and caps the work on images with huge numbers of colours. `5` is about 8× faster for a small loss. |
|
|
467
|
-
| `colorSpace` | clustering and mapping | `'rgb'` (default), `'oklab'` | `'rgb'` minimises squared error in sRGB (the best PSNR); `'oklab'` clusters and matches in [OKLab](https://bottosson.github.io/posts/oklab/). Neither wins everywhere: see "Choosing a colour space". |
|
|
468
|
-
| `alpha` | clustering | `'weight'` (default), `'ignore'` | `'weight'` counts each RGBA pixel in proportion to its opacity, so transparent pixels don't count (exact pixel counting for opaque images). `'ignore'` counts every pixel fully, as 1.x did. Each pixel keeps its own alpha in the output. |
|
|
469
|
-
| `dither` | mapping | `false` (default), `true`, or `0`–`1` | Serpentine Floyd–Steinberg error diffusion, with a strength from 0 to 1. Hides banding in gradients at low colour counts, at a cost in per-pixel metrics such as PSNR. Fully transparent pixels are left undithered. |
|
|
470
|
-
| `width` | mapping | integer | The image width, for dithering a `Uint8Array` or a `RawImage` without one. If the image has a width of its own, this must equal it. |
|
|
471
|
-
| `signal` | any call with an image | an `AbortSignal` | Cancels the call; see "Cancelling and progress". |
|
|
472
|
-
| `onProgress` | clustering | `(fraction) => void` | Reports 0 to 1 as the clustering runs; see "Cancelling and progress". |
|
|
473
|
-
| `transparent` | clustering; indexed output | `false` (default), `true`, or an alpha cutoff `1`–`255` | Pixels with alpha below the cutoff (128 for `true`) are left out of clustering and the rest count whole; indexed output gives them a transparent entry, counted in `k`. For GIFs and palette PNGs; see "Transparency". |
|
|
474
|
-
|
|
475
|
-
"Clustering" means any function that builds a clustering (`getClustering`, `getPalette`, `getSwatches`, `quantize` and `quantizeToIndices`), and "mapping" means any that maps pixels to a palette (`quantize`, `quantizeFromClustering`, `quantizeWithPalette` and the indexed versions). A function that does both takes both sets of options.
|
|
476
|
-
|
|
477
|
-
Pass an ordinary object. It is copied once before use (its enumerable properties, inherited ones included, so `Object.create(defaults)` works), and an unknown key is an error, including one that another function takes: an object with both `precision` and `dither` passed to `getClustering` throws on `dither`. TypeScript doesn't catch that when the object is a variable typed `QuantizeOptions` (extra properties of a variable are allowed), so give each call the options it takes, or keep one object per stage.
|
|
478
|
-
|
|
479
|
-
```js
|
|
480
|
-
// Perceptual palettes for a photo, quickly
|
|
481
|
-
const palette = await getPalette(photo, 128, { colorSpace: 'oklab', precision: 6 });
|
|
482
|
-
|
|
483
|
-
// Retro look: 8 colours, dithered
|
|
484
|
-
const retro = await quantize(imageData, 8, { dither: true });
|
|
485
|
-
|
|
486
|
-
// Dithering a raw buffer needs its width
|
|
487
|
-
const out = await quantize(rgbaBytes, 32, { dither: 0.8, width: 640 });
|
|
488
|
-
```
|
|
489
|
-
|
|
490
|
-
#### Choosing a colour space
|
|
491
|
-
|
|
492
|
-
`'rgb'` is the default and the right choice for most photos. Measured on the 24 Kodak photos and the synthetic set, at 3 to 256 colours:
|
|
493
|
-
|
|
494
|
-
| You are making | Colours | Use | What the numbers say |
|
|
495
|
-
|---|---|---|---|
|
|
496
|
-
| Swatches, dominant colours | 3–8 | `'rgb'` | Keeps more of the image's colourfulness (chroma retention 0.88–0.91 against 0.85–0.88 on photos); mean ΔE is tied. |
|
|
497
|
-
| PNG-8 and web compression | 64–256 | `'rgb'` for PSNR, `'oklab'` for ΔE | RGB has about 0.7–1.1 dB more PSNR on every photo; OKLab has about 4% lower ΔE at 256 colours (better on 22 of 24 photos). |
|
|
498
|
-
| Dithered GIF, retro look | 8–64 | `'rgb'` | Looks closer from a distance: blurred ΔE 2.59 against 2.86 at 16 colours. |
|
|
499
|
-
| Flat graphics, logos, pixel art | 8–32 | either | About equal. |
|
|
500
|
-
| Smooth gradients and skies, not dithered | 8–64 | `'oklab'` | Mean ΔE 11.0 against 13.4 at 8 colours on the synthetic gradients (two images, so a hint). |
|
|
501
|
-
| Noisy or very varied images | any | `'oklab'` | Mean ΔE 7.0 against 7.9 at 64 colours (one synthetic image). |
|
|
502
|
-
|
|
503
|
-
`'oklab'` also takes 10–25% longer. Pixel values are treated as sRGB whatever the canvas colour space; a wide-gamut `ImageData` (`display-p3`) comes back in its own colour space, unshifted, but `'oklab'` is then approximate.
|
|
504
|
-
|
|
505
|
-
How the options trade speed and quality, measured on the Kodak photos:
|
|
506
|
-
|
|
507
|
-
| Setting | 16 colours ΔE2000 | 256 colours ΔE2000 | One 64-colour palette |
|
|
508
|
-
|---|---|---|---|
|
|
509
|
-
| default (`rgb`, exact) | **4.31** | 1.67 | 70 ms |
|
|
510
|
-
| `precision: 6` | **4.29** | 1.68 | 24 ms |
|
|
511
|
-
| `colorSpace: 'oklab'` | 4.46 | **1.60** | 78 ms |
|
|
512
|
-
| `colorSpace: 'oklab', precision: 6` | 4.44 | 1.61 | 30 ms |
|
|
513
|
-
| libimagequant, for reference | 4.38 | 1.61 | 79 ms |
|
|
514
|
-
|
|
515
|
-
#### Transparency
|
|
516
|
-
|
|
517
|
-
Three things in this library are about alpha, and they act at different stages:
|
|
518
|
-
|
|
519
|
-
| | What it is | Stage | Effect |
|
|
520
|
-
|---|---|---|---|
|
|
521
|
-
| `'rgba'` input | The format of the pixels (bare `Uint8Array` and `ImageData` are RGBA; `{ data, format: 'rgb' }` has none) | input | RGB images have no alpha, so nothing below applies to them. |
|
|
522
|
-
| `alpha` | An option: `'weight'` (default) or `'ignore'` | clustering | `'weight'` counts each RGBA pixel in proportion to its opacity, so transparent pixels don't count; `'ignore'` counts every pixel fully, as 1.x did. Each pixel keeps its own alpha in the output. |
|
|
523
|
-
| `transparent` | An option: `false` (default), `true`, or an alpha cutoff `1`–`255` | clustering; indexed output | Pixels with alpha below the cutoff (128 for `true`) are left out of clustering and the rest count whole; indexed output gives them one transparent entry, counted in `k`. |
|
|
524
|
-
|
|
525
|
-
Give one or the other: `transparent` replaces `alpha`, so naming both is an error. Use `alpha` (the default) for swatches and for images that keep each pixel's alpha, and `transparent` when the destination has one transparent colour, as GIF and palette PNG do, in the clustering step too, so the palette you cut is the one you map with. Translucent palette colours are not supported.
|
|
526
|
-
|
|
527
|
-
The cutoff decides which side a half-transparent pixel falls on. With the default (128), a soft drop shadow under 50% opacity disappears, and the darker part of it becomes solid; raise the cutoff (`transparent: 200`) to drop more of it, or lower it to keep more.
|
|
132
|
+
All rows are from one run. Full results at every palette size, on synthetic images too, with ΔE2000 and the method, are in [bench/COMPARISON.md](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/bench/COMPARISON.md); reproduce them with `node bench/run.js`. These numbers are a snapshot, so expect them to move with the hardware and the versions.
|
|
528
133
|
|
|
529
|
-
|
|
530
|
-
The palettes and clusterings this library returns are ordinary `Uint8Array`s with a hidden tag: what they are and, for a palette, the colour space it was made in. Anything that takes bytes takes them, and their `constructor` is `Uint8Array`, so `expect(palette).toEqual(new Uint8Array([...]))` passes in your tests. The tags buy four things:
|
|
134
|
+
## Documentation
|
|
531
135
|
|
|
532
|
-
- **
|
|
533
|
-
- **
|
|
534
|
-
-
|
|
535
|
-
- **
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
const clustering = new Clustering(stored); // typed again, and checked
|
|
542
|
-
const palette = await getPaletteFromClustering(clustering, 8);
|
|
543
|
-
palette instanceof Palette; // true
|
|
544
|
-
palette.colorSpace; // 'rgb' or 'oklab', as it was clustered
|
|
545
|
-
palette.slice(0, 3) instanceof Palette; // false: slice, subarray and clones are plain bytes
|
|
546
|
-
```
|
|
547
|
-
|
|
548
|
-
`slice`, `subarray`, `structuredClone`, `postMessage` and storage give plain, untagged `Uint8Array`s (the worker entry carries the tags across for you). In Node, `console.log` shows the tag: `Palette(oklab) Uint8Array(6) [ … ]`.
|
|
549
|
-
|
|
550
|
-
**Storing a palette.** Storage keeps a palette's bytes but not its colour space, and plain bytes are matched in RGB. So an OKLab palette that you store and read back maps differently from the one you stored, without an error. Store the colour space with it and give it back:
|
|
551
|
-
|
|
552
|
-
```js
|
|
553
|
-
await db.put('palette', { bytes: Array.from(palette), colorSpace: palette.colorSpace });
|
|
554
|
-
const { bytes, colorSpace } = await db.get('palette');
|
|
555
|
-
const restored = new Palette(bytes, colorSpace); // maps exactly as the palette you stored
|
|
556
|
-
```
|
|
557
|
-
|
|
558
|
-
A clustering needs none of this: its colour space is in its bytes.
|
|
559
|
-
|
|
560
|
-
### Cancelling and progress
|
|
561
|
-
Every function that takes an image accepts `signal`; the ones that cluster (`getClustering`, `getPalette`, `getSwatches`, `quantize`, `quantizeToIndices`) also accept `onProgress`:
|
|
562
|
-
|
|
563
|
-
```js
|
|
564
|
-
const controller = new AbortController();
|
|
565
|
-
const clustering = await getClustering(image, {
|
|
566
|
-
signal: controller.signal, // controller.abort() cancels it
|
|
567
|
-
onProgress: (fraction) => bar.value = fraction, // 0 to 1
|
|
568
|
-
});
|
|
569
|
-
```
|
|
570
|
-
|
|
571
|
-
- **Slices.** With either option, clustering runs in slices of about 10 ms (a large photo has a few unsliced steps of up to 150 ms in between; an image with millions of distinct colours, longer: see [Performance and limits](#performance-and-limits)), so an abort takes effect within a slice and the page stays responsive. The result is the same; slicing costs about 5% more time.
|
|
572
|
-
- **Aborting** rejects with the signal's `reason` (an `AbortError` by default), like `fetch`. It is not one of this library's errors, and has none of their codes (a `DOMException`'s `code` is a number). To tell an abort from a failure, check your signal (`signal.aborted`), not the error: a reason you gave (`controller.abort(new Error('superseded'))`) keeps its own name. An already aborted signal does no work.
|
|
573
|
-
- **Mapping can't be interrupted** (it takes milliseconds: 6 ms at 768×512, 27 ms dithered). The functions that only map check the signal before they start, and don't take `onProgress`.
|
|
574
|
-
- **Progress** is approximate, never goes backwards, and ends at exactly 1.
|
|
575
|
-
- **In a worker** the work in the worker stops too, and a call still queued is removed without running. The worker keeps running for later calls.
|
|
576
|
-
|
|
577
|
-
### Errors
|
|
578
|
-
|
|
579
|
-
Every error the library throws is an `Error` with a `code`, so you don't have to match on message text (except an abort, which rejects with the signal's own `reason`).
|
|
580
|
-
|
|
581
|
-
When an error is about one argument, `error.argument` names it: `'image'`, `'k'`, `'clustering'`, `'palette'`, `'options'`, `'colorSpace'` (from `new Palette`), or `'options.<name>'` (for example `'options.colorSpace'`), so a form can point at the right field. Arguments are checked in the order you pass them, so the error is about the first that is wrong.
|
|
582
|
-
|
|
583
|
-
| `code` | When |
|
|
584
|
-
| --- | --- |
|
|
585
|
-
| `invalid-argument` | A bad image, `k`, option or palette. |
|
|
586
|
-
| `invalid-clustering` | Bytes that aren't a clustering this version can read, or a stored clustering that came back damaged (its checksum or its records don't fit). |
|
|
587
|
-
| `unsupported-version` | A clustering from a newer format, or using a colour space it doesn't know (upgrade the package), or an older one without what you asked for (cluster again, e.g. for `getSwatchesFromClustering`). |
|
|
588
|
-
| `out-of-memory` | The WebAssembly module couldn't allocate: an image with very many colours, or pixel data over its 2 GB (the message gives the size). |
|
|
589
|
-
| `wasm-load-failed` | The WebAssembly module couldn't be loaded or compiled: a missing or blocked `.wasm` file, a server bundle that moved it, a browser without SIMD, or a `.wasm` from a different version of the library than the script (a stale cache or CDN copy; the message names both versions). The message leads with the engine's reason and says what to check, and `cause` is the engine's own error. |
|
|
590
|
-
| `worker-terminated`, `worker-failed`, `invalid-handle` | Worker entry only: the worker was stopped, failed, or a handle was released. `worker-terminated` is for calls running or waiting when `terminate()` was called, and every later call on that `createWorker()` worker, so retrying on it can't help (the shared worker starts again on the next call). After `worker-failed` (it couldn't start, crashed or exited), the next call starts a new worker. |
|
|
591
|
-
|
|
592
|
-
```js
|
|
593
|
-
import { getPaletteFromClustering, isCodedError } from 'agglomerative-clustering';
|
|
594
|
-
|
|
595
|
-
try {
|
|
596
|
-
await getPaletteFromClustering(stored, 16);
|
|
597
|
-
} catch (error) {
|
|
598
|
-
// isCodedError narrows the type in TypeScript, and is false for errors that aren't the library's (Node's ENOENT, an abort)
|
|
599
|
-
if (isCodedError(error) && (error.code === 'unsupported-version' || error.code === 'invalid-clustering')) { /* cluster the image again */ }
|
|
600
|
-
else { throw error; }
|
|
601
|
-
}
|
|
602
|
-
```
|
|
603
|
-
|
|
604
|
-
`errorCodes` lists every code, for code that forwards them (a wrapper package re-exporting them, a bridge between processes). `isCodedError` also accepts a plain object with a known `code` and a `message`, which is what an error becomes after Electron's IPC or a `postMessage`.
|
|
605
|
-
|
|
606
|
-
Messages are for people and may change. The worker entry fails the same way as the main entry, with your call's stack (the worker's is on `cause`). A failure that isn't the library's own, such as a WebAssembly trap, has no `code`.
|
|
607
|
-
|
|
608
|
-
### Worker entry
|
|
609
|
-
`agglomerative-clustering/worker` exports every function above, run in one shared worker started on first use, plus `terminate()`, which stops it (the next call starts a new one), and `createWorker(options?)`, which starts a worker of your own. A worker has every function as a method, plus:
|
|
610
|
-
|
|
611
|
-
- **`cluster(image, options?)`** keeps the image and its clustering in the worker, behind a handle with `getClustering()`, `getPalette(k)`, `getSwatches(k)`, `getClusteringInfo()`, `quantize(k, options?)`, `quantizeToIndices(k, options?)`, `quantizeWithPalette(palette, options?)` and `quantizeToIndicesWithPalette(palette, options?)`. A palette of plain bytes is matched in the handle's colour space, and `quantizeToIndices` uses the cutoff it was clustered with. Free it with `release()`, or declare it with `await using handle = await worker.cluster(image)`; a dropped handle is freed only when the garbage collector gets to it.
|
|
612
|
-
- **`terminate()`** stops the worker and rejects the calls still waiting. `await using worker = createWorker()` calls it at the end of the block.
|
|
613
|
-
|
|
614
|
-
**Terminate the workers you create.** A worker's thread, and the memory its last images needed, stay until `terminate()`: a running worker is never garbage-collected, so a server or page that creates a worker per request and drops it gathers threads. Keep a few workers and reuse them (see [Performance and limits](#performance-and-limits)), or use the shared worker, which the exported functions use. As a safety net, a worker you dropped is stopped some time after the garbage collector has collected it, once no call is running on it and no handle from it is left, but when that happens is up to the engine (it may be never, in a process with little memory pressure).
|
|
615
|
-
|
|
616
|
-
`createWorker` takes `transfer`, `wasm` (see [Loading the WebAssembly module](#loading-the-webassembly-module)) and `script`: the URL (or in Node, the path) of a copy of the package's `dist/worker-thread.mjs`, for setups whose bundler doesn't emit the package's own. For the shared worker, `init({ script })` does the same, before any other call.
|
|
617
|
-
|
|
618
|
-
Calls run one at a time, in order. Results are transferred back without copying. Images are copied in, unless you create the worker with `createWorker({ transfer: true })`, which is faster but leaves your buffer empty. Only pixels that are a whole buffer of their own are transferred; a view into part of a larger buffer, such as a `subarray` or a small Node `Buffer`, is copied.
|
|
619
|
-
|
|
620
|
-
The entry is an ES module, with a CommonJS build for `require()` in Node and in Jest. In a browser bundle, import it rather than `require()` it: bundlers find the worker script only from the ES module, so the CommonJS build there needs `createWorker({ script })`.
|
|
621
|
-
|
|
622
|
-
### TypeScript
|
|
623
|
-
Both entries ship declarations, checked in CI under strict mode with `nodenext` (ES module and CommonJS importers), `bundler`, and a Node-only project without the DOM lib. The worker entry's declarations use `await using` for handles, so they need **TypeScript 5.2 or newer** (or `skipLibCheck: true`); the main entry works on older versions. Both entries have CommonJS declarations too, so a `.cts` file or a CommonJS project imports either.
|
|
624
|
-
|
|
625
|
-
Results narrow: checking `result.indexBits === 8` makes `indices` a `Uint8Array`. Palette parameters take a `PaletteLike` (a `Palette`, plain bytes or a `number[]`, not a `Clustering`), and errors are `CodedError`s with `code` and `argument`.
|
|
626
|
-
|
|
627
|
-
An image object assigned to a variable before it is passed widens `format: 'rgba'` to `string`, which no longer matches `RawImage`: write `format: 'rgba' as const`, or declare the variable as `RawImage`.
|
|
628
|
-
|
|
629
|
-
## API
|
|
630
|
-
|
|
631
|
-
### `getClustering(image, options?): Promise<Clustering>`
|
|
632
|
-
Builds the colour hierarchy for an image. Pass the result to `getPaletteFromClustering` or `quantizeFromClustering` to get any number of palettes without clustering again.
|
|
633
|
-
|
|
634
|
-
Options: `colorSpace`, `precision`, `alpha`, `transparent`, `signal`, `onProgress`.
|
|
635
|
-
|
|
636
|
-
### `getPaletteFromClustering(clustering, k): Promise<Palette>`
|
|
637
|
-
Cuts a clustering to at most `k` colours, returned as flat RGB bytes. This takes well under a millisecond. Colours come in split order: index 0 is the dominant colour at two colours and keeps its place as the palette grows (it is not always the heaviest entry of a larger palette), and the palette for `k + 1` is the palette for `k` with one entry refined (the larger half of a split keeps its parent's place) and the smaller half appended. Accepts clusterings from 2.x too. `k` is a maximum: an image with fewer distinct colours gives fewer entries.
|
|
638
|
-
|
|
639
|
-
### `getPalette(image, k, options?): Promise<Palette>`
|
|
640
|
-
`getClustering` followed by `getPaletteFromClustering`.
|
|
641
|
-
|
|
642
|
-
Options: `colorSpace`, `precision`, `alpha`, `transparent`, `signal`, `onProgress`.
|
|
643
|
-
|
|
644
|
-
### `getSwatches(image, k, options?): Promise<Swatches>`
|
|
645
|
-
A palette with how much of the image each colour covers, for swatches with percentages. It returns `{ palette, weights, shares }`, three arrays from one cut of one clustering, so entry `i` of each describes the same colour:
|
|
646
|
-
- `palette` is flat RGB bytes in split order (what `getPaletteFromClustering` gives).
|
|
647
|
-
- `weights` are pixels per colour. Fully transparent pixels count 0 and partly transparent ones in proportion to their opacity, as in clustering; with `alpha: 'ignore'` every pixel counts 1.
|
|
648
|
-
- `shares` are the weights divided by their total, so they sum to 1.
|
|
649
|
-
|
|
650
|
-
All three are empty for an image with no visible pixels, and `k` is a maximum, so lay swatches out from the arrays' length, not from `k`. It clusters the image each time: to try several sizes, use `getClustering` once and `getSwatchesFromClustering`.
|
|
651
|
-
|
|
652
|
-
Options: `colorSpace`, `precision`, `alpha`, `transparent`, `signal`, `onProgress`.
|
|
653
|
-
|
|
654
|
-
### `getSwatchesFromClustering(clustering, k): Promise<Swatches>`
|
|
655
|
-
The same from a clustering you already have, well under a millisecond. Needs a clustering from 3.x: 2.x clusterings don't record weights, so they are rejected.
|
|
656
|
-
|
|
657
|
-
### `getClusteringInfo(clustering): Promise<ClusteringInfo>`
|
|
658
|
-
What a clustering holds: `{ formatVersion, colorSpace, precision, transparent, maxColors, totalWeight, mse, explained }`.
|
|
659
|
-
|
|
660
|
-
- `formatVersion`: the format of its bytes (compare it with the exported `formatVersion`).
|
|
661
|
-
- `transparent`: the alpha cutoff it was made with, or `false`. `quantizeToIndicesFromClustering` uses it by default.
|
|
662
|
-
- `maxColors`: the largest palette it can be cut to.
|
|
663
|
-
- `mse[k - 1]`: the mean squared error per channel of the `k`-colour clustering, in 8-bit RGB values (OKLab units for an OKLab clustering). `mse[0]` is the image's variance, and `mse[maxColors - 1]` is 0 at the default `precision: 8` (below 8, it is the error that grouping colours discarded). It is an estimate from merge costs; mapping pixels to the palette usually lowers it by another 10–15%.
|
|
664
|
-
- `explained[k - 1]`: `1 - mse[k - 1] / mse[0]`, the share of the image's variance the `k`-colour palette keeps, from 0 to 1. It has no units, so a target such as `0.99` means the same in both colour spaces.
|
|
665
|
-
|
|
666
|
-
It needs a clustering from 3.x, like `getSwatchesFromClustering`: a 2.x clustering recorded no weights, so it is rejected with `unsupported-version` (the palette and mapping functions still read it).
|
|
667
|
-
|
|
668
|
-
### `quantize(image, k, options?): Promise<the type of image>`
|
|
669
|
-
Reduces the image to at most `k` colours.
|
|
670
|
-
|
|
671
|
-
Options: `colorSpace`, `precision`, `alpha`, `transparent`, `dither`, `width`, `signal`, `onProgress`.
|
|
672
|
-
|
|
673
|
-
### `quantizeFromClustering(image, clustering, k, options?): Promise<the type of image>`
|
|
674
|
-
Quantizes using a clustering you already have.
|
|
675
|
-
|
|
676
|
-
Options: `colorSpace` (defaults to the clustering's), `dither`, `width`, `signal`.
|
|
677
|
-
|
|
678
|
-
### `quantizeWithPalette(image, palette, options?): Promise<the type of image>`
|
|
679
|
-
Maps each pixel to its nearest colour in any palette: a `Palette`, or flat RGB bytes (a `Uint8Array`, `Uint8ClampedArray`, or plain array of integers 0–255; flatten an array of `[r, g, b]` colours first with `colors.flat()`). A `Palette` is matched in its own colour space and plain bytes in RGB, unless you name a `colorSpace`. The result doesn't depend on the palette's order: equally near colours are decided by their RGB value.
|
|
680
|
-
|
|
681
|
-
Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signal`.
|
|
682
|
-
|
|
683
|
-
### `quantizeToIndices(image, k, options?): Promise<IndexedImage>`
|
|
684
|
-
Like `quantize`, but returns each pixel's palette index rather than its colour: what palette PNGs, GIFs, pixel art and pattern generators need.
|
|
685
|
-
|
|
686
|
-
Options: `colorSpace`, `precision`, `alpha`, `transparent`, `dither`, `width`, `signal`, `onProgress`.
|
|
687
|
-
|
|
688
|
-
The result is `{ palette, colors, indices, indexBits, transparentIndex }`, plus `width` and `height` when the input has them:
|
|
689
|
-
- `palette`: the flat RGB bytes an encoder wants, including the transparent entry if there is one.
|
|
690
|
-
- `colors`: the same without the transparent entry, to pass to `quantizeToIndicesWithPalette` for more images with these colours.
|
|
691
|
-
- `indices`: one per pixel, a `Uint8Array` for up to 256 entries, `Uint16Array` up to 65536, else `Uint32Array`; `indexBits` (8, 16 or 32) says which.
|
|
692
|
-
- `transparentIndex`: the transparent entry's index, or `null`.
|
|
693
|
-
|
|
694
|
-
With `transparent`, RGBA pixels below the cutoff get the transparent entry (appended after the colours, and counted in `k`) and every other pixel is shown fully opaque, which is all a GIF can express, so anti-aliased edges snap to one side. The colours are chosen from the visible pixels, the same as `getPalette(image, k - 1, { transparent: true })` when the image has pixels below the cutoff; when it has none there is no transparent entry, and all `k` entries are colours. At least one colour is always kept. See [Transparency](#transparency).
|
|
695
|
-
|
|
696
|
-
```js
|
|
697
|
-
const { palette, colors, indices, transparentIndex } = await quantizeToIndices(imageData, 256, { transparent: true });
|
|
698
|
-
```
|
|
699
|
-
|
|
700
|
-
### `quantizeToIndicesFromClustering(image, clustering, k, options?): Promise<IndexedImage>`
|
|
701
|
-
The same as `quantizeToIndices`, from a clustering you already have. The default cutoff is the one the clustering was made with (`getClusteringInfo(clustering).transparent`), so clustering and mapping agree unless you name another.
|
|
702
|
-
|
|
703
|
-
Options: `colorSpace` (defaults to the clustering's), `dither`, `width`, `signal`, `transparent`.
|
|
704
|
-
|
|
705
|
-
### `quantizeToIndicesWithPalette(image, palette, options?): Promise<IndexedImage>`
|
|
706
|
-
The same as `quantizeToIndices`, with a palette you supply. There is no `k`: the transparent entry is added to the palette you give, so a 256-colour palette gives 257 entries.
|
|
707
|
-
|
|
708
|
-
Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signal`, `transparent`.
|
|
709
|
-
|
|
710
|
-
### `init(options?): Promise<void>`
|
|
711
|
-
Loads the WebAssembly module. Every other function does this on first use, so calling it is optional, for example to warm up before a batch. Concurrent calls share one load, and a failed load can be retried. To say where the module is, see [Loading the WebAssembly module](#loading-the-webassembly-module).
|
|
712
|
-
|
|
713
|
-
### `errorCodes: readonly string[]` and `isCodedError(value): boolean`
|
|
714
|
-
`errorCodes` is a frozen array of every `code` the library's errors have (see [Errors](#errors)). `isCodedError(value)` is true when `value` has a string `message` and one of those codes; in TypeScript it narrows to `CodedError`. Both entries export both.
|
|
715
|
-
|
|
716
|
-
### `version: string` and `formatVersion: number`
|
|
717
|
-
`version` is the library's version (such as `'3.0.0'`), for bug reports and runtime checks. `formatVersion` is the version of the data it stores (the clustering format), which changes only when that format does: a minor release may raise it, and every earlier format from 2 on stays readable. To keep stored clusterings current, cluster the image again when `getClusteringInfo(stored).formatVersion` is below it, or when `getClusteringInfo` rejects the clustering with `unsupported-version` (a 2.x clustering, which has no weights, or one from a newer version than this one). Both entries export both, and a `.wasm` from another version fails to load with `wasm-load-failed`.
|
|
718
|
-
|
|
719
|
-
## Running it
|
|
720
|
-
|
|
721
|
-
### Where it runs
|
|
722
|
-
|
|
723
|
-
Node 20.19+ and 22.12+ (CI tests Node 20, 22 and 24, on Linux and Windows), and browsers with WebAssembly SIMD: Chrome and Edge 91, Firefox 89, Safari 16.4 or newer ([support table](https://caniuse.com/wasm-simd)). CI bundles a test page with Vite and webpack 5 and runs it in Chromium, Firefox and WebKit on Linux and in Safari on macOS. In a browser without SIMD, or where the `.wasm` is blocked or missing, `init` and every other call reject with a `wasm-load-failed` error.
|
|
724
|
-
|
|
725
|
-
CI also loads `dist/` from another origin, as a page using a CDN does, and the worker entry from a sandboxed iframe, in the same browsers, and runs both entries under Jest. Checked by hand, not in CI: Deno 2.9, Bun 1.4, Cloudflare Workers (Wrangler, workerd), Vercel's edge runtime, the AWS Lambda Node image, pnpm and Yarn Plug'n'Play, SvelteKit, Nuxt, Astro, React Router, Angular, Next.js and Parcel 2 (see below).
|
|
726
|
-
|
|
727
|
-
### From a CDN, without a build step
|
|
728
|
-
|
|
729
|
-
```html
|
|
730
|
-
<script type="module">
|
|
731
|
-
import { getSwatches } from 'https://cdn.jsdelivr.net/npm/agglomerative-clustering@next/dist/index.mjs';
|
|
732
|
-
import { createWorker } from 'https://cdn.jsdelivr.net/npm/agglomerative-clustering@next/dist/worker.mjs';
|
|
733
|
-
</script>
|
|
734
|
-
```
|
|
735
|
-
|
|
736
|
-
Import `dist/index.mjs` and `dist/worker.mjs` by their paths (jsDelivr and unpkg don't follow the package's `exports` for subpaths such as `/worker`); `https://esm.sh/agglomerative-clustering@next` works too. The `.wasm` is found next to the script, so `init` needs no `wasm` option, and the worker entry starts its worker through a `blob:` script (browsers don't start workers from another origin's script). A Content-Security-Policy needs the CDN in `script-src` and `connect-src` (the `.wasm` is fetched) and `'wasm-unsafe-eval'` in `script-src`. The worker entry also needs `worker-src blob:` *and* the CDN, since the `blob:` worker imports its script from there: `worker-src blob: https://cdn.jsdelivr.net`. Pin an exact version in production, as `@3.0.0` rather than `@next`.
|
|
737
|
-
|
|
738
|
-
### Deno, Bun and Cloudflare Workers
|
|
739
|
-
|
|
740
|
-
- **Bun** needs nothing: `bun add agglomerative-clustering`, then both entries work as in Node.
|
|
741
|
-
- **Deno**: `import { getPalette } from 'npm:agglomerative-clustering@next'`, run with `--allow-read` (the `.wasm` is read from the package). Importing from a CDN URL works too, without it. The worker entry runs on Deno's `worker_threads`, which is about 3 times slower per call than the main entry; for a few calls, use the main entry. Deno doesn't install npm versions less than a day old by default, so on the day of a release it may quietly install the previous one (`"minimumDependencyAge": 0` in `deno.json` turns that off; the exported `version` says what you got).
|
|
742
|
-
- **Cloudflare Workers**: Wrangler imports a `.wasm` file as a compiled module, so give it to `init` before the first call. There are no threads, so use the main entry.
|
|
743
|
-
|
|
744
|
-
```js
|
|
745
|
-
import { init, getSwatches } from 'agglomerative-clustering';
|
|
746
|
-
import wasm from 'agglomerative-clustering/clustering.wasm';
|
|
747
|
-
|
|
748
|
-
const ready = init({ wasm });
|
|
749
|
-
export default {
|
|
750
|
-
async fetch(request) {
|
|
751
|
-
await ready;
|
|
752
|
-
// … decode the upload to pixels (fast-png works here), then getSwatches(pixels, 8)
|
|
753
|
-
},
|
|
754
|
-
};
|
|
755
|
-
```
|
|
756
|
-
|
|
757
|
-
### Loading the WebAssembly module
|
|
758
|
-
By default the module is found next to the package's script, which Node and bundlers such as Vite handle. Otherwise, say where it is before any other call (the first load that succeeds wins):
|
|
759
|
-
|
|
760
|
-
```js
|
|
761
|
-
await init({ wasm: 'https://cdn.example.com/clustering.wasm' }); // a URL or path string, or a URL
|
|
762
|
-
await init({ wasm: await (await fetch(url)).arrayBuffer() }); // the bytes
|
|
763
|
-
await init({ wasm: wasmModule }); // a compiled WebAssembly.Module
|
|
764
|
-
```
|
|
765
|
-
|
|
766
|
-
The package exports the file as `agglomerative-clustering/clustering.wasm`, so a bundler that imports `.wasm` files as compiled modules (Wrangler, for Cloudflare Workers) can give you `wasmModule`. In Node a path or `file:` URL is read from disk, also when the package is bundled into CommonJS. A strict Content-Security-Policy needs `'wasm-unsafe-eval'` in `script-src`. `createWorker({ wasm })` passes the same option to a worker.
|
|
767
|
-
|
|
768
|
-
### SvelteKit, Nuxt and other frameworks
|
|
769
|
-
|
|
770
|
-
SvelteKit (adapter-node) and Nuxt (Nitro's node-server) need no configuration, in development and production builds: the worker entry for pages, the main entry in server routes. Importing either entry during server rendering is safe, and `createWorker()` starts no thread until its first call. On Nitro's Cloudflare preset, turn on `nitro: { experimental: { wasm: true } }` and pass the module from `import wasm from 'agglomerative-clustering/clustering.wasm?module'` to `init`, as for the Edge runtime below.
|
|
771
|
-
|
|
772
|
-
### Serverless functions: AWS Lambda, Vercel, Netlify
|
|
773
|
-
|
|
774
|
-
Both entries run in Node functions (checked in the AWS Lambda Node 20 image, with a read-only code directory, and with the file tracers Vercel and Netlify use). Unbundled, with `node_modules` in the package or a layer, nothing is needed. Bundled:
|
|
775
|
-
|
|
776
|
-
- **An ES module bundle** finds `clustering.wasm` next to itself: copy `node_modules/agglomerative-clustering/dist/clustering.wasm` beside the bundle. **A CommonJS bundle** has lost the package's own location: pass `init({ wasm: path })`, with a path to the copy you ship.
|
|
777
|
-
- **The worker entry** needs `worker-thread.mjs` and the files it imports (`index.mjs`, `shared.mjs`, `clustering.js`, `clustering.wasm`): leave the package external, or ship a copy of `dist/` and pass `createWorker({ script: path })`. Netlify's esbuild bundler moves them apart, so list the package in `external_node_modules`.
|
|
778
|
-
- **Size and cold starts:** the files a function needs are about 180 KB (235 KB with the worker). Loading the module takes 10 to 70 ms, and a first palette of a 1-megapixel image at `precision: 6` came 0.3 to 0.5 s after a cold start; calling `init()` early doesn't make the first palette faster.
|
|
779
|
-
- **Edge functions** (Vercel's edge runtime, Cloudflare) can't compile WebAssembly while they run: import the module as described for [Next.js](#nextjs) and [Cloudflare Workers](#deno-bun-and-cloudflare-workers).
|
|
780
|
-
|
|
781
|
-
### pnpm, Yarn Plug'n'Play and monorepos
|
|
782
|
-
|
|
783
|
-
pnpm (isolated or hoisted) and Yarn Plug'n'Play need nothing for the main entry. Under Plug'n'Play the package stays in its zip archive, and the worker entry's thread loads its ES modules from there only through Yarn's loader: run with `yarn node` (or `node --require ./.pnp.cjs --loader ./.pnp.loader.mjs`), or `yarn unplug agglomerative-clustering`. Yarn 4 holds back versions published in the last day by default, so to try a release on its first day set `npmMinimalAgeGate: 0` in `.yarnrc.yml`.
|
|
784
|
-
|
|
785
|
-
Two versions in one process (a monorepo whose packages depend on different releases) each load their own module and don't share state; clusterings and palettes pass between them, and `isCodedError` recognises either one's errors.
|
|
786
|
-
|
|
787
|
-
### Next.js
|
|
788
|
-
|
|
789
|
-
Checked with Next.js 16, under Turbopack and webpack, in production builds:
|
|
790
|
-
|
|
791
|
-
- **Client components** need nothing: the main entry and the worker entry both work as they are.
|
|
792
|
-
- **Route handlers and Server Components** (the Node runtime) work as they are too. A server bundle moves the package's files away from each other, so the library then loads `clustering.wasm` and the worker script from the package in `node_modules`, found from the directory the server runs in. If your deployment doesn't ship `node_modules` with the server (a `standalone` output copied elsewhere, say), leave the package out of the bundle instead, which keeps its files together:
|
|
793
|
-
|
|
794
|
-
```js
|
|
795
|
-
// next.config.js
|
|
796
|
-
export default { serverExternalPackages: ['agglomerative-clustering'] };
|
|
797
|
-
```
|
|
798
|
-
- **The Edge runtime** can't fetch or compile a `.wasm` file itself, so import the module and pass it to `init`. The import has to be a relative path to the file (the bundler drops the `?module` query from a package path):
|
|
799
|
-
|
|
800
|
-
```ts
|
|
801
|
-
import { init, getSwatches } from 'agglomerative-clustering';
|
|
802
|
-
// @ts-expect-error -- `?module` gives a compiled WebAssembly.Module
|
|
803
|
-
import wasm from '../../../node_modules/agglomerative-clustering/dist/clustering.wasm?module';
|
|
804
|
-
|
|
805
|
-
export const runtime = 'edge';
|
|
806
|
-
|
|
807
|
-
export async function POST(request: Request) {
|
|
808
|
-
await init({ wasm }); // loads once; later calls return at once
|
|
809
|
-
// … decode the upload to pixels, then getSwatches(pixels, 8)
|
|
810
|
-
}
|
|
811
|
-
```
|
|
812
|
-
|
|
813
|
-
### Angular, esbuild, Rollup and other bundlers
|
|
814
|
-
|
|
815
|
-
The main entry works in all of them, except that an Angular production build needs `init({ wasm })` (below). The worker entry needs its script (`worker-thread.mjs`, which imports the package's other files) next to the rest of `dist/`, and some bundlers emit neither it nor `clustering.wasm`. Then a worker call fails at run time with `worker-failed` or `wasm-load-failed`, often only after deploying, because a dev server serves `node_modules` as it is. Copy the package's whole `dist/` folder out as static assets and say where it is (copy all of it, not a list of files: which files the worker script imports isn't part of the API, and a minor release may change it):
|
|
816
|
-
|
|
817
|
-
```js
|
|
818
|
-
import { createWorker } from 'agglomerative-clustering/worker';
|
|
819
|
-
const worker = createWorker({
|
|
820
|
-
script: '/assets/agglomerative-clustering/worker-thread.mjs', // relative URLs resolve against the page
|
|
821
|
-
wasm: '/assets/agglomerative-clustering/clustering.wasm',
|
|
822
|
-
});
|
|
823
|
-
```
|
|
824
|
-
|
|
825
|
-
- **Angular** (the default `application` builder): add the files to the app's `angular.json` assets, then use the code above. Production builds don't emit `clustering.wasm` for the main entry either, so in the browser call `init({ wasm: '/assets/agglomerative-clustering/clustering.wasm' })` before the first call (the dev server works without it). With SSR, the server bundle finds the package's files from the directory the server starts in: start it from the project directory, or give the server its own `init({ wasm: path })`. zone.js needs nothing.
|
|
826
|
-
|
|
827
|
-
```json
|
|
828
|
-
"assets": [{ "glob": "**/*", "input": "node_modules/agglomerative-clustering/dist", "output": "assets/agglomerative-clustering" }]
|
|
829
|
-
```
|
|
830
|
-
- **esbuild, Rollup and `bun build`** do not recognise `new Worker(new URL(...))`, so copy the whole `dist/` folder into the output and give `script` (and `wasm`). Rollup users can also build `worker-thread.mjs` as a second entry.
|
|
831
|
-
- **Vite, webpack 5 and Rsbuild** find the script themselves. So does **Parcel 2**, once it reads package `exports` (without this it can't resolve `agglomerative-clustering/worker`):
|
|
832
|
-
|
|
833
|
-
```json
|
|
834
|
-
"@parcel/resolver-default": { "packageExports": true }
|
|
835
|
-
```
|
|
836
|
-
in your `package.json`.
|
|
837
|
-
- **The main entry** can also be told where the `.wasm` is with `init({ wasm })`.
|
|
838
|
-
- **A server bundle** (esbuild or Rollup with a Node target, CommonJS or ES module): leave the package external if you ship `node_modules`. Bundled, it finds its files from the working directory, if at all: pass `init({ wasm: path })` and `createWorker({ script: path })`, with paths to copies of `dist/` that you ship.
|
|
839
|
-
|
|
840
|
-
### Electron
|
|
841
|
-
|
|
842
|
-
Everything works in dev and in an app packaged with `asar` (no `asarUnpack`), in the renderer, the main process and a `utilityProcess`, loaded from `file://`, a custom scheme or a dev server. For responsiveness, **decode in the renderer and use `agglomerative-clustering/worker`** there: the main entry in the main process blocks the whole app for the length of a clustering. Two traps:
|
|
843
|
-
|
|
844
|
-
- **Keep the package external in a bundled main process** (electron-vite does by default; with webpack or esbuild mark it external). A bundle that inlines it finds the `.wasm` and worker script only when the app starts from the project directory, which a packaged app doesn't. If you must bundle it, pass `init({ wasm })` for the main entry and `createWorker({ script })` for the worker.
|
|
845
|
-
- **`nodeIntegrationInWorker: true`** is supported: the worker script talks through `self` there.
|
|
846
|
-
|
|
847
|
-
Errors lose their `code` and `argument` crossing Electron's IPC (only the message survives), so send `{ message, code, argument }` yourself; `isCodedError` accepts that object on the other side. `nativeImage` gives BGRA pixels: swap the channels to RGBA first.
|
|
848
|
-
|
|
849
|
-
### Browser extensions
|
|
850
|
-
|
|
851
|
-
The main entry runs in every extension context: a Manifest V3 service worker, an offscreen document, extension pages and content scripts (a page's own Content-Security-Policy does not apply to the main entry in a content script). Tested in Chrome and in Firefox's extension pages and background.
|
|
852
|
-
|
|
853
|
-
- **Manifest CSP.** Compiling WebAssembly in the service worker, an offscreen document or an extension page needs `'wasm-unsafe-eval'` (not `'wasm-eval'`, which Chrome refuses in a manifest): `"content_security_policy": { "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'" }`. The main entry in a content script needs nothing.
|
|
854
|
-
- **A service worker has no `Worker`**, so use the main entry there, which already keeps the page's thread free. The worker entry works in an offscreen document or an extension page. In a content script it starts its worker through a `blob:` URL, and that worker follows the *page's* policy, so it works only on pages whose CSP allows `worker-src blob:` and `'wasm-unsafe-eval'` (or has no CSP); on other pages, use the main entry in the content script, or hand the pixels to an offscreen document.
|
|
855
|
-
- **Files.** With Vite and CRXJS the `.wasm` and worker script are emitted and made web-accessible for you. Without a bundler, copy `dist/*.mjs`, `clustering.js` and `clustering.wasm` into the extension and list them under `web_accessible_resources` if a content script loads them (all of them: a `.wasm` left out fails as "could not be fetched", and only the browser's console names the key).
|
|
856
|
-
- A service worker can fetch cross-origin images with host permissions (a content script gets a tainted canvas), so cluster there. Typed arrays become plain objects through `chrome.runtime.sendMessage`: convert with `Array.from(palette)` and back with `new Uint8Array(...)`.
|
|
857
|
-
|
|
858
|
-
### Plugins and single-file hosts: Figma, VS Code, Obsidian
|
|
859
|
-
|
|
860
|
-
Some hosts load a plugin as one file, or a few fixed ones, so the package's `.wasm` and worker script can't sit next to it. Embed them, and say where everything is: in these hosts the package can't find its own files. (Tested against stand-ins for these hosts: a sandboxed iframe, a Node host process, an Electron renderer. Not inside the apps themselves.)
|
|
861
|
-
|
|
862
|
-
- **The `.wasm` as bytes.** Import it with your bundler's binary loader (esbuild: `--loader:.wasm=binary`, importing `agglomerative-clustering/clustering.wasm`) and pass the bytes: `init({ wasm: bytes })` for the main entry, `createWorker({ wasm: bytes })` for a worker. Set esbuild's `target` (such as `es2022`), or the decoder it emits may use `Uint8Array.fromBase64`, which not every runtime has. The file is about 92 KB, 122 KB as base64, and 54 KB gzipped then base64 (decompress it with `DecompressionStream` before passing it).
|
|
863
|
-
- **The worker script as a `data:` URL.** Bundle `node_modules/agglomerative-clustering/dist/worker-thread.mjs` into one ES module (esbuild `--bundle --format=esm`) and pass it as `createWorker({ script: 'data:text/javascript;base64,…', wasm: bytes })`. In a sandboxed iframe (Figma's UI) a `blob:` worker fails in Chromium; a `data:` one works. The main entry alone is often enough for a plugin's images, and needs only the bytes.
|
|
864
|
-
- **VS Code.** The extension host is Node: bundle your extension with the package external and ship it in `node_modules`, or bundle it and pass a path to a `.wasm` you ship (`init({ wasm: path.join(context.extensionPath, 'dist', 'clustering.wasm') })`); a bundled extension otherwise looks for the package from the working directory, which is not your extension's. A webview's CSP needs `'wasm-unsafe-eval'` in `script-src`, and `worker-src` for the worker entry.
|
|
865
|
-
- **Obsidian** ships `main.js`, `manifest.json` and `styles.css` only, so embed the `.wasm` bytes. Its renderer has Node's globals and a real `Worker`, so both entries work once given the bytes (and, for workers, the `data:` script).
|
|
866
|
-
- **Copying `dist/` files instead**, keep their `.mjs` names: they are ES modules by their extension. Renamed to `.js`, they need a `package.json` with `"type": "module"` next to them.
|
|
867
|
-
- **Get it wrong** and the error says so: a bundled main entry without its `.wasm` fails with `wasm-load-failed` asking for `init({ wasm })`, and a worker without its script with `worker-failed` naming `createWorker({ script })`.
|
|
868
|
-
|
|
869
|
-
### Testing code that uses it
|
|
870
|
-
|
|
871
|
-
- **Vitest** needs no configuration, in node, jsdom, happy-dom and browser mode. **Storybook** (Vite builder) works as it is.
|
|
872
|
-
- **Jest** works in its default CommonJS mode, in the node and jsdom environments, with both entries, without transforms or `--experimental-vm-modules` (both have CommonJS builds). Mocha and `node:test` work too.
|
|
873
|
-
- **jsdom and happy-dom** have no `ImageData` (install `canvas`, `@napi-rs/canvas` or `skia-canvas`, or pass `{ data, format: 'rgba', width }`) and no `Worker`: the worker entry then uses a Node worker thread, which is fine for tests. Results come back in the class of the `ImageData` you passed.
|
|
874
|
-
- **Leaks.** Call `terminate()` (from `agglomerative-clustering/worker`, or on a `createWorker()`) in `afterAll`. It doesn't stop Jest from exiting, but each test file otherwise leaves a worker thread, 15 to 30 MB, in the process until the run ends (or until the garbage collector gets to a dropped `createWorker()`, which may not happen in a test run).
|
|
875
|
-
- **Mocking.** Mock the module with a factory (`vi.mock('agglomerative-clustering', () => ({ getPalette: vi.fn(...) }))`), or in Vitest keep the real `Palette` with `importOriginal`. Build fake palettes with `new Palette(bytes, colorSpace)`, and fake errors as `Object.assign(new Error(message), { code: 'invalid-argument' })` (`isCodedError` accepts them).
|
|
876
|
-
- **Snapshots.** Palettes (and swatches, indices, mapped pixels) are identical across platforms, Node versions and browsers, and within a major version change only for a bug fix that the changelog names: snapshot them, and expect to update a snapshot when such a fix lands. Clustering bytes are not promised to stay the same, so don't hash them. `toEqual` doesn't see a palette's `colorSpace`: compare it explicitly.
|
|
877
|
-
- Fake timers don't affect it. An unawaited call still running at the end holds Jest open until it finishes.
|
|
878
|
-
|
|
879
|
-
### Writing a package that wraps it
|
|
880
|
-
|
|
881
|
-
Make `agglomerative-clustering` a **`peerDependency`** and keep it **external** in your build (tsup `external`, Rollup `external`): the app's bundler then finds the worker script and `.wasm` once, with one copy in the output. Bundling it into your package leaves `./worker-thread.mjs` unresolved. Re-export `errorCodes`, `isCodedError` and the types you need (`CodedError`, `ErrorCode`, `ClusteringOptions`, …), check `version` against your supported range at run time, and let your users pass `wasm` and `script` through. Importing it on the server (SSR) doesn't run anything: only calls load the module.
|
|
882
|
-
|
|
883
|
-
### Performance and limits
|
|
884
|
-
|
|
885
|
-
**Servers.** Cap the pixel count of uploads (check the header's dimensions before decoding, as sharp's `limitInputPixels` does), use `precision: 6` (it bounds the memory an image with very many colours needs), and run the work in workers so a clustering doesn't block the event loop. One worker runs one call at a time, so create a few:
|
|
886
|
-
|
|
887
|
-
```js
|
|
888
|
-
import { createWorker } from 'agglomerative-clustering/worker';
|
|
889
|
-
|
|
890
|
-
// Four workers; each call goes to the one with the least work waiting.
|
|
891
|
-
const pool = Array.from({ length: 4 }, () => ({ worker: createWorker(), waiting: 0 }));
|
|
892
|
-
const run = async (method, ...args) => {
|
|
893
|
-
const slot = pool.reduce((best, next) => (next.waiting < best.waiting ? next : best));
|
|
894
|
-
slot.waiting++;
|
|
895
|
-
const call = slot.worker[method];
|
|
896
|
-
try {return await call(...args);} finally {slot.waiting--;}
|
|
897
|
-
};
|
|
898
|
-
|
|
899
|
-
// In a request handler (Fastify shown): stop the work if the client goes away. In Node, listen on the response's
|
|
900
|
-
// 'close' (reply.raw, or res in Express), not the request's.
|
|
901
|
-
const controller = new AbortController();
|
|
902
|
-
reply.raw.on('close', () => {if (!reply.raw.writableFinished) {controller.abort();}});
|
|
903
|
-
const swatches = await run('getSwatches', image, 8, { precision: 6, signal: controller.signal });
|
|
904
|
-
```
|
|
136
|
+
- **[Guides](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md):** swatches and choosing a palette size, GIFs and palette PNGs, animations, live video, workers, fixed palettes (e-ink, thread, bricks), batches of images, converting the output, and moving from color-thief, node-vibrant or image-q.
|
|
137
|
+
- **[API reference](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md):** input formats, options, choosing a colour space, transparency, `Palette` and `Clustering`, cancelling and progress, errors, the worker entry, TypeScript, and every function.
|
|
138
|
+
- **[Environments](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md):** CDNs, Deno, Bun, Cloudflare Workers, serverless functions, Next.js, Angular and other bundlers, Electron, browser extensions, plugin hosts, pnpm and Yarn, and testing.
|
|
139
|
+
- **[Performance and limits](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/performance.md):** servers and worker pools, memory, and large images.
|
|
140
|
+
- **[Troubleshooting](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/troubleshooting.md):** what an error or a surprising result means, and what to do.
|
|
141
|
+
- **[Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md)** from 2.x and 1.x, and the [CHANGELOG](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/CHANGELOG.md).
|
|
142
|
+
- **[Stability and versioning](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/stability.md):** what won't change within a major version.
|
|
143
|
+
- **[How the algorithm works](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/how-it-works.md)**, with architecture notes for contributors in [CLAUDE.md](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/CLAUDE.md).
|
|
144
|
+
- **[Roadmap](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/ROADMAP.md):** what is planned, and what was tried and dropped.
|
|
905
145
|
|
|
906
|
-
|
|
907
|
-
- **Memory:** one image can need up to 2 GB in a worker, so a pool of four can peak near 8 GB on hostile input; a pixel cap and `precision: 6` keep it to a fraction of that. Memory comes back after a large image, but not at once (below).
|
|
908
|
-
- **Address space:** each WebAssembly instance (the main entry's, and one per worker) reserves about 10 GB of *virtual* memory up front on 64-bit engines, of which it uses only what it needs. A virtual-memory limit (`ulimit -v`) refuses that reservation, which shows as `wasm-load-failed`; limit resident memory instead. A container's memory limit (a cgroup's `memory.max`, Docker's `--memory`) applies to what is used, but when it is reached the kernel kills the process: there is no `out-of-memory` error to catch, so cap the image size below it.
|
|
909
|
-
- **Stored clusterings:** make them with `precision: 6`. An exact clustering of a noisy 4-megapixel image is 78 MB, against 5.5 MB at `precision: 6`. Read back, wrap the bytes once with `new Clustering(bytes)` and keep that object while you use it: its checksum is checked the first time an object is used (2 to 3 ms for a photo's clustering).
|
|
910
|
-
- Running out of memory is a catchable `out-of-memory` error, and `terminate()` on each worker shuts the pool down.
|
|
911
|
-
|
|
912
|
-
**Large images.** Time and memory grow with the number of *distinct colours*, not just pixels: a 12-megapixel photo takes 2 to 8 s exact (0.2 to 0.9 million distinct colours) and 0.1 to 0.4 s with `precision: 6`, and 36 megapixels of random noise (the worst case) about 6 s with `precision: 6`. (Times are from an idle machine; a busy or throttled one, a laptop on battery or a CI runner can be several times slower.) One WebAssembly instance can use up to 2 GB, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA: 22000 × 22000 works); an image that needs more is rejected with `out-of-memory`, and later calls work normally. WebAssembly memory only grows, so after a call that leaves it above 256 MB the library drops the instance (the next call loads a fresh one, in milliseconds). The engine frees the old instance's memory at its next garbage collection, which in an idle process or worker can be much later: a worker that clustered 12 megapixels of noise held about 1 GB until it had served about a hundred more calls. `terminate()` frees a worker's memory at once.
|
|
913
|
-
|
|
914
|
-
The unsliced steps between slices (see [Cancelling and progress](#cancelling-and-progress)) take up to about 150 ms on a 12-megapixel photo, but grow with the number of distinct colours: on 12 megapixels of noise at full precision one takes over a second, and progress moves unevenly. `precision: 6` keeps them short.
|
|
915
|
-
|
|
916
|
-
### Troubleshooting
|
|
917
|
-
|
|
918
|
-
| What you see | Why | What to do |
|
|
919
|
-
|---|---|---|
|
|
920
|
-
| `wasm-load-failed` | The `.wasm` is missing, blocked, served from another version, moved by a server bundle, or the browser has no WebAssembly SIMD. | Check the file is served and the Content-Security-Policy allows `'wasm-unsafe-eval'`; say where it is with `init({ wasm })`. In Next.js, see "Next.js". |
|
|
921
|
-
| `invalid-argument` naming a PNG, JPEG, … | You passed an image file's bytes, not pixels. | Decode it first (canvas or `createImageBitmap` in a browser, sharp in Node). |
|
|
922
|
-
| A palette of nonsense, no error | RGB bytes were passed bare, so they were read as RGBA. | Pass `{ data, format: 'rgb', width }`, or add an alpha channel (`sharp(...).ensureAlpha()`). |
|
|
923
|
-
| `invalid-argument` for a canvas, `Blob` or `ImageBitmap` | Those aren't pixels. | Draw to a canvas and pass `getImageData()`. |
|
|
924
|
-
| The palette isn't sorted by how much of the image each colour covers | Palettes come in split order, so they nest. | Sort by `shares` (see "Using the output"), or accept the order. |
|
|
925
|
-
| `quantizeWithPalette` maps differently from a plain-bytes palette | A `Palette` is matched in the space it was made in, unless you name one. | Pass `colorSpace` explicitly if you want a specific space. |
|
|
926
|
-
| A stored OKLab palette maps differently from when it was made | Storage dropped its colour space, so it is matched in RGB. | Store `palette.colorSpace` too and restore it with `new Palette(bytes, colorSpace)` (see "Palette and Clustering"). |
|
|
927
|
-
| `invalid-clustering` for a clustering you stored | Its bytes changed in storage (truncated, re-encoded, mixed up). | Cluster the image again, and check how it is stored: as a binary blob, or base64 that is decoded in full. |
|
|
928
|
-
| `out-of-memory` | An image with very many distinct colours. | Use `precision: 6`, or a smaller image. |
|
|
929
|
-
| The worker doesn't start under a bundler (`worker-failed`, or a 404 for `worker-thread.mjs`) | The bundler didn't emit the worker script (Angular, esbuild, Rollup). | Copy the package's `dist/` files and pass `createWorker({ script })`: see [Angular, esbuild, Rollup and other bundlers](#angular-esbuild-rollup-and-other-bundlers). |
|
|
930
|
-
| Jest: "Must use import to load ES Module" (or "Cannot use import statement" for `/worker`) | An older package version; this one loads in Jest's CommonJS mode, both entries. | Upgrade to the latest `3.0.0-beta`. |
|
|
931
|
-
| `wasm-load-failed` mentioning a Content-Security-Policy | The page or extension forbids compiling WebAssembly. | Add `'wasm-unsafe-eval'` to `script-src`: the page's for the worker entry's worker, also from a content script. |
|
|
932
|
-
| `wasm-load-failed`: "is not WebAssembly" | An error page (a 404, or a server's fallback page) was served in place of `clustering.wasm`. | Open the `.wasm` URL in the browser; copy the file where it is expected, or say where it is with `init({ wasm })`. |
|
|
933
|
-
| `worker-failed` with the worker entry from a CDN, under a CSP | `worker-src` allows `blob:` but not the CDN the worker imports from. | `worker-src blob: <the CDN's origin>`. |
|
|
934
|
-
| `worker-failed` in a serverless function, "Cannot find module … worker-thread.mjs" | The bundler or file tracer left the worker's files out. | Leave the package external, or ship `dist/` and pass `createWorker({ script })`: see [Serverless functions](#serverless-functions-aws-lambda-vercel-netlify). |
|
|
935
|
-
| `worker-failed` under Yarn Plug'n'Play, a path inside a `.zip` | Node can't load the worker's ES modules from the zip without Yarn's loader. | Run with `yarn node`, or `yarn unplug agglomerative-clustering`. |
|
|
936
|
-
| `wasm-load-failed` under `ulimit -v` | Each instance reserves about 10 GB of address space. | Limit resident memory instead (see [Performance and limits](#performance-and-limits)). |
|
|
937
|
-
| Threads and memory grow in a long-running process | `createWorker()` workers that were dropped without `terminate()`. | Reuse a few workers, or terminate each one. |
|
|
938
|
-
| TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
|
|
939
|
-
|
|
940
|
-
## More
|
|
941
|
-
|
|
942
|
-
- **[Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md)** from 2.x (and 1.x) to the current version, and the [CHANGELOG](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/CHANGELOG.md) for every release.
|
|
943
|
-
- **[Stability and versioning](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/stability.md)**: what won't change within a major version.
|
|
944
|
-
- **[How it works](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/how-it-works.md)**: the algorithm, and the architecture notes for contributors in [CLAUDE.md](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/CLAUDE.md).
|
|
945
|
-
- **[Roadmap](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/ROADMAP.md)**: what is planned and what was tried and dropped.
|
|
946
|
-
|
|
947
|
-
### Demo
|
|
146
|
+
## Demo
|
|
948
147
|
|
|
949
148
|
```sh
|
|
950
149
|
git clone https://github.com/RohanFredriksson/agglomerative-clustering && cd agglomerative-clustering
|