agglomerative-clustering 2.0.0 → 3.0.0-beta.2

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,33 +8,126 @@
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 70 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
 
24
25
  ```sh
25
- npm install agglomerative-clustering
26
+ npm install agglomerative-clustering@next
26
27
  ```
27
28
 
29
+ **3.0 is in beta.** This page describes 3.0, which is published under the `next` tag until its release; a plain `npm install agglomerative-clustering` still gives 2.0 (see [its README](https://www.npmjs.com/package/agglomerative-clustering/v/2.0.0) and [what changed](docs/migrating.md)).
30
+
31
+ It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (see [Where it runs](#where-it-runs)).
32
+
28
33
  ## Quick start
29
34
 
35
+ **In Node, with [sharp](https://sharp.pixelplumbing.com/):**
36
+
30
37
  ```js
38
+ import sharp from 'sharp';
31
39
  import { getPalette, quantize } from 'agglomerative-clustering';
32
40
 
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
41
+ const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
42
+ const image = { data: new Uint8Array(data.buffer, data.byteOffset, data.length), format: 'rgba', width: info.width };
43
+
44
+ const palette = await getPalette(image, 8); // flat bytes: [r, g, b, r, g, b, ...]
45
+ const reduced = await quantize(image, 16, { dither: true }); // the image, in 16 colours
46
+
47
+ await sharp(Buffer.from(reduced.data), { raw: { width: info.width, height: info.height, channels: 4 } }).toFile('photo-16.png');
48
+ ```
49
+
50
+ **In the browser, with a canvas:**
51
+
52
+ ```js
53
+ import { quantize } from 'agglomerative-clustering';
54
+
55
+ const ctx = canvas.getContext('2d');
56
+ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
57
+
58
+ ctx.putImageData(await quantize(imageData, 16, { dither: true }), 0, 0); // ImageData in, ImageData out
59
+ ```
60
+
61
+ **Swatches, with each colour's share of the image:**
62
+
63
+ ```js
64
+ import { getSwatches } from 'agglomerative-clustering';
65
+
66
+ const { palette, shares } = await getSwatches(imageData, 6); // six colours; the shares sum to 1
67
+ shares.forEach((share, i) => {
68
+ console.log(`rgb(${palette[3 * i]} ${palette[3 * i + 1]} ${palette[3 * i + 2]})`, `${(share * 100).toFixed(1)}%`);
69
+ });
70
+ ```
71
+
72
+ 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)).
73
+
74
+ ## The idea in one minute
75
+
76
+ ```
77
+ image ──▶ getClustering ──▶ a clustering ──▶ cut to k colours ──▶ a palette ──▶ map the pixels ──▶ reduced image
78
+ once, ~70 ms bytes you can under 1 ms, flat RGB a few ms,
79
+ store any k bytes any palette
36
80
  ```
37
81
 
82
+ 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.
83
+
84
+ | You want | from the image | from a clustering you hold | with a palette you supply |
85
+ |---|---|---|---|
86
+ | a palette (flat RGB) | `getPalette` | `getPaletteFromClustering` | |
87
+ | a palette with each colour's share | `getSwatches` | `getSwatchesFromClustering` | |
88
+ | the image reduced to those colours | `quantize` | `quantizeFromClustering` | `quantizeWithPalette` |
89
+ | palette indices (GIF, PNG-8) | `quantizeToIndices` | `quantizeToIndicesFromClustering` | `quantizeToIndicesWithPalette` |
90
+
91
+ 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.
92
+
93
+ Five words are used throughout:
94
+
95
+ - **clustering**: the tree of an image's colours. It is opaque bytes (a `Clustering`) that you can store next to the image.
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.
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.
100
+
101
+ ## Is it the right tool?
102
+
103
+ **A good fit:**
104
+ - **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
+ - **Several palette sizes for the same image,** or storing one clustering and cutting it later.
106
+ - **The most accurate palette for a given size,** for example as a starting point for vectorisation or flat-colour art.
107
+
108
+ **Probably not the right tool:**
109
+ - **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.
111
+ - **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
+
113
+ ### How it compares
114
+
115
+ 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
+
117
+ | Library | PSNR | Error vs ours | One palette | Palettes at 16/64/128/256 |
118
+ |---|---|---|---|---|
119
+ | **agglomerative-clustering** | **35.72 dB** | **1.00×** | 70 ms | **69 ms** |
120
+ | agglomerative-clustering, `precision: 6` | 35.70 dB | 1.00× | 24 ms | 23 ms |
121
+ | libimagequant (pngquant's engine) | 35.39 dB | 1.08× | 79 ms | 323 ms |
122
+ | image-q Wu | 35.51 dB | 1.05× | 532 ms | 2404 ms |
123
+ | image-q NeuQuant | 34.41 dB | 1.35× | 428 ms | 2562 ms |
124
+ | MMCQ (color-thief's algorithm) | 32.53 dB | 2.08× | 19 ms | 98 ms |
125
+ | image-q RgbQuant | 31.95 dB | 2.38× | 242 ms | 1006 ms |
126
+
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
+
38
131
  ### Cluster once, cut anywhere
39
132
 
40
133
  ```js
@@ -43,54 +136,178 @@ import { getClustering, getPaletteFromClustering, quantizeWithPalette } from 'ag
43
136
  const clustering = await getClustering(imageData); // the expensive step, done once
44
137
 
45
138
  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);
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);
50
143
  };
51
144
  ```
52
145
 
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.
146
+ 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)).
54
147
 
55
- ## How it compares
148
+ ### Swatches, and choosing a palette size
56
149
 
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.
150
+ ```js
151
+ import { getSwatches, getClustering, getSwatchesFromClustering, getClusteringInfo } from 'agglomerative-clustering';
58
152
 
59
- | Library | PSNR | Error vs ours | One palette | Palettes at 16/64/128/256 |
60
- |---|---|---|---|---|
61
- | **agglomerative-clustering** | **35.72 dB** | **1.00×** | 97 ms | **99 ms** |
62
- | agglomerative-clustering, `precision: 6` | 35.70 dB | 1.00× | 31 ms | 31 ms |
63
- | libimagequant (pngquant's engine) | 35.39 dB | 1.08× | 134 ms | 552 ms |
64
- | image-q Wu | 35.51 dB | 1.05× | 740 ms | 3387 ms |
65
- | image-q NeuQuant | 34.41 dB | 1.35× | 609 ms | 3461 ms |
66
- | MMCQ (color-thief's algorithm) | 32.53 dB | 2.08× | 24 ms | 120 ms |
67
- | image-q RgbQuant | 31.95 dB | 2.38× | 385 ms | 1535 ms |
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
+ ### GIFs and palette PNGs
167
+
168
+ `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`.
169
+
170
+ **A GIF** with [gifenc](https://github.com/mattdesl/gifenc), keeping a transparent background:
171
+
172
+ ```js
173
+ import { GIFEncoder } from 'gifenc'; // in plain Node ESM: import gifenc from 'gifenc'; const { GIFEncoder } = gifenc;
174
+ import { quantizeToIndices } from 'agglomerative-clustering';
175
+
176
+ // k counts the transparent entry, so 256 is the most a GIF holds. `image` is { data, format: 'rgba', width, height }.
177
+ const { palette, indices, transparentIndex } = await quantizeToIndices(image, 256, { transparent: true });
178
+ const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
179
+
180
+ const gif = GIFEncoder();
181
+ gif.writeFrame(indices, image.width, image.height, { palette: colors, transparent: transparentIndex !== null, transparentIndex: transparentIndex ?? 0 });
182
+ gif.finish();
183
+ const bytes = gif.bytes();
184
+ ```
185
+
186
+ **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:
187
+
188
+ ```js
189
+ import { encode } from 'fast-png';
190
+
191
+ // Swap the transparent entry with entry 0 (when there is one), in the palette and in the indices.
192
+ const t = transparentIndex ?? 0;
193
+ const swap = (i) => (i === t ? 0 : i === 0 ? t : i);
194
+ const png = encode({
195
+ width: image.width, height: image.height, depth: 8, channels: 1,
196
+ data: indices.map(swap),
197
+ palette: colors.map((_, i) => [...colors[swap(i)], i === 0 && transparentIndex !== null ? 0 : 255]),
198
+ });
199
+ ```
200
+
201
+ 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`.
202
+
203
+ ### Off the main thread
204
+
205
+ 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):
206
+
207
+ ```js
208
+ import { quantize } from 'agglomerative-clustering/worker'; // same API, one shared worker
209
+ const reduced = await quantize(imageData, 16);
210
+ ```
211
+
212
+ 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:
213
+
214
+ ```js
215
+ import { createWorker } from 'agglomerative-clustering/worker';
216
+
217
+ const worker = createWorker();
218
+ const handle = await worker.cluster(imageData, { precision: 6 });
219
+
220
+ let controller = null;
221
+ slider.oninput = async () => {
222
+ controller?.abort(); // a size the slider has already moved past isn't worth finishing
223
+ controller = new AbortController();
224
+ try {
225
+ ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true, signal: controller.signal }), 0, 0);
226
+ } catch (error) {
227
+ if (error.name !== 'AbortError') {throw error;}
228
+ }
229
+ };
230
+ ```
231
+
232
+ Calls to one worker run in order, and re-mapping a large image takes a while (about 0.3 s at 10 megapixels), 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.
233
+
234
+ 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 and esbuild, Parcel 2 works with its `packageExports` option on, and for Next.js see [Next.js](#nextjs). In Node an idle worker never keeps the process alive. See the [worker reference](#worker-entry).
235
+
236
+ ### Using the output
237
+
238
+ 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`):
239
+
240
+ ```js
241
+ // [[r, g, b], …]: what gifenc, fast-png, color-thief and libimagequant use
242
+ const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
243
+
244
+ // A CSS colour, and a 0xRRGGBB number
245
+ const css = (i) => `rgb(${palette[3 * i]} ${palette[3 * i + 1]} ${palette[3 * i + 2]})`;
246
+ const hex = (i) => (palette[3 * i] << 16) | (palette[3 * i + 1] << 8) | palette[3 * i + 2];
247
+
248
+ // 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)
249
+ const swatches = Array.from(shares, (share, i) => ({ color: css(i), share }));
250
+ ```
251
+
252
+ **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.
253
+
254
+ ```js
255
+ // A palette and its weights, heaviest first
256
+ const order = Array.from(weights.keys()).sort((a, b) => weights[b] - weights[a]); // old index of the 1st, 2nd, … entry
257
+ const rankedColors = order.map((i) => colors[i]);
258
+ const rankedShares = order.map((i) => shares[i]);
259
+
260
+ // An indexed image, heaviest first: count how many pixels use each entry (that is what "heaviest" means for the image),
261
+ // sort, and renumber the indices
262
+ const used = new Uint32Array(palette.length / 3);
263
+ for (const index of indices) {used[index]++;}
264
+ const byUse = Array.from(used.keys()).sort((a, b) => used[b] - used[a]);
265
+ const rank = new Uint32Array(used.length);
266
+ byUse.forEach((old, position) => {rank[old] = position;});
267
+ const rankedPalette = byUse.map((old) => colors[old]);
268
+ const rankedIndices = indices.map((index) => rank[index]); // same typed-array type as `indices`
269
+ const rankedTransparentIndex = transparentIndex === null ? null : rank[transparentIndex];
270
+ ```
271
+
272
+ ## Reference
273
+
274
+ ### Input and output
275
+ Every function that takes an image accepts:
276
+
277
+ ```ts
278
+ Uint8Array // raw RGBA bytes
279
+ ImageData // from a canvas: always RGBA, width included
280
+ { data: Uint8Array | Uint8ClampedArray, // explicit format, for RGB data or clamped arrays
281
+ format: 'rgb' | 'rgba',
282
+ width?: number, height?: number } // optional: used for dithering, copied to results
283
+ ```
284
+
285
+ `width` and `height` must be whole numbers, and when both are given they must account for exactly the pixels in `data`.
286
+
287
+ > **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()`).
288
+
289
+ > **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).
68
290
 
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`.
291
+ 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.
70
292
 
71
- ## Options
293
+ ### Options
72
294
 
73
295
  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.
74
296
 
75
297
  | Option | Applies to | Values | What it does |
76
298
  |---|---|---|---|
77
299
  | `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. |
300
+ | `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". |
301
+ | `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. |
302
+ | `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. |
303
+ | `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. |
304
+ | `signal` | any call with an image | an `AbortSignal` | Cancels the call; see "Cancelling and progress". |
305
+ | `onProgress` | clustering | `(fraction) => void` | Reports 0 to 1 as the clustering runs; see "Cancelling and progress". |
306
+ | `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". |
82
307
 
83
- "Clustering" means `getClustering` and `getPalette`, "mapping" means `quantizeWithClustering` and `quantizeWithPalette`, and `quantize` takes both.
308
+ "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.
84
309
 
85
- Measured on the Kodak photos:
86
-
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 |
310
+ 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.
94
311
 
95
312
  ```js
96
313
  // Perceptual palettes for a photo, quickly
@@ -103,98 +320,297 @@ const retro = await quantize(imageData, 8, { dither: true });
103
320
  const out = await quantize(rgbaBytes, 32, { dither: 0.8, width: 640 });
104
321
  ```
105
322
 
106
- ## When to use it, and when not
323
+ #### Choosing a colour space
107
324
 
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.
325
+ `'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:
112
326
 
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.
327
+ | You are making | Colours | Use | What the numbers say |
328
+ |---|---|---|---|
329
+ | 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. |
330
+ | 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). |
331
+ | Dithered GIF, retro look | 8–64 | `'rgb'` | Looks closer from a distance: blurred ΔE 2.59 against 2.86 at 16 colours. |
332
+ | Flat graphics, logos, pixel art | 8–32 | either | About equal. |
333
+ | 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). |
334
+ | Noisy or very varied images | any | `'oklab'` | Mean ΔE 7.0 against 7.9 at 64 colours (one synthetic image). |
117
335
 
118
- ## Usage
336
+ `'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.
119
337
 
120
- ### Browser (Canvas)
338
+ How the options trade speed and quality, measured on the Kodak photos:
121
339
 
122
- ```js
123
- import { quantize } from 'agglomerative-clustering';
340
+ | Setting | 16 colours ΔE2000 | 256 colours ΔE2000 | One 64-colour palette |
341
+ |---|---|---|---|
342
+ | default (`rgb`, exact) | **4.31** | 1.67 | 70 ms |
343
+ | `precision: 6` | **4.29** | 1.68 | 24 ms |
344
+ | `colorSpace: 'oklab'` | 4.46 | **1.60** | 78 ms |
345
+ | `colorSpace: 'oklab', precision: 6` | 4.44 | 1.61 | 30 ms |
346
+ | libimagequant, for reference | 4.38 | 1.61 | 79 ms |
124
347
 
125
- const ctx = canvas.getContext('2d');
126
- const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
348
+ #### Transparency
349
+
350
+ Three things in this library are about alpha, and they act at different stages:
351
+
352
+ | | What it is | Stage | Effect |
353
+ |---|---|---|---|
354
+ | `'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. |
355
+ | `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. |
356
+ | `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`. |
127
357
 
128
- // ImageData in, ImageData out
129
- const result = await quantize(imageData, 16, { dither: true });
130
- ctx.putImageData(result, 0, 0);
358
+ 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.
359
+
360
+ 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.
361
+
362
+ ### Palette and Clustering
363
+ 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:
364
+
365
+ - **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.
366
+ - **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.
367
+ - **`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.
368
+ - **A clustering is checked before it is used.** Clusterings carry a checksum, so stored bytes that came back damaged (truncated, a changed byte, a lossy base64 round trip) are reported as `invalid-clustering` rather than cut into a wrong palette.
369
+
370
+ ```js
371
+ import { Clustering, Palette, getPaletteFromClustering } from 'agglomerative-clustering';
372
+
373
+ const stored = new Uint8Array(await db.get('clustering')); // what storage gives back: plain bytes
374
+ const clustering = new Clustering(stored); // typed again, and checked
375
+ const palette = await getPaletteFromClustering(clustering, 8);
376
+ palette instanceof Palette; // true
377
+ palette.colorSpace; // 'rgb' or 'oklab', as it was clustered
378
+ palette.slice(0, 3) instanceof Palette; // false: slice, subarray and clones are plain bytes
131
379
  ```
132
380
 
133
- ### Node.js (with sharp)
381
+ `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) [ … ]`.
382
+
383
+ **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:
134
384
 
135
385
  ```js
136
- import { quantize } from 'agglomerative-clustering';
137
- import sharp from 'sharp';
386
+ await db.put('palette', { bytes: Array.from(palette), colorSpace: palette.colorSpace });
387
+ const { bytes, colorSpace } = await db.get('palette');
388
+ const restored = new Palette(bytes, colorSpace); // maps exactly as the palette you stored
389
+ ```
138
390
 
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 };
391
+ A clustering needs none of this: its colour space is in its bytes.
141
392
 
142
- const { data: output } = await quantize(image, 32, { precision: 6, dither: true });
393
+ ### Cancelling and progress
394
+ Every function that takes an image accepts `signal`; the ones that cluster (`getClustering`, `getPalette`, `getSwatches`, `quantize`, `quantizeToIndices`) also accept `onProgress`:
143
395
 
144
- await sharp(Buffer.from(output), { raw: { width: info.width, height: info.height, channels: 4 } }).toFile('photo-32.png');
396
+ ```js
397
+ const controller = new AbortController();
398
+ const clustering = await getClustering(image, {
399
+ signal: controller.signal, // controller.abort() cancels it
400
+ onProgress: (fraction) => bar.value = fraction, // 0 to 1
401
+ });
145
402
  ```
146
403
 
147
- ## Input types
404
+ - **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.
405
+ - **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: check `error.name === 'AbortError'`. An already aborted signal does no work.
406
+ - **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`.
407
+ - **Progress** is approximate, never goes backwards, and ends at exactly 1.
408
+ - **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.
148
409
 
149
- Every function that takes an image accepts:
410
+ ### Errors
150
411
 
151
- ```ts
152
- Uint8Array // raw RGBA bytes
153
- ImageData // from a canvas: always RGBA, width included
154
- { data: Uint8Array | Uint8ClampedArray, // explicit format, for RGB data or clamped arrays
155
- format: 'rgb' | 'rgba',
156
- width?: number, height?: number } // optional: used for dithering, copied to results
412
+ 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`).
413
+
414
+ 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.
415
+
416
+ | `code` | When |
417
+ | --- | --- |
418
+ | `invalid-argument` | A bad image, `k`, option or palette. |
419
+ | `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). |
420
+ | `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`). |
421
+ | `out-of-memory` | The WebAssembly module couldn't allocate. |
422
+ | `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. |
423
+ | `worker-terminated`, `worker-failed`, `invalid-handle` | Worker entry only: the worker was stopped or failed to start, or a handle was released. |
424
+
425
+ ```js
426
+ try {
427
+ await getPaletteFromClustering(stored, 16);
428
+ } catch (error) {
429
+ const code = error instanceof Error && 'code' in error ? error.code : undefined; // also compiles in strict TypeScript
430
+ if (code === 'unsupported-version' || code === 'invalid-clustering') { /* cluster the image again */ }
431
+ else { throw error; }
432
+ }
157
433
  ```
158
434
 
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.
435
+ 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`.
436
+
437
+ ### Worker entry
438
+ `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:
439
+
440
+ - **`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.
441
+ - **`terminate()`** stops the worker and rejects the calls still waiting.
442
+
443
+ 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.
444
+
445
+ ### TypeScript
446
+ 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`.
447
+
448
+ 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`.
449
+
450
+ 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`.
160
451
 
161
452
  ## API
162
453
 
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.
454
+ ### `getClustering(image, options?): Promise<Clustering>`
455
+ Builds the colour hierarchy for an image. Pass the result to `getPaletteFromClustering` or `quantizeFromClustering` to get any number of palettes without clustering again.
456
+
457
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `signal`, `onProgress`.
458
+
459
+ ### `getPaletteFromClustering(clustering, k): Promise<Palette>`
460
+ 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.
461
+
462
+ ### `getPalette(image, k, options?): Promise<Palette>`
463
+ `getClustering` followed by `getPaletteFromClustering`.
464
+
465
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `signal`, `onProgress`.
466
+
467
+ ### `getSwatches(image, k, options?): Promise<Swatches>`
468
+ 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:
469
+ - `palette` is flat RGB bytes in split order (what `getPaletteFromClustering` gives).
470
+ - `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.
471
+ - `shares` are the weights divided by their total, so they sum to 1.
472
+
473
+ 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`.
474
+
475
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `signal`, `onProgress`.
476
+
477
+ ### `getSwatchesFromClustering(clustering, k): Promise<Swatches>`
478
+ 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.
479
+
480
+ ### `getClusteringInfo(clustering): Promise<ClusteringInfo>`
481
+ What a clustering holds: `{ formatVersion, colorSpace, precision, transparent, maxColors, totalWeight, mse, explained }`.
482
+
483
+ - `formatVersion`: the format of its bytes (compare it with the exported `formatVersion`).
484
+ - `transparent`: the alpha cutoff it was made with, or `false`. `quantizeToIndicesFromClustering` uses it by default.
485
+ - `maxColors`: the largest palette it can be cut to.
486
+ - `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%.
487
+ - `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.
488
+
489
+ 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.
490
+
491
+ ### `quantize(image, k, options?): Promise<the type of image>`
492
+ Reduces the image to at most `k` colours.
493
+
494
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `dither`, `width`, `signal`, `onProgress`.
495
+
496
+ ### `quantizeFromClustering(image, clustering, k, options?): Promise<the type of image>`
497
+ Quantizes using a clustering you already have.
498
+
499
+ Options: `colorSpace` (defaults to the clustering's), `dither`, `width`, `signal`.
500
+
501
+ ### `quantizeWithPalette(image, palette, options?): Promise<the type of image>`
502
+ 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.
503
+
504
+ Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signal`.
505
+
506
+ ### `quantizeToIndices(image, k, options?): Promise<IndexedImage>`
507
+ Like `quantize`, but returns each pixel's palette index rather than its colour: what palette PNGs, GIFs, pixel art and pattern generators need.
508
+
509
+ Options: `colorSpace`, `precision`, `alpha`, `transparent`, `dither`, `width`, `signal`, `onProgress`.
510
+
511
+ The result is `{ palette, colors, indices, indexBits, transparentIndex }`, plus `width` and `height` when the input has them:
512
+ - `palette`: the flat RGB bytes an encoder wants, including the transparent entry if there is one.
513
+ - `colors`: the same without the transparent entry, to pass to `quantizeToIndicesWithPalette` for more images with these colours.
514
+ - `indices`: one per pixel, a `Uint8Array` for up to 256 entries, `Uint16Array` up to 65536, else `Uint32Array`; `indexBits` (8, 16 or 32) says which.
515
+ - `transparentIndex`: the transparent entry's index, or `null`.
516
+
517
+ 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).
165
518
 
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.
519
+ ```js
520
+ const { palette, colors, indices, transparentIndex } = await quantizeToIndices(imageData, 256, { transparent: true });
521
+ ```
522
+
523
+ ### `quantizeToIndicesFromClustering(image, clustering, k, options?): Promise<IndexedImage>`
524
+ 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.
525
+
526
+ Options: `colorSpace` (defaults to the clustering's), `dither`, `width`, `signal`, `transparent`.
527
+
528
+ ### `quantizeToIndicesWithPalette(image, palette, options?): Promise<IndexedImage>`
529
+ 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.
530
+
531
+ Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signal`, `transparent`.
532
+
533
+ ### `init(options?): Promise<void>`
534
+ 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).
168
535
 
169
- ### `getPalette(image, k, options?): Promise<Uint8Array>`
170
- `getClustering` followed by `getPaletteFromClustering`. Options: `colorSpace`, `precision`, `alpha`.
536
+ ### `version: string` and `formatVersion: number`
537
+ `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: 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`.
171
538
 
172
- ### `quantize(image, k, options?): Promise<Uint8Array | ImageData | RawImage>`
173
- Reduces the image to at most `k` colours. Options: `colorSpace`, `precision`, `alpha`, `dither`, `width`.
539
+ ## Running it
174
540
 
175
- ### `quantizeWithClustering(image, clustering, k, options?)`
176
- Quantizes using a clustering you already have. Options: `colorSpace` (defaults to the clustering's), `dither`, `width`.
541
+ ### Where it runs
542
+
543
+ 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.
544
+
545
+ 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.
546
+
547
+ ### Loading the WebAssembly module
548
+ 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):
549
+
550
+ ```js
551
+ await init({ wasm: 'https://cdn.example.com/clustering.wasm' }); // a URL or path string, or a URL
552
+ await init({ wasm: await (await fetch(url)).arrayBuffer() }); // the bytes
553
+ await init({ wasm: wasmModule }); // a compiled WebAssembly.Module
554
+ ```
177
555
 
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`.
556
+ 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.
180
557
 
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.
558
+ ### Next.js
183
559
 
184
- Invalid inputs, palette sizes and options (including unknown option names) are rejected with a descriptive error.
560
+ Checked with Next.js 16, under Turbopack and webpack, in production builds:
185
561
 
186
- ## Migrating from 1.x
562
+ - **Client components** need nothing: the main entry and the worker entry both work as they are.
563
+ - **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:
187
564
 
188
- 2.0 keeps the same functions and defaults (`rgb`, no dithering, exact `precision`). What changes:
565
+ ```js
566
+ // next.config.js
567
+ export default { serverExternalPackages: ['agglomerative-clustering'] };
568
+ ```
569
+ - **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):
189
570
 
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.
571
+ ```ts
572
+ import { init, getSwatches } from 'agglomerative-clustering';
573
+ // @ts-expect-error -- `?module` gives a compiled WebAssembly.Module
574
+ import wasm from '../../../node_modules/agglomerative-clustering/dist/clustering.wasm?module';
196
575
 
197
- ## Demo
576
+ export const runtime = 'edge';
577
+
578
+ export async function POST(request: Request) {
579
+ await init({ wasm }); // loads once; later calls return at once
580
+ // … decode the upload to pixels, then getSwatches(pixels, 8)
581
+ }
582
+ ```
583
+
584
+ ### Performance and limits
585
+
586
+ **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.
587
+
588
+ **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.
589
+
590
+ ### Troubleshooting
591
+
592
+ | What you see | Why | What to do |
593
+ |---|---|---|
594
+ | `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". |
595
+ | `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). |
596
+ | 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()`). |
597
+ | `invalid-argument` for a canvas, `Blob` or `ImageBitmap` | Those aren't pixels. | Draw to a canvas and pass `getImageData()`. |
598
+ | 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. |
599
+ | `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. |
600
+ | 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"). |
601
+ | `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. |
602
+ | `out-of-memory` | An image with very many distinct colours. | Use `precision: 6`, or a smaller image. |
603
+ | 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. |
604
+ | TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
605
+
606
+ ## More
607
+
608
+ - **[Migrating](docs/migrating.md)** from 2.x (and 1.x) to the current version, and the [CHANGELOG](CHANGELOG.md) for every release.
609
+ - **[Stability and versioning](docs/stability.md)**: what won't change within a major version.
610
+ - **[How it works](docs/how-it-works.md)**: the algorithm, and the architecture notes for contributors in [CLAUDE.md](CLAUDE.md).
611
+ - **[Roadmap](docs/ROADMAP.md)**: what is planned and what was tried and dropped.
612
+
613
+ ### Demo
198
614
 
199
615
  ```sh
200
616
  git clone https://github.com/RohanFredriksson/agglomerative-clustering && cd agglomerative-clustering
@@ -204,16 +620,6 @@ npm run demo # then open http://localhost:8080/demo/
204
620
 
205
621
  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
622
 
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
623
  ## License
218
624
 
219
625
  MIT © Rohan Fredriksson