agglomerative-clustering 2.0.0-beta.1 → 3.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,16 +8,17 @@
8
8
 
9
9
  ![The Kodak parrots photo cut to 4, 16 and 64 colours from one clustering, and 16 colours with dithering](docs/palette-sizes.png)
10
10
 
11
- Most colour quantizers answer one question: *give me k colours*. Ask for a different k and they start over. This library builds the complete merge hierarchy of the image's colours with Ward's method, which merges whichever two colour groups add the least squared error. Every palette size is then a cut of that one tree:
11
+ Most colour quantizers answer one question: *give me k colours*. Ask for a different k and they start over. This library clusters an image's colours once, into a complete tree, and every palette size is then a cheap cut of that tree. A colour-count slider, or a set of 8, 16, 32 and 64 colour versions, costs one clustering instead of one per size.
12
12
 
13
- - **Every palette size from one pass.** After clustering, a palette of any size takes about 0.4 ms. A colour-count slider, or a set of 8/16/32/64-colour variants, costs one clustering instead of one per size.
14
- - **Palettes nest, in a stable order.** The 16-colour palette is the 32-colour one with pairs merged. Index 0 is always the dominant colour, and each larger palette is the previous one with one entry refined and one colour appended, so swatches don't jump around as the count changes.
15
- - **Transparency-aware.** Pixels count in proportion to their opacity, so a logo's transparent background never ends up in its palette.
16
- - **Accurate.** Across the 24 Kodak photos it has the lowest average error of the six JavaScript quantizers we benchmarked, at every palette size from 16 to 256.
17
- - **Fast enough to be interactive.** A 768×512 photo takes about 100 ms exact, in RGB or OKLab, or about 30 ms with `precision: 6` at the same quality. That is level with or faster than libimagequant and 3.7–15× faster than image-q.
18
- - **Small and portable.** 65 KB of WebAssembly with SIMD, Node and browsers, an async API, TypeScript types and no runtime dependencies. Output is deterministic.
13
+ - **Every palette size from one pass.** Clustering a photo takes about 100 ms. After that, a palette of any size takes about 0.4 ms.
14
+ - **Palettes nest, in a stable order.** The 16-colour palette is the 32-colour one with pairs merged, so swatches don't jump around as the count changes.
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
+ - **Transparency-aware.** A logo's transparent background never ends up in its palette. GIF and palette PNG output are built in.
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 ([numbers](#how-it-compares)).
19
+ - **Small and portable.** 88 KB of WebAssembly, Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
19
20
 
20
- **[Try the demo](#demo)**: drop in an image and drag the palette-size slider.
21
+ [Install](#install) · [Quick start](#quick-start) · [The idea](#the-idea-in-one-minute) · [Guides](#guides) · [Reference](#reference) · [API](#api) · [Troubleshooting](#troubleshooting)
21
22
 
22
23
  ## Install
23
24
 
@@ -25,36 +26,91 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
25
26
  npm install agglomerative-clustering
26
27
  ```
27
28
 
29
+ It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (see [Where it runs](#where-it-runs)).
30
+
28
31
  ## Quick start
29
32
 
33
+ **In Node, with [sharp](https://sharp.pixelplumbing.com/):**
34
+
30
35
  ```js
36
+ import sharp from 'sharp';
31
37
  import { getPalette, quantize } from 'agglomerative-clustering';
32
38
 
33
- // `image` is ImageData, a raw RGBA Uint8Array, or { data, format: 'rgb' | 'rgba' }
34
- const palette = await getPalette(image, 8); // Uint8Array: [r, g, b, r, g, b, ...]
35
- const reduced = await quantize(image, 16, { dither: true }); // same type as the input
39
+ const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
40
+ const image = { data: new Uint8Array(data.buffer, data.byteOffset, data.length), format: 'rgba', width: info.width };
41
+
42
+ const palette = await getPalette(image, 8); // flat bytes: [r, g, b, r, g, b, ...]
43
+ const reduced = await quantize(image, 16, { dither: true }); // the image, in 16 colours
44
+
45
+ await sharp(Buffer.from(reduced.data), { raw: { width: info.width, height: info.height, channels: 4 } }).toFile('photo-16.png');
36
46
  ```
37
47
 
38
- ### Cluster once, cut anywhere
48
+ **In the browser, with a canvas:**
39
49
 
40
50
  ```js
41
- import { getClustering, getPaletteFromClustering, quantizeWithPalette } from 'agglomerative-clustering';
51
+ import { quantize } from 'agglomerative-clustering';
42
52
 
43
- const clustering = await getClustering(imageData); // the expensive step, done once
53
+ const ctx = canvas.getContext('2d');
54
+ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
44
55
 
45
- slider.oninput = async () => {
46
- const k = Number(slider.value);
47
- const palette = await getPaletteFromClustering(clustering, k); // ~0.4 ms for any k
48
- const result = await quantizeWithPalette(imageData, palette); // ~5-12 ms for a 768×512 image
49
- ctx.putImageData(result, 0, 0);
50
- };
56
+ ctx.putImageData(await quantize(imageData, 16, { dither: true }), 0, 0); // ImageData in, ImageData out
57
+ ```
58
+
59
+ **Swatches, with each colour's share of the image:**
60
+
61
+ ```js
62
+ import { getSwatches } from 'agglomerative-clustering';
63
+
64
+ const { palette, shares } = await getSwatches(imageData, 6); // six colours; the shares sum to 1
65
+ shares.forEach((share, i) => {
66
+ console.log(`rgb(${palette[3 * i]} ${palette[3 * i + 1]} ${palette[3 * i + 2]})`, `${(share * 100).toFixed(1)}%`);
67
+ });
51
68
  ```
52
69
 
53
- The clustering is a compact `Uint8Array` (a 4-byte header plus 9 bytes per distinct colour), so you can cache it or store it next to the image. It records the colour space it was made in, so `quantizeWithClustering` matches in the same space unless you say otherwise.
70
+ Those three are all you need to get started. The rest of this page is organised by what you want to do (the [guides](#guides)) and by what to look up (the [reference](#reference) and the [API](#api)).
54
71
 
55
- ## How it compares
72
+ ## The idea in one minute
73
+
74
+ ```
75
+ image ──▶ getClustering ──▶ a clustering ──▶ cut to k colours ──▶ a palette ──▶ map the pixels ──▶ reduced image
76
+ once, ~100 ms bytes you can under 1 ms, flat RGB a few ms,
77
+ store any k bytes any palette
78
+ ```
79
+
80
+ The one-shot functions (`getPalette`, `quantize`, …) do the first steps for you. To try many palette sizes, call `getClustering` once and cut it as often as you like.
81
+
82
+ | You want | from the image | from a clustering you hold | with a palette you supply |
83
+ |---|---|---|---|
84
+ | a palette (flat RGB) | `getPalette` | `getPaletteFromClustering` | |
85
+ | a palette with each colour's share | `getSwatches` | `getSwatchesFromClustering` | |
86
+ | the image reduced to those colours | `quantize` | `quantizeFromClustering` | `quantizeWithPalette` |
87
+ | palette indices (GIF, PNG-8) | `quantizeToIndices` | `quantizeToIndicesFromClustering` | `quantizeToIndicesWithPalette` |
56
88
 
57
- This table covers 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 22.
89
+ The names follow one rule: **`…FromClustering`** derives the colours from a clustering you already hold, and **`…WithPalette`** takes colours you supply. With neither, the image is clustered for you. `getClustering` builds the clustering to hold, `getClusteringInfo` reads one, and `init` loads the WebAssembly module (optional). Most code only needs the first column.
90
+
91
+ Five words are used throughout:
92
+
93
+ - **clustering**: the tree of an image's colours. It is opaque bytes (a `Clustering`) that you can store next to the image.
94
+ - **palette**: flat RGB bytes, `[r, g, b, r, g, b, …]`. A `Palette` knows the colour space it was made in.
95
+ - **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.
96
+ - **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.
97
+ - **precision**: an option that groups similar colours before clustering, about 3× faster at practically the same quality.
98
+
99
+ ## Is it the right tool?
100
+
101
+ **A good fit:**
102
+ - **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.
103
+ - **Several palette sizes for the same image,** or storing one clustering and cutting it later.
104
+ - **The most accurate palette for a given size,** for example as a starting point for vectorisation or flat-colour art.
105
+
106
+ **Probably not the right tool:**
107
+ - **Shrinking PNG files in a build pipeline.** Use [sharp](https://sharp.pixelplumbing.com/) or pngquant, which run libimagequant natively and are tuned for compression.
108
+ - **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.
109
+ - **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.
110
+
111
+ ### How it compares
112
+
113
+ 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 22.
58
114
 
59
115
  | Library | PSNR | Error vs ours | One palette | Palettes at 16/64/128/256 |
60
116
  |---|---|---|---|---|
@@ -66,86 +122,141 @@ This table covers the 24 Kodak photos (768×512) at 64 colours. "Error vs ours"
66
122
  | MMCQ (color-thief's algorithm) | 32.53 dB | 2.08× | 24 ms | 120 ms |
67
123
  | image-q RgbQuant | 31.95 dB | 2.38× | 385 ms | 1535 ms |
68
124
 
69
- The `precision: 6` row comes from a separate run on the same machine. Full results at every palette size, on synthetic images too, with ΔE2000 and the method, are in [bench/COMPARISON.md](bench/COMPARISON.md). You can reproduce them with `node bench/run.js`.
125
+ The `precision: 6` row comes from a separate run on the same machine. 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.
70
126
 
71
- ## Options
127
+ ## Guides
72
128
 
73
- 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.
129
+ ### Cluster once, cut anywhere
74
130
 
75
- | Option | Applies to | Values | What it does |
76
- |---|---|---|---|
77
- | `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. |
78
- | `colorSpace` | clustering and mapping | `'rgb'` (default), `'oklab'` | `'oklab'` clusters and matches in [OKLab](https://bottosson.github.io/posts/oklab/), where distance tracks perceived difference. It gives lower ΔE2000 at 64+ colours and on smooth gradients, at the cost of PSNR. Use it when the result is for human eyes and you want 64 or more colours. At 16 colours, RGB is better. |
79
- | `alpha` | clustering | `'weight'` (default), `'ignore'` | `'weight'` counts each RGBA pixel in proportion to its opacity: fully transparent pixels are ignored, and semi-transparent ones count partially. For opaque images, and images whose pixels are only fully opaque or fully transparent, this is exact pixel counting. `'ignore'` counts every pixel fully, as 1.x did. Alpha is always preserved in the output. |
80
- | `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. It scores worse on per-pixel metrics such as PSNR, because the noise is the point. Error is diffused in the chosen `colorSpace`, and fully transparent pixels are left undithered. |
81
- | `width` | mapping | integer | Needed for dithering when the image is a `Uint8Array`, or a `RawImage` without `width`. `ImageData` provides it. |
131
+ ```js
132
+ import { getClustering, getPaletteFromClustering, quantizeWithPalette } from 'agglomerative-clustering';
82
133
 
83
- "Clustering" means `getClustering` and `getPalette`, "mapping" means `quantizeWithClustering` and `quantizeWithPalette`, and `quantize` takes both.
134
+ const clustering = await getClustering(imageData); // the expensive step, done once
84
135
 
85
- Measured on the Kodak photos:
136
+ slider.oninput = async () => {
137
+ const k = Number(slider.value);
138
+ const palette = await getPaletteFromClustering(clustering, k); // ~0.4 ms for any k
139
+ const result = await quantizeWithPalette(imageData, palette); // ~5-12 ms for a 768×512 image
140
+ ctx.putImageData(result, 0, 0);
141
+ };
142
+ ```
86
143
 
87
- | Setting | 16 colours ΔE2000 | 256 colours ΔE2000 | One 64-colour palette |
88
- |---|---|---|---|
89
- | default (`rgb`, exact) | **4.31** | 1.67 | 102 ms |
90
- | `precision: 6` | **4.29** | 1.68 | 31 ms |
91
- | `colorSpace: 'oklab'` | 4.46 | **1.60** | 104 ms |
92
- | `colorSpace: 'oklab', precision: 6` | 4.44 | 1.61 | 39 ms |
93
- | libimagequant, for reference | 4.38 | 1.61 | 147 ms |
144
+ A clustering is about 1.3 MB for a 768×512 photo (0.45 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)).
145
+
146
+ ### Swatches, and choosing a palette size
94
147
 
95
148
  ```js
96
- // Perceptual palettes for a photo, quickly
97
- const palette = await getPalette(photo, 128, { colorSpace: 'oklab', precision: 6 });
149
+ import { getSwatches, getClustering, getSwatchesFromClustering, getClusteringInfo } from 'agglomerative-clustering';
98
150
 
99
- // Retro look: 8 colours, dithered
100
- const retro = await quantize(imageData, 8, { dither: true });
151
+ // Colours with their share of the image, in one call
152
+ const { palette, weights, shares } = await getSwatches(image, 8);
153
+ // palette: flat RGB bytes, weights: pixels per colour, shares: each colour's share of the image (they sum to 1)
101
154
 
102
- // Dithering a raw buffer needs its width
103
- const out = await quantize(rgbaBytes, 32, { dither: 0.8, width: 640 });
155
+ // Or cluster once and cut it as often as you like (well under a millisecond each)
156
+ const clustering = await getClustering(image);
157
+ const eight = await getSwatchesFromClustering(clustering, 8);
158
+
159
+ // The smallest palette that keeps 99% of the image's colour variance (works the same in 'rgb' and 'oklab')
160
+ const { explained } = await getClusteringInfo(clustering);
161
+ const k = explained.findIndex((share) => share >= 0.99) + 1;
104
162
  ```
105
163
 
106
- ## When to use it, and when not
164
+ ### GIFs and palette PNGs
107
165
 
108
- **A good fit:**
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.
110
- - **Generating several palette sizes for the same image,** or storing one clustering and cutting it later.
111
- - **When you want the most accurate palette for a given size,** for example as a starting point for vectorisation or flat-colour art.
166
+ `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`.
112
167
 
113
- **Probably not the right tool:**
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.
115
- - **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.
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.
168
+ **A GIF** with [gifenc](https://github.com/mattdesl/gifenc), keeping a transparent background:
117
169
 
118
- ## Usage
170
+ ```js
171
+ import { GIFEncoder } from 'gifenc'; // in plain Node ESM: import gifenc from 'gifenc'; const { GIFEncoder } = gifenc;
172
+ import { quantizeToIndices } from 'agglomerative-clustering';
119
173
 
120
- ### Browser (Canvas)
174
+ // k counts the transparent entry, so 256 is the most a GIF holds. `image` is { data, format: 'rgba', width, height }.
175
+ const { palette, indices, transparentIndex } = await quantizeToIndices(image, 256, { transparent: true });
176
+ const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
177
+
178
+ const gif = GIFEncoder();
179
+ gif.writeFrame(indices, image.width, image.height, { palette: colors, transparent: transparentIndex !== null, transparentIndex: transparentIndex ?? 0 });
180
+ gif.finish();
181
+ const bytes = gif.bytes();
182
+ ```
183
+
184
+ **A palette PNG** with [fast-png](https://github.com/image-js/fast-png): the same call, then give the transparent entry alpha 0:
121
185
 
122
186
  ```js
123
- import { quantize } from 'agglomerative-clustering';
187
+ import { encode } from 'fast-png';
124
188
 
125
- const ctx = canvas.getContext('2d');
126
- const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
189
+ const png = encode({
190
+ width: image.width, height: image.height, data: indices, depth: 8, channels: 1,
191
+ palette: colors.map((color, i) => [...color, i === transparentIndex ? 0 : 255]),
192
+ });
193
+ ```
127
194
 
128
- // ImageData in, ImageData out
129
- const result = await quantize(imageData, 16, { dither: true });
130
- ctx.putImageData(result, 0, 0);
195
+ With at most 256 entries, `indices` is a `Uint8Array`, as these formats need (`indexBits` says so). To map more frames with the same colours, pass the result's `colors` (the palette without the transparent entry) to `quantizeToIndicesWithPalette`.
196
+
197
+ ### Off the main thread
198
+
199
+ Clustering a photo takes about 100 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):
200
+
201
+ ```js
202
+ import { quantize } from 'agglomerative-clustering/worker'; // same API, one shared worker
203
+ const reduced = await quantize(imageData, 16);
131
204
  ```
132
205
 
133
- ### Node.js (with sharp)
206
+ 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:
134
207
 
135
208
  ```js
136
- import { quantize } from 'agglomerative-clustering';
137
- import sharp from 'sharp';
209
+ import { createWorker } from 'agglomerative-clustering/worker';
138
210
 
139
- const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
140
- const image = { data: new Uint8Array(data.buffer, data.byteOffset, data.length), format: 'rgba', width: info.width };
211
+ const worker = createWorker();
212
+ const handle = await worker.cluster(imageData, { precision: 6 });
213
+
214
+ slider.oninput = async () => {
215
+ ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true }), 0, 0);
216
+ };
217
+ ```
218
+
219
+ It starts the worker with `new Worker(new URL('./worker-thread.mjs', import.meta.url))`, the form bundlers look for: CI tests Vite, webpack 5 (as Next.js uses it) and esbuild, and Parcel 2 works with its `packageExports` option on. In Node an idle worker never keeps the process alive. See the [worker reference](#worker-entry).
141
220
 
142
- const { data: output } = await quantize(image, 32, { precision: 6, dither: true });
221
+ ### Using the output
143
222
 
144
- await sharp(Buffer.from(output), { raw: { width: info.width, height: info.height, channels: 4 } }).toFile('photo-32.png');
223
+ 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`):
224
+
225
+ ```js
226
+ // [[r, g, b], …]: what gifenc, fast-png, color-thief and libimagequant use
227
+ const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
228
+
229
+ // A CSS colour, and a 0xRRGGBB number
230
+ const css = (i) => `rgb(${palette[3 * i]} ${palette[3 * i + 1]} ${palette[3 * i + 2]})`;
231
+ const hex = (i) => (palette[3 * i] << 16) | (palette[3 * i + 1] << 8) | palette[3 * i + 2];
232
+
233
+ // 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)
234
+ const swatches = Array.from(shares, (share, i) => ({ color: css(i), share }));
235
+ ```
236
+
237
+ **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.
238
+
239
+ ```js
240
+ // A palette and its weights, heaviest first
241
+ const order = Array.from(weights.keys()).sort((a, b) => weights[b] - weights[a]); // old index of the 1st, 2nd, … entry
242
+ const rankedColors = order.map((i) => colors[i]);
243
+ const rankedShares = order.map((i) => shares[i]);
244
+
245
+ // An indexed image, heaviest first: count how many pixels use each entry (that is what "heaviest" means for the image),
246
+ // sort, and renumber the indices
247
+ const used = new Uint32Array(palette.length / 3);
248
+ for (const index of indices) {used[index]++;}
249
+ const byUse = Array.from(used.keys()).sort((a, b) => used[b] - used[a]);
250
+ const rank = new Uint32Array(used.length);
251
+ byUse.forEach((old, position) => {rank[old] = position;});
252
+ const rankedPalette = byUse.map((old) => colors[old]);
253
+ const rankedIndices = indices.map((index) => rank[index]); // same typed-array type as `indices`
254
+ const rankedTransparentIndex = transparentIndex === null ? null : rank[transparentIndex];
145
255
  ```
146
256
 
147
- ## Input types
257
+ ## Reference
148
258
 
259
+ ### Input and output
149
260
  Every function that takes an image accepts:
150
261
 
151
262
  ```ts
@@ -156,45 +267,291 @@ ImageData // from a canvas: always RGBA, widt
156
267
  width?: number, height?: number } // optional: used for dithering, copied to results
157
268
  ```
158
269
 
159
- The `quantize*` functions return the same type they were given: a `Uint8Array` for a `Uint8Array`, `ImageData` for `ImageData`, and an object with the same `format` (plus `width`/`height` if given) for an object.
270
+ `width` and `height` must be whole numbers, and when both are given they must account for exactly the pixels in `data`.
271
+
272
+ > **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()`).
273
+
274
+ > **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](docs/ROADMAP.md).
275
+
276
+ 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.
277
+
278
+ ### Options
279
+
280
+ 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.
281
+
282
+ | Option | Applies to | Values | What it does |
283
+ |---|---|---|---|
284
+ | `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. |
285
+ | `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". |
286
+ | `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. |
287
+ | `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. |
288
+ | `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. |
289
+ | `signal` | any call with an image | an `AbortSignal` | Cancels the call; see "Cancelling and progress". |
290
+ | `onProgress` | clustering | `(fraction) => void` | Reports 0 to 1 as the clustering runs; see "Cancelling and progress". |
291
+ | `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". |
292
+
293
+ "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.
294
+
295
+ 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.
296
+
297
+ ```js
298
+ // Perceptual palettes for a photo, quickly
299
+ const palette = await getPalette(photo, 128, { colorSpace: 'oklab', precision: 6 });
300
+
301
+ // Retro look: 8 colours, dithered
302
+ const retro = await quantize(imageData, 8, { dither: true });
303
+
304
+ // Dithering a raw buffer needs its width
305
+ const out = await quantize(rgbaBytes, 32, { dither: 0.8, width: 640 });
306
+ ```
307
+
308
+ #### Choosing a colour space
309
+
310
+ `'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:
311
+
312
+ | You are making | Colours | Use | What the numbers say |
313
+ |---|---|---|---|
314
+ | 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. |
315
+ | 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). |
316
+ | Dithered GIF, retro look | 8–64 | `'rgb'` | Looks closer from a distance: blurred ΔE 2.59 against 2.86 at 16 colours. |
317
+ | Flat graphics, logos, pixel art | 8–32 | either | About equal. |
318
+ | 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). |
319
+ | Noisy or very varied images | any | `'oklab'` | Mean ΔE 7.0 against 7.9 at 64 colours (one synthetic image). |
320
+
321
+ `'oklab'` also takes 10–30% 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.
322
+
323
+ How the options trade speed and quality, measured on the Kodak photos:
324
+
325
+ | Setting | 16 colours ΔE2000 | 256 colours ΔE2000 | One 64-colour palette |
326
+ |---|---|---|---|
327
+ | default (`rgb`, exact) | **4.31** | 1.67 | 102 ms |
328
+ | `precision: 6` | **4.29** | 1.68 | 31 ms |
329
+ | `colorSpace: 'oklab'` | 4.46 | **1.60** | 104 ms |
330
+ | `colorSpace: 'oklab', precision: 6` | 4.44 | 1.61 | 39 ms |
331
+ | libimagequant, for reference | 4.38 | 1.61 | 147 ms |
332
+
333
+ #### Transparency
334
+
335
+ Three things in this library are about alpha, and they act at different stages:
336
+
337
+ | | What it is | Stage | Effect |
338
+ |---|---|---|---|
339
+ | `'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. |
340
+ | `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. |
341
+ | `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". |
342
+
343
+ 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.
344
+
345
+ ### Palette and Clustering
346
+ 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 three things:
347
+
348
+ - **A palette maps in the space it was made in.** `quantizeWithPalette(image, palette)` matches an OKLab palette in OKLab without being told; name a `colorSpace` to override it. Plain bytes are matched in RGB.
349
+ - **A clustering can't be passed as a palette**, or the other way round. TypeScript rejects it, and at run time it throws (`invalid-argument` or `invalid-clustering`), with no guessing about bytes.
350
+ - **`new Palette(bytes, colorSpace)` and `new Clustering(bytes)` give bytes their type back**, and check them: `new Palette([300, 0, 0])` throws rather than wrapping 300 to 44, and `new Clustering(bytes)` throws `invalid-clustering` unless they are one. The functions still accept a clustering as plain bytes, so stored clusterings keep working in JavaScript; TypeScript wants the constructor.
351
+
352
+ ```js
353
+ import { Clustering, Palette, getPaletteFromClustering } from 'agglomerative-clustering';
354
+
355
+ const stored = new Uint8Array(await db.get('clustering')); // what storage gives back: plain bytes
356
+ const clustering = new Clustering(stored); // typed again, and checked
357
+ const palette = await getPaletteFromClustering(clustering, 8);
358
+ palette instanceof Palette; // true
359
+ palette.colorSpace; // 'rgb' or 'oklab', as it was clustered
360
+ palette.slice(0, 3) instanceof Palette; // false: slice, subarray and clones are plain bytes
361
+ ```
362
+
363
+ `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) [ … ]`.
364
+
365
+ ### Cancelling and progress
366
+ Every function that takes an image accepts `signal`; the ones that cluster (`getClustering`, `getPalette`, `getSwatches`, `quantize`, `quantizeToIndices`) also accept `onProgress`:
367
+
368
+ ```js
369
+ const controller = new AbortController();
370
+ const clustering = await getClustering(image, {
371
+ signal: controller.signal, // controller.abort() cancels it
372
+ onProgress: (fraction) => bar.value = fraction, // 0 to 1
373
+ });
374
+ ```
375
+
376
+ - **Slices.** With either option, clustering runs in slices of about 10 ms, so an abort takes effect within a slice and the page stays responsive. The result is the same; slicing costs about 5% more time.
377
+ - **Aborting** rejects with the signal's `reason` (an `AbortError` by default), like `fetch`. It is the one error without a `code`: check `error.name === 'AbortError'`. An already aborted signal does no work.
378
+ - **Mapping can't be interrupted** (it takes a few milliseconds). The functions that only map check the signal before they start, and don't take `onProgress`.
379
+ - **Progress** is approximate, never goes backwards, and ends at exactly 1.
380
+ - **In a worker** the worker itself stops, and a call still queued is removed without running.
381
+
382
+ ### Errors
383
+
384
+ 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`).
385
+
386
+ When an error is about one argument, `error.argument` names it: `'image'`, `'k'`, `'clustering'`, `'palette'`, `'options'`, 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.
387
+
388
+ | `code` | When |
389
+ | --- | --- |
390
+ | `invalid-argument` | A bad image, `k`, option or palette. |
391
+ | `invalid-clustering` | Bytes that aren't a clustering this version can read. |
392
+ | `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`). |
393
+ | `out-of-memory` | The WebAssembly module couldn't allocate. |
394
+ | `wasm-load-failed` | The WebAssembly module couldn't be loaded or compiled: a missing or blocked `.wasm` file, 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 says what to check, and `cause` is the engine's own error. |
395
+ | `worker-terminated`, `worker-failed`, `invalid-handle` | Worker entry only: the worker was stopped or failed to start, or a handle was released. |
396
+
397
+ ```js
398
+ try {
399
+ await getPaletteFromClustering(stored, 16);
400
+ } catch (error) {
401
+ if (error.code === 'unsupported-version' || error.code === 'invalid-clustering') { /* cluster the image again */ }
402
+ else { throw error; }
403
+ }
404
+ ```
405
+
406
+ 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`.
407
+
408
+ ### Worker entry
409
+ `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:
410
+
411
+ - **`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.
412
+ - **`terminate()`** stops the worker and rejects the calls still waiting.
413
+
414
+ 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. The entry is an ES module; `require()` works too on the supported Node versions.
415
+
416
+ ### TypeScript
417
+ 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. From a CommonJS file, load the worker entry with `await import('agglomerative-clustering/worker')`, or use TypeScript 5.8+ with `module: nodenext`.
418
+
419
+ Results narrow: checking `result.indexBits === 8` makes `indices` a `Uint8Array`, and checking `info.formatVersion === 3` makes `mse`, `explained` and `totalWeight` present. Palette parameters take a `PaletteLike` (a `Palette`, plain bytes or a `number[]`, not a `Clustering`), and errors are `CodedError`s with `code` and `argument`.
160
420
 
161
421
  ## API
162
422
 
163
- ### `getClustering(image, options?): Promise<Uint8Array>`
164
- Builds the colour hierarchy for an image. Options: `colorSpace`, `precision`, `alpha`. Pass the result to `getPaletteFromClustering` or `quantizeWithClustering` to get any number of palettes without clustering again.
423
+ ### `getClustering(image, options?): Promise<Clustering>`
424
+ Builds the colour hierarchy for an image. Pass the result to `getPaletteFromClustering` or `quantizeFromClustering` to get any number of palettes without clustering again.
425
+
426
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `signal`, `onProgress`.
427
+
428
+ ### `getPaletteFromClustering(clustering, k): Promise<Palette>`
429
+ 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.
430
+
431
+ ### `getPalette(image, k, options?): Promise<Palette>`
432
+ `getClustering` followed by `getPaletteFromClustering`.
433
+
434
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `signal`, `onProgress`.
435
+
436
+ ### `getSwatches(image, k, options?): Promise<Swatches>`
437
+ 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:
438
+ - `palette` is flat RGB bytes in split order (what `getPaletteFromClustering` gives).
439
+ - `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.
440
+ - `shares` are the weights divided by their total, so they sum to 1.
441
+
442
+ 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`.
443
+
444
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `signal`, `onProgress`.
445
+
446
+ ### `getSwatchesFromClustering(clustering, k): Promise<Swatches>`
447
+ 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.
448
+
449
+ ### `getClusteringInfo(clustering): Promise<ClusteringInfo>`
450
+ What a clustering holds: `{ formatVersion, colorSpace, precision, transparent, maxColors, totalWeight, mse, explained }`.
451
+
452
+ - `formatVersion`: the format of its bytes (compare it with the exported `formatVersion`).
453
+ - `transparent`: the alpha cutoff it was made with, or `false`. `quantizeToIndicesFromClustering` uses it by default.
454
+ - `maxColors`: the largest palette it can be cut to.
455
+ - `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%.
456
+ - `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.
457
+
458
+ For a 2.x clustering, `formatVersion` is 2 and `totalWeight`, `mse` and `explained` are `null`; in TypeScript, checking `info.formatVersion === 3` narrows them to present.
459
+
460
+ ### `quantize(image, k, options?): Promise<the type of image>`
461
+ Reduces the image to at most `k` colours.
462
+
463
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `dither`, `width`, `signal`, `onProgress`.
464
+
465
+ ### `quantizeFromClustering(image, clustering, k, options?): Promise<the type of image>`
466
+ Quantizes using a clustering you already have.
165
467
 
166
- ### `getPaletteFromClustering(clustering, k): Promise<Uint8Array>`
167
- 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, 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 1.x too.
468
+ Options: `colorSpace` (defaults to the clustering's), `dither`, `width`, `signal`.
168
469
 
169
- ### `getPalette(image, k, options?): Promise<Uint8Array>`
170
- `getClustering` followed by `getPaletteFromClustering`. Options: `colorSpace`, `precision`, `alpha`.
470
+ ### `quantizeWithPalette(image, palette, options?): Promise<the type of image>`
471
+ 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.
171
472
 
172
- ### `quantize(image, k, options?): Promise<Uint8Array | ImageData | RawImage>`
173
- Reduces the image to at most `k` colours. Options: `colorSpace`, `precision`, `alpha`, `dither`, `width`.
473
+ Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signal`.
174
474
 
175
- ### `quantizeWithClustering(image, clustering, k, options?)`
176
- Quantizes using a clustering you already have. Options: `colorSpace` (defaults to the clustering's), `dither`, `width`.
475
+ ### `quantizeToIndices(image, k, options?): Promise<IndexedImage>`
476
+ Like `quantize`, but returns each pixel's palette index rather than its colour: what palette PNGs, GIFs, pixel art and pattern generators need.
177
477
 
178
- ### `quantizeWithPalette(image, palette, options?)`
179
- Maps each pixel to its nearest colour in any palette (flat RGB bytes). The result doesn't depend on the palette's order: equally near colours are decided by their RGB value. Options: `colorSpace`, `dither`, `width`.
478
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `dither`, `width`, `signal`, `onProgress`.
180
479
 
181
- ### `init(): Promise<void>`
182
- 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.
480
+ The result is `{ palette, colors, indices, indexBits, transparentIndex }`, plus `width` and `height` when the input has them:
481
+ - `palette`: the flat RGB bytes an encoder wants, including the transparent entry if there is one.
482
+ - `colors`: the same without the transparent entry, to pass to `quantizeToIndicesWithPalette` for more images with these colours.
483
+ - `indices`: one per pixel, a `Uint8Array` for up to 256 entries, `Uint16Array` up to 65536, else `Uint32Array`; `indexBits` (8, 16 or 32) says which.
484
+ - `transparentIndex`: the transparent entry's index, or `null`.
183
485
 
184
- Invalid inputs, palette sizes and options (including unknown option names) are rejected with a descriptive error.
486
+ 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 })`, and at least one colour is always kept. See [Transparency](#transparency).
185
487
 
186
- ## Migrating from 1.x
488
+ ```js
489
+ const { palette, colors, indices, transparentIndex } = await quantizeToIndices(imageData, 256, { transparent: true });
490
+ ```
491
+
492
+ ### `quantizeToIndicesFromClustering(image, clustering, k, options?): Promise<IndexedImage>`
493
+ 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.
494
+
495
+ Options: `colorSpace` (defaults to the clustering's), `dither`, `width`, `signal`, `transparent`.
496
+
497
+ ### `quantizeToIndicesWithPalette(image, palette, options?): Promise<IndexedImage>`
498
+ 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.
499
+
500
+ Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signal`, `transparent`.
501
+
502
+ ### `init(options?): Promise<void>`
503
+ 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).
187
504
 
188
- 2.0 keeps the same functions and defaults (`rgb`, no dithering, exact `precision`). What changes:
505
+ ### `version: string` and `formatVersion: number`
506
+ `version` is the library's version (`'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: if a stored clustering's `getClusteringInfo(stored).formatVersion` differs, cluster the image again (2.x clusterings still load, but have no weights). Both entries export both, and a `.wasm` from another version fails to load with `wasm-load-failed`.
189
507
 
190
- - **Palette order.** Palettes come in split order, dominant colour first, rather than in an arbitrary order. For opaque images they contain exactly the same colours as 1.2.
191
- - **Transparency.** RGBA pixels are weighted by opacity, so palettes of images with transparency change: fully transparent pixels no longer contribute. Pass `{ alpha: 'ignore' }` for the 1.x behaviour.
192
- - **Clustering bytes.** Clusterings gain a 4-byte header recording their colour space and precision. Clusterings saved by 1.x still load. Anything that inspected the raw bytes needs to skip the header.
193
- - **`quantizeWithClustering`** matches in the clustering's colour space unless you pass `colorSpace`.
194
- - **Exact ties** in pixel mapping go to the colour with the smaller RGB value, so results don't depend on palette order. A small number of pixels that sit exactly between two palette colours may map differently from 1.2.
195
- - **Invalid clusterings** passed to `getPaletteFromClustering` or `quantizeWithClustering` now throw instead of giving an empty palette.
508
+ ## Running it
196
509
 
197
- ## Demo
510
+ ### Where it runs
511
+
512
+ Node 20.19+ and 22.12+ (CI tests Node 20, 22 and 24), 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.
513
+
514
+ Checked by hand, not in CI: Deno 2.9, Bun 1.4 (both including the worker entry), Cloudflare Workers (a Worker bundled with esbuild, run in Miniflare) and Parcel 2.
515
+
516
+ ### Loading the WebAssembly module
517
+ 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):
518
+
519
+ ```js
520
+ await init({ wasm: 'https://cdn.example.com/clustering.wasm' }); // a URL or path string, or a URL
521
+ await init({ wasm: await (await fetch(url)).arrayBuffer() }); // the bytes
522
+ await init({ wasm: wasmModule }); // a compiled WebAssembly.Module
523
+ ```
524
+
525
+ 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`. A strict Content-Security-Policy needs `'wasm-unsafe-eval'` in `script-src`. `createWorker({ wasm })` passes the same option to a worker.
526
+
527
+ ### Performance and limits
528
+
529
+ **Servers.** Cap the pixel count of uploads, use `precision: 6` (it bounds the memory an image with very many colours needs), and use the worker entry so a clustering doesn't block the event loop. One worker runs one call at a time, so create a few with `createWorker()` for concurrency. Running out of memory is a catchable `out-of-memory` error.
530
+
531
+ **Large images.** Time and memory grow with the number of *distinct colours*, not just pixels: a 12-megapixel photo takes about 4 s exact and 0.9 s with `precision: 6`, and 36 megapixels of random noise (the worst case) about 6 s with `precision: 6`. One WebAssembly instance can use up to 2 GB; an image that needs more is rejected with `out-of-memory`, and later calls work normally.
532
+
533
+ ### Troubleshooting
534
+
535
+ | What you see | Why | What to do |
536
+ |---|---|---|
537
+ | `wasm-load-failed` | The `.wasm` is missing, blocked, served from another version, 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 })`. |
538
+ | `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). |
539
+ | 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()`). |
540
+ | `invalid-argument` for a canvas, `Blob` or `ImageBitmap` | Those aren't pixels. | Draw to a canvas and pass `getImageData()`. |
541
+ | 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. |
542
+ | `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. |
543
+ | `out-of-memory` | An image with very many distinct colours. | Use `precision: 6`, or a smaller image. |
544
+ | The worker doesn't start under a bundler | The bundler didn't see the `new Worker(new URL(...))` form. | See "Off the main thread" for the bundlers that are tested. |
545
+ | TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
546
+
547
+ ## More
548
+
549
+ - **[Migrating](docs/migrating.md)** from 2.x (and 1.x) to the current version, and the [CHANGELOG](CHANGELOG.md) for every release.
550
+ - **[Stability and versioning](docs/stability.md)**: what won't change within a major version.
551
+ - **[How it works](docs/how-it-works.md)**: the algorithm, and the architecture notes for contributors in [CLAUDE.md](CLAUDE.md).
552
+ - **[Roadmap](docs/ROADMAP.md)**: what is planned and what was tried and dropped.
553
+
554
+ ### Demo
198
555
 
199
556
  ```sh
200
557
  git clone https://github.com/RohanFredriksson/agglomerative-clustering && cd agglomerative-clustering
@@ -204,16 +561,6 @@ npm run demo # then open http://localhost:8080/demo/
204
561
 
205
562
  The demo clusters an image once, then re-cuts and re-maps it live as you drag the palette-size and dithering sliders. You can switch colour space and precision, and drop in your own images.
206
563
 
207
- ## How it works
208
-
209
- 1. **Histogram.** Distinct colours are counted with an open-addressing hash table. With `precision` below 8, colours are first grouped by their top bits.
210
- 2. **Exact Ward clustering.** A nearest-neighbour chain finds mutually cheapest pairs and merges them. Ward's criterion is reducible, so this produces exactly the same hierarchy as repeatedly merging the globally cheapest pair, without a priority queue.
211
- 3. **Fast partner search.** Clusters live in an adaptive 3D grid sized to the occupied part of colour space, with per-column occupancy bits so searches step over empty cells. Searches prune whole cells using each cell's colour box and lightest member, compute four Ward costs at once with WASM SIMD, and skip most candidates with a division-free float test before the exact double-precision check. Clusters whose searches are expensive cache their best candidates.
212
- 4. **Compact output.** The hierarchy is stored as a 4-byte header and 9-byte merge records in reverse order, each listing its heavier half first. Cutting to `k` colours replays the first `k − 1` records, which gives the stable split order.
213
- 5. **Mapping.** A memo of recent colours, then a grid over colour space whose cells list the palette entries that can be nearest there (a KD-tree for palettes above 256 colours), maps pixels to the palette, with optional error-diffusion dithering.
214
-
215
- The algorithm is C++17 compiled to WebAssembly with Emscripten. Architecture notes for contributors are in [CLAUDE.md](CLAUDE.md).
216
-
217
564
  ## License
218
565
 
219
566
  MIT © Rohan Fredriksson