agglomerative-clustering 3.2.0 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -21
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +41 -17
- package/dist/index.d.cts +30 -8
- package/dist/index.d.ts +30 -8
- package/dist/index.mjs +38 -15
- package/dist/shared.cjs +103 -9
- package/dist/shared.mjs +101 -8
- package/dist/worker-thread.mjs +21 -5
- package/dist/worker.cjs +82 -26
- package/dist/worker.d.cts +22 -4
- package/dist/worker.d.ts +22 -4
- package/dist/worker.mjs +79 -24
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
|
|
|
16
16
|
- **Transparency-aware.** A logo's transparent background never ends up in its palette. GIF and palette PNG output are built in.
|
|
17
17
|
- **Off the main thread.** `agglomerative-clustering/worker` runs the same API in a Web Worker or Node worker thread.
|
|
18
18
|
- **Accurate and fast.** The lowest average error of the six JavaScript quantizers we benchmarked, at about the speed of libimagequant ([benchmarks](#benchmarks)).
|
|
19
|
-
- **Small and portable.**
|
|
19
|
+
- **Small and portable.** About 127 KB of WebAssembly (52 KB gzipped), Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
|
|
20
20
|
|
|
21
21
|
## Install
|
|
22
22
|
|
|
@@ -24,7 +24,7 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
|
|
|
24
24
|
npm install agglomerative-clustering
|
|
25
25
|
```
|
|
26
26
|
|
|
27
|
-
Upgrading
|
|
27
|
+
Upgrading? See [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md). From 3.3, three functions have new names, and the old ones keep working until 4.0. From 2.x, one function was renamed, and palettes and images are the same as 2.0's, with one documented exception.
|
|
28
28
|
|
|
29
29
|
It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (Chrome and Edge 91, Firefox 89, Safari 16.4). Deno, Bun, Cloudflare Workers, serverless functions, Electron and browser extensions work too: see [Environments](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).
|
|
30
30
|
|
|
@@ -34,12 +34,12 @@ It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (Chrome
|
|
|
34
34
|
|
|
35
35
|
```js
|
|
36
36
|
import sharp from 'sharp';
|
|
37
|
-
import {
|
|
37
|
+
import { buildPalette, quantize } from 'agglomerative-clustering';
|
|
38
38
|
|
|
39
39
|
const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
40
40
|
const image = { data, format: 'rgba', width: info.width }; // in TypeScript: format: 'rgba' as const
|
|
41
41
|
|
|
42
|
-
const palette = await
|
|
42
|
+
const palette = await buildPalette(image, 8); // flat bytes: [r, g, b, r, g, b, ...]
|
|
43
43
|
const reduced = await quantize(image, 16, { dither: true }); // the image, in 16 colours
|
|
44
44
|
|
|
45
45
|
await sharp(Buffer.from(reduced.data), { raw: { width: info.width, height: info.height, channels: 4 } }).toFile('photo-16.png');
|
|
@@ -59,9 +59,9 @@ ctx.putImageData(await quantize(imageData, 16, { dither: true }), 0, 0); // Im
|
|
|
59
59
|
**Swatches, with each colour's share of the image:**
|
|
60
60
|
|
|
61
61
|
```js
|
|
62
|
-
import {
|
|
62
|
+
import { buildSwatches } from 'agglomerative-clustering';
|
|
63
63
|
|
|
64
|
-
const { palette, shares } = await
|
|
64
|
+
const { palette, shares } = await buildSwatches(imageData, 6); // six colours; the shares sum to 1
|
|
65
65
|
shares.forEach((share, i) => {
|
|
66
66
|
console.log(`rgb(${palette[3 * i]} ${palette[3 * i + 1]} ${palette[3 * i + 2]})`, `${(share * 100).toFixed(1)}%`);
|
|
67
67
|
});
|
|
@@ -70,36 +70,43 @@ shares.forEach((share, i) => {
|
|
|
70
70
|
**A colour-count slider:** cluster once, then cut and map as often as you like.
|
|
71
71
|
|
|
72
72
|
```js
|
|
73
|
-
import {
|
|
73
|
+
import { buildClustering, quantizeWithPalette } from 'agglomerative-clustering';
|
|
74
74
|
|
|
75
|
-
const clustering = await
|
|
75
|
+
const clustering = await buildClustering(imageData); // the expensive step, done once
|
|
76
76
|
|
|
77
77
|
slider.oninput = async () => {
|
|
78
|
-
const palette = await
|
|
79
|
-
ctx.putImageData(await quantizeWithPalette(imageData, palette), 0, 0);
|
|
78
|
+
const palette = await clustering.getPalette(Number(slider.value)); // ~0.4 ms for any k
|
|
79
|
+
ctx.putImageData(await quantizeWithPalette(imageData, palette), 0, 0); // ~5-12 ms at 768×512
|
|
80
80
|
};
|
|
81
81
|
```
|
|
82
82
|
|
|
83
|
-
Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use the same
|
|
83
|
+
Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
|
|
84
84
|
|
|
85
85
|
## How it works
|
|
86
86
|
|
|
87
87
|
```
|
|
88
|
-
image ──▶
|
|
89
|
-
once, ~70 ms
|
|
90
|
-
|
|
88
|
+
image ──▶ buildClustering ──▶ a clustering ──▶ cut to k colours ──▶ a palette ──▶ map the pixels ──▶ reduced image
|
|
89
|
+
once, ~70 ms bytes you can under 1 ms, flat RGB a few ms,
|
|
90
|
+
store any k bytes any palette
|
|
91
91
|
```
|
|
92
92
|
|
|
93
|
-
The one-shot functions (`
|
|
93
|
+
The one-shot functions (`buildPalette`, `quantize`, …) do every step for you. To try many palette sizes, call `buildClustering` once and cut it as often as you like.
|
|
94
94
|
|
|
95
|
-
| You want | from the image | from a clustering you hold | with a palette you supply |
|
|
95
|
+
| You want | from the image | from a clustering you hold¹ | with a palette you supply |
|
|
96
96
|
|---|---|---|---|
|
|
97
|
-
| a palette (flat RGB) | `
|
|
98
|
-
| a palette with each colour's share | `
|
|
99
|
-
| the image reduced to those colours | `quantize` | `quantizeFromClustering` | `quantizeWithPalette` |
|
|
100
|
-
| palette indices (GIF, PNG-8) | `quantizeToIndices` | `quantizeToIndicesFromClustering` | `quantizeToIndicesWithPalette` |
|
|
97
|
+
| a palette (flat RGB) | `buildPalette` | `clustering.getPalette(k)` (`getPaletteFromClustering`) | |
|
|
98
|
+
| a palette with each colour's share | `buildSwatches` | `clustering.getSwatches(k)` (`getSwatchesFromClustering`) | |
|
|
99
|
+
| the image reduced to those colours | `quantize` | `clustering.quantize(image, k)` (`quantizeFromClustering`) | `quantizeWithPalette` |
|
|
100
|
+
| palette indices (GIF, PNG-8) | `quantizeToIndices` | `clustering.quantizeToIndices(image, k)` (`quantizeToIndicesFromClustering`) | `quantizeToIndicesWithPalette` |
|
|
101
|
+
| its error curve, for choosing a palette size | | `clustering.getClusteringInfo()` (`getClusteringInfo`) | |
|
|
101
102
|
|
|
102
|
-
|
|
103
|
+
A clustering you hold has **methods** that take the colours from it, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `buildClustering` builds a clustering, and `init` loads the WebAssembly module (optional). Most code only needs the first column.
|
|
104
|
+
|
|
105
|
+
The verb says how much work a call does. `build…` clusters an image (tens of milliseconds for a photo). `get…` reads or cuts what a clustering or a worker handle already holds (well under a millisecond). `quantize…` maps pixels. So `buildPalette(image, k)` and `clustering.getPalette(k)` give the same kind of result from different starting points. The `build…` names arrived in 3.4.0; [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md) has the old ones.
|
|
106
|
+
|
|
107
|
+
**Methods or functions?** On the main thread, or in a Node script, use the methods: they are the shortest way to cut one clustering many times. **In a worker, use a handle** (`createWorker().cluster(image)`, below) or the worker entry's function forms: the methods always run on the thread that calls them, with the main entry, and reject with `wasm-load-failed` where only the worker entry is imported.
|
|
108
|
+
|
|
109
|
+
¹ Each method has a function form, in brackets, that does the same. The cuts take the clustering first (`getPaletteFromClustering(clustering, k)`); the mapping functions take the image first and the clustering second (`quantizeFromClustering(image, clustering, k)`). See [Clustering methods](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#clustering-methods).
|
|
103
110
|
|
|
104
111
|
Palettes come in **split order**: the palette for `k + 1` is the one for `k` with one colour split in two, so entries keep their place as `k` grows (they are not sorted by share). The options are `precision` (6 is about 3× faster at practically the same quality), `colorSpace` (`'rgb'` or `'oklab'`), `alpha`, `transparent`, `dither` (Floyd–Steinberg, Atkinson, or ordered for animation, which keeps still areas still), `width`, `signal` and `onProgress`: see the [API reference](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md).
|
|
105
112
|
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|
package/dist/index.cjs
CHANGED
|
@@ -21,6 +21,7 @@ Object.defineProperty(exports, "alphaModes", {
|
|
|
21
21
|
return _shared.alphaModes;
|
|
22
22
|
}
|
|
23
23
|
});
|
|
24
|
+
exports.buildSwatches = exports.buildPalette = exports.buildClustering = void 0;
|
|
24
25
|
Object.defineProperty(exports, "colorSpaces", {
|
|
25
26
|
enumerable: true,
|
|
26
27
|
get: function () {
|
|
@@ -553,7 +554,7 @@ const checkSize = (pixels, size, name, argument) => {
|
|
|
553
554
|
};
|
|
554
555
|
const load = image => {
|
|
555
556
|
if ((0, _shared.isClustering)(image) || (0, _shared.isPalette)(image)) {
|
|
556
|
-
const what = (0, _shared.isClustering)(image) ? 'a clustering (from
|
|
557
|
+
const what = (0, _shared.isClustering)(image) ? 'a clustering (from buildClustering)' : 'a palette';
|
|
557
558
|
const fix = (0, _shared.isClustering)(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
|
|
558
559
|
throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
|
|
559
560
|
}
|
|
@@ -712,7 +713,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
712
713
|
options = (0, _shared.snapshot)(options);
|
|
713
714
|
for (const key of Object.keys(options)) {
|
|
714
715
|
if (!allowed.includes(key)) {
|
|
715
|
-
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
|
|
716
|
+
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : key === 'onProgress' && allowed.includes('signal') ? ' The functions that only map pixels take just signal: they finish in milliseconds, with no progress to report.' : '';
|
|
716
717
|
throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
|
|
717
718
|
}
|
|
718
719
|
}
|
|
@@ -963,9 +964,12 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
|
963
964
|
|
|
964
965
|
// The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
|
|
965
966
|
// anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
|
|
967
|
+
// `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
|
|
968
|
+
// the method form of mapping.
|
|
966
969
|
const noOptions = (name, extra) => {
|
|
967
970
|
if (extra.some(value => value !== undefined)) {
|
|
968
|
-
|
|
971
|
+
const alternative = name.startsWith('clustering.') ? 'clustering.quantize' : 'quantizeFromClustering';
|
|
972
|
+
throw (0, _shared.fail)('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use ${alternative}.`, 'options');
|
|
969
973
|
}
|
|
970
974
|
};
|
|
971
975
|
|
|
@@ -973,7 +977,7 @@ const noOptions = (name, extra) => {
|
|
|
973
977
|
// already loaded, `Module || await acquire()` doesn't wait, and the work up to the first slice of a long clustering
|
|
974
978
|
// happens before the call returns.
|
|
975
979
|
|
|
976
|
-
const
|
|
980
|
+
const buildClustering = async (image, options) => {
|
|
977
981
|
image = load(image);
|
|
978
982
|
const o = parseOptions(options, clusterOptions, image);
|
|
979
983
|
const wasm = Module || (await acquire());
|
|
@@ -985,8 +989,10 @@ const getClustering = async (image, options) => {
|
|
|
985
989
|
}
|
|
986
990
|
return (0, _shared.markClustering)(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
|
|
987
991
|
};
|
|
988
|
-
|
|
989
|
-
|
|
992
|
+
/** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
|
|
993
|
+
exports.buildClustering = buildClustering;
|
|
994
|
+
const getClustering = exports.getClustering = buildClustering;
|
|
995
|
+
const buildPalette = async (image, k, options) => {
|
|
990
996
|
image = load(image);
|
|
991
997
|
k = check(k);
|
|
992
998
|
const o = parseOptions(options, clusterOptions, image);
|
|
@@ -1001,15 +1007,20 @@ const getPalette = async (image, k, options) => {
|
|
|
1001
1007
|
}
|
|
1002
1008
|
return (0, _shared.markPalette)(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), (0, _shared.colorSpaceName)(o.colorSpace));
|
|
1003
1009
|
};
|
|
1004
|
-
|
|
1005
|
-
|
|
1010
|
+
/** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
|
|
1011
|
+
exports.buildPalette = buildPalette;
|
|
1012
|
+
const getPalette = exports.getPalette = buildPalette;
|
|
1013
|
+
|
|
1014
|
+
// The cuts take the name they were called by, for their messages: the functions below, or the methods on Clustering.
|
|
1015
|
+
const cutPalette = async (name, clustering, k, extra) => {
|
|
1006
1016
|
const header = (0, _shared.readHeader)(clustering);
|
|
1007
1017
|
k = check(k);
|
|
1008
|
-
noOptions(
|
|
1018
|
+
noOptions(name, extra);
|
|
1009
1019
|
clustering = held(clustering);
|
|
1010
1020
|
const wasm = Module || (await acquire());
|
|
1011
1021
|
return (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
|
|
1012
1022
|
};
|
|
1023
|
+
const getPaletteFromClustering = (clustering, k, ...extra) => cutPalette('getPaletteFromClustering', clustering, k, extra);
|
|
1013
1024
|
|
|
1014
1025
|
// The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
|
|
1015
1026
|
exports.getPaletteFromClustering = getPaletteFromClustering;
|
|
@@ -1032,10 +1043,10 @@ const needsWeights = header => {
|
|
|
1032
1043
|
// A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
|
|
1033
1044
|
// arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
|
|
1034
1045
|
// proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
|
|
1035
|
-
const
|
|
1046
|
+
const cutSwatches = async (name, clustering, k, extra) => {
|
|
1036
1047
|
const header = (0, _shared.readHeader)(clustering);
|
|
1037
1048
|
k = check(k);
|
|
1038
|
-
noOptions(
|
|
1049
|
+
noOptions(name, extra);
|
|
1039
1050
|
needsWeights(header);
|
|
1040
1051
|
clustering = held(clustering);
|
|
1041
1052
|
const wasm = Module || (await acquire());
|
|
@@ -1057,23 +1068,26 @@ const getSwatchesFromClustering = async (clustering, k, ...extra) => {
|
|
|
1057
1068
|
shares
|
|
1058
1069
|
};
|
|
1059
1070
|
};
|
|
1071
|
+
const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getSwatchesFromClustering', clustering, k, extra);
|
|
1060
1072
|
|
|
1061
1073
|
// The same for an image: clusters it, then cuts, like getPalette.
|
|
1062
1074
|
exports.getSwatchesFromClustering = getSwatchesFromClustering;
|
|
1063
|
-
const
|
|
1075
|
+
const buildSwatches = async (image, k, options) => {
|
|
1064
1076
|
// Arguments are checked in the order they are given (image, then k, then options), as in every other function.
|
|
1065
1077
|
load(image);
|
|
1066
1078
|
k = check(k);
|
|
1067
|
-
return getSwatchesFromClustering(await
|
|
1079
|
+
return getSwatchesFromClustering(await buildClustering(image, options), k);
|
|
1068
1080
|
};
|
|
1081
|
+
/** @deprecated The same function as buildSwatches, its name before 3.4.0. Removed in 4.0. */
|
|
1082
|
+
exports.buildSwatches = buildSwatches;
|
|
1083
|
+
const getSwatches = exports.getSwatches = buildSwatches;
|
|
1069
1084
|
|
|
1070
1085
|
// What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
|
|
1071
1086
|
// squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
|
|
1072
1087
|
// weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
|
|
1073
|
-
|
|
1074
|
-
const getClusteringInfo = async (clustering, ...extra) => {
|
|
1088
|
+
const readInfo = async (name, clustering, extra) => {
|
|
1075
1089
|
const header = (0, _shared.readHeader)(clustering);
|
|
1076
|
-
noOptions(
|
|
1090
|
+
noOptions(name, extra);
|
|
1077
1091
|
needsWeights(header);
|
|
1078
1092
|
const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
|
|
1079
1093
|
const info = {
|
|
@@ -1114,6 +1128,7 @@ const getClusteringInfo = async (clustering, ...extra) => {
|
|
|
1114
1128
|
}
|
|
1115
1129
|
return info;
|
|
1116
1130
|
};
|
|
1131
|
+
const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
|
|
1117
1132
|
exports.getClusteringInfo = getClusteringInfo;
|
|
1118
1133
|
const quantize = async (image, k, options) => {
|
|
1119
1134
|
const wrap = getWrapper(image);
|
|
@@ -1208,4 +1223,13 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1208
1223
|
const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
|
|
1209
1224
|
return result;
|
|
1210
1225
|
};
|
|
1211
|
-
|
|
1226
|
+
|
|
1227
|
+
// The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
|
|
1228
|
+
exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
|
|
1229
|
+
(0, _shared.setEngine)({
|
|
1230
|
+
cut: cutPalette,
|
|
1231
|
+
cutSwatches,
|
|
1232
|
+
info: readInfo,
|
|
1233
|
+
quantizeFromClustering,
|
|
1234
|
+
quantizeToIndicesFromClustering
|
|
1235
|
+
});
|
package/dist/index.d.cts
CHANGED
|
@@ -125,12 +125,18 @@ export class Palette extends Uint8Array {
|
|
|
125
125
|
}
|
|
126
126
|
|
|
127
127
|
/**
|
|
128
|
-
* The bytes of a clustering, as `
|
|
128
|
+
* The bytes of a clustering, as `buildClustering` returns them: an opaque `Uint8Array` (tagged, like `Palette`) that you can
|
|
129
129
|
* store (a file, IndexedDB, next to the image) and cut to a palette of any size later. It is a type of its own, so a
|
|
130
130
|
* clustering can't be passed where a palette goes (or the other way round): TypeScript says so, and at run time a
|
|
131
131
|
* `Clustering` given as a palette is rejected, with no guessing about its bytes. Stored bytes come back as a plain
|
|
132
132
|
* `Uint8Array`, which functions still accept at run time; `new Clustering(bytes)` gives them the type back (TypeScript
|
|
133
133
|
* wants it) and checks they are a clustering.
|
|
134
|
+
*
|
|
135
|
+
* It has methods for the cluster-once workflow: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and
|
|
136
|
+
* so on. They run on the calling thread with the main entry, so in a worker-only app they compile but reject with
|
|
137
|
+
* `wasm-load-failed`. They exist only on values from this library or `new Clustering(bytes)`: slices and clones are plain
|
|
138
|
+
* bytes, and a cast (`bytes as Clustering`) or a `structuredClone` keeps the type without them: wrap those with
|
|
139
|
+
* `new Clustering(bytes)`.
|
|
134
140
|
*/
|
|
135
141
|
export class Clustering extends Uint8Array {
|
|
136
142
|
/**
|
|
@@ -141,6 +147,16 @@ export class Clustering extends Uint8Array {
|
|
|
141
147
|
constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
|
|
142
148
|
/** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
|
|
143
149
|
readonly [clusteringBrand]: true;
|
|
150
|
+
/** The k-colour palette, as `getPaletteFromClustering(this, k)`. Takes no options. Runs on the calling thread, with the main entry. */
|
|
151
|
+
getPalette(this: Clustering, k: number): Promise<Palette>;
|
|
152
|
+
/** Palette, weights and shares, as `getSwatchesFromClustering(this, k)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
|
|
153
|
+
getSwatches(this: Clustering, k: number): Promise<Swatches>;
|
|
154
|
+
/** The error curve and totals, as `getClusteringInfo(this)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
|
|
155
|
+
getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
|
|
156
|
+
/** Maps `image` to the k-colour palette, as `quantizeFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
|
|
157
|
+
quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
|
|
158
|
+
/** Indexed output, as `quantizeToIndicesFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
|
|
159
|
+
quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
144
160
|
}
|
|
145
161
|
|
|
146
162
|
/** What is not a clustering: a `Clustering` is not accepted where a palette is. */
|
|
@@ -184,7 +200,7 @@ export interface ProgressOptions extends CancelOptions {
|
|
|
184
200
|
onProgress?: ((progress: number) => void) | undefined;
|
|
185
201
|
}
|
|
186
202
|
|
|
187
|
-
/** Options for building the colour hierarchy: `
|
|
203
|
+
/** Options for building the colour hierarchy: `buildClustering`, `buildPalette`, and the clustering half of `quantize` and `quantizeToIndices`. */
|
|
188
204
|
export interface ClusteringOptions extends ProgressOptions {
|
|
189
205
|
/**
|
|
190
206
|
* `'rgb'` (default) minimises squared sRGB error, which is what MSE/PSNR measure.
|
|
@@ -207,7 +223,7 @@ export interface ClusteringOptions extends ProgressOptions {
|
|
|
207
223
|
* `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for images with alpha (RGBA or BGRA): pixels with alpha
|
|
208
224
|
* below the cutoff don't exist as far as the palette is concerned. They are left out of clustering, and the rest count
|
|
209
225
|
* whole instead of by opacity (so it replaces `alpha` for this call). That is the model of indexed output (GIF, palette
|
|
210
|
-
* PNG), and it gives the same palette everywhere: `
|
|
226
|
+
* PNG), and it gives the same palette everywhere: `buildPalette(image, k, { transparent })` is the palette
|
|
211
227
|
* `quantizeToIndices(image, k, { transparent })` uses, apart from that function's extra transparent entry.
|
|
212
228
|
* Cluster with it to get the palette you will map with (see `IndexOptions.transparent`). The cutoff is recorded in the
|
|
213
229
|
* clustering (see `ClusteringInfo.transparent`), and `quantizeToIndicesFromClustering` uses it unless you name one.
|
|
@@ -277,7 +293,7 @@ export interface IndexOptions {
|
|
|
277
293
|
* opaque in its nearest colour. `k` counts that entry, so `k = 256` gives at most 256 entries (255 colours and the
|
|
278
294
|
* transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is kept when any pixel is visible (an image with none gives just the transparent entry). Where
|
|
279
295
|
* this function builds the palette itself it also leaves the pixels below the cutoff out of clustering (see
|
|
280
|
-
* `ClusteringOptions.transparent`), so its palette is `
|
|
296
|
+
* `ClusteringOptions.transparent`), so its palette is `buildPalette(image, k - 1, { transparent })`'s. With a palette
|
|
281
297
|
* you supply (`quantizeToIndicesWithPalette`) there is no `k`: the entry is added to your palette as it is. In
|
|
282
298
|
* `quantizeToIndicesFromClustering` the default is the cutoff the clustering was made with.
|
|
283
299
|
*/
|
|
@@ -336,7 +352,7 @@ export interface InitOptions {
|
|
|
336
352
|
export const version: string;
|
|
337
353
|
|
|
338
354
|
/**
|
|
339
|
-
* The version of the data this library stores: the format of the clusterings `
|
|
355
|
+
* The version of the data this library stores: the format of the clusterings `buildClustering` writes (`getClusteringInfo`
|
|
340
356
|
* reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
|
|
341
357
|
* changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
|
|
342
358
|
* may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
|
|
@@ -355,16 +371,20 @@ export function init(options?: InitOptions): Promise<void>;
|
|
|
355
371
|
* cache or store next to the image. Cut it to a palette of any size with `getPaletteFromClustering`, or map pixels
|
|
356
372
|
* with `quantizeFromClustering`. An image with no visible pixels gives a clustering that cuts to an empty palette.
|
|
357
373
|
*/
|
|
374
|
+
export function buildClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
375
|
+
/** @deprecated Renamed {@link buildClustering} in 3.4.0 (the same function). Removed in 4.0. */
|
|
358
376
|
export function getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
359
377
|
|
|
360
378
|
/**
|
|
361
379
|
* A palette of at most `k` colours for `image` (fewer if it has fewer distinct colours), as flat RGB bytes in split
|
|
362
|
-
* order (see `getPaletteFromClustering`). It clusters the image each time: to try several sizes, call `
|
|
380
|
+
* order (see `getPaletteFromClustering`). It clusters the image each time: to try several sizes, call `buildClustering`
|
|
363
381
|
* once and cut it.
|
|
364
382
|
*
|
|
365
383
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
366
384
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
367
385
|
*/
|
|
386
|
+
export function buildPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
387
|
+
/** @deprecated Renamed {@link buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
|
|
368
388
|
export function getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
369
389
|
|
|
370
390
|
/**
|
|
@@ -401,10 +421,12 @@ export interface Swatches {
|
|
|
401
421
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
402
422
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
403
423
|
*/
|
|
424
|
+
export function buildSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
425
|
+
/** @deprecated Renamed {@link buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
|
|
404
426
|
export function getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
405
427
|
|
|
406
428
|
/**
|
|
407
|
-
* The same as `
|
|
429
|
+
* The same as `buildSwatches` from a clustering you already have, so trying another `k` costs well under a millisecond.
|
|
408
430
|
* Needs a clustering from 3.x; a 2.x clustering has no weights and is rejected.
|
|
409
431
|
*
|
|
410
432
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
@@ -485,7 +507,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
|
|
|
485
507
|
|
|
486
508
|
/**
|
|
487
509
|
* Like `quantize`, but returns each pixel's palette index instead of its colour, with the palette (for palette
|
|
488
|
-
* PNGs, pixel art and pattern generators). The palette is the one `
|
|
510
|
+
* PNGs, pixel art and pattern generators). The palette is the one `buildPalette` gives, except that with `transparent`
|
|
489
511
|
* pixels below the cutoff are left out of it.
|
|
490
512
|
*
|
|
491
513
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
package/dist/index.d.ts
CHANGED
|
@@ -125,12 +125,18 @@ export class Palette extends Uint8Array {
|
|
|
125
125
|
}
|
|
126
126
|
|
|
127
127
|
/**
|
|
128
|
-
* The bytes of a clustering, as `
|
|
128
|
+
* The bytes of a clustering, as `buildClustering` returns them: an opaque `Uint8Array` (tagged, like `Palette`) that you can
|
|
129
129
|
* store (a file, IndexedDB, next to the image) and cut to a palette of any size later. It is a type of its own, so a
|
|
130
130
|
* clustering can't be passed where a palette goes (or the other way round): TypeScript says so, and at run time a
|
|
131
131
|
* `Clustering` given as a palette is rejected, with no guessing about its bytes. Stored bytes come back as a plain
|
|
132
132
|
* `Uint8Array`, which functions still accept at run time; `new Clustering(bytes)` gives them the type back (TypeScript
|
|
133
133
|
* wants it) and checks they are a clustering.
|
|
134
|
+
*
|
|
135
|
+
* It has methods for the cluster-once workflow: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and
|
|
136
|
+
* so on. They run on the calling thread with the main entry, so in a worker-only app they compile but reject with
|
|
137
|
+
* `wasm-load-failed`. They exist only on values from this library or `new Clustering(bytes)`: slices and clones are plain
|
|
138
|
+
* bytes, and a cast (`bytes as Clustering`) or a `structuredClone` keeps the type without them: wrap those with
|
|
139
|
+
* `new Clustering(bytes)`.
|
|
134
140
|
*/
|
|
135
141
|
export class Clustering extends Uint8Array {
|
|
136
142
|
/**
|
|
@@ -141,6 +147,16 @@ export class Clustering extends Uint8Array {
|
|
|
141
147
|
constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
|
|
142
148
|
/** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
|
|
143
149
|
readonly [clusteringBrand]: true;
|
|
150
|
+
/** The k-colour palette, as `getPaletteFromClustering(this, k)`. Takes no options. Runs on the calling thread, with the main entry. */
|
|
151
|
+
getPalette(this: Clustering, k: number): Promise<Palette>;
|
|
152
|
+
/** Palette, weights and shares, as `getSwatchesFromClustering(this, k)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
|
|
153
|
+
getSwatches(this: Clustering, k: number): Promise<Swatches>;
|
|
154
|
+
/** The error curve and totals, as `getClusteringInfo(this)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
|
|
155
|
+
getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
|
|
156
|
+
/** Maps `image` to the k-colour palette, as `quantizeFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
|
|
157
|
+
quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
|
|
158
|
+
/** Indexed output, as `quantizeToIndicesFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
|
|
159
|
+
quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
144
160
|
}
|
|
145
161
|
|
|
146
162
|
/** What is not a clustering: a `Clustering` is not accepted where a palette is. */
|
|
@@ -184,7 +200,7 @@ export interface ProgressOptions extends CancelOptions {
|
|
|
184
200
|
onProgress?: ((progress: number) => void) | undefined;
|
|
185
201
|
}
|
|
186
202
|
|
|
187
|
-
/** Options for building the colour hierarchy: `
|
|
203
|
+
/** Options for building the colour hierarchy: `buildClustering`, `buildPalette`, and the clustering half of `quantize` and `quantizeToIndices`. */
|
|
188
204
|
export interface ClusteringOptions extends ProgressOptions {
|
|
189
205
|
/**
|
|
190
206
|
* `'rgb'` (default) minimises squared sRGB error, which is what MSE/PSNR measure.
|
|
@@ -207,7 +223,7 @@ export interface ClusteringOptions extends ProgressOptions {
|
|
|
207
223
|
* `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for images with alpha (RGBA or BGRA): pixels with alpha
|
|
208
224
|
* below the cutoff don't exist as far as the palette is concerned. They are left out of clustering, and the rest count
|
|
209
225
|
* whole instead of by opacity (so it replaces `alpha` for this call). That is the model of indexed output (GIF, palette
|
|
210
|
-
* PNG), and it gives the same palette everywhere: `
|
|
226
|
+
* PNG), and it gives the same palette everywhere: `buildPalette(image, k, { transparent })` is the palette
|
|
211
227
|
* `quantizeToIndices(image, k, { transparent })` uses, apart from that function's extra transparent entry.
|
|
212
228
|
* Cluster with it to get the palette you will map with (see `IndexOptions.transparent`). The cutoff is recorded in the
|
|
213
229
|
* clustering (see `ClusteringInfo.transparent`), and `quantizeToIndicesFromClustering` uses it unless you name one.
|
|
@@ -277,7 +293,7 @@ export interface IndexOptions {
|
|
|
277
293
|
* opaque in its nearest colour. `k` counts that entry, so `k = 256` gives at most 256 entries (255 colours and the
|
|
278
294
|
* transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is kept when any pixel is visible (an image with none gives just the transparent entry). Where
|
|
279
295
|
* this function builds the palette itself it also leaves the pixels below the cutoff out of clustering (see
|
|
280
|
-
* `ClusteringOptions.transparent`), so its palette is `
|
|
296
|
+
* `ClusteringOptions.transparent`), so its palette is `buildPalette(image, k - 1, { transparent })`'s. With a palette
|
|
281
297
|
* you supply (`quantizeToIndicesWithPalette`) there is no `k`: the entry is added to your palette as it is. In
|
|
282
298
|
* `quantizeToIndicesFromClustering` the default is the cutoff the clustering was made with.
|
|
283
299
|
*/
|
|
@@ -336,7 +352,7 @@ export interface InitOptions {
|
|
|
336
352
|
export const version: string;
|
|
337
353
|
|
|
338
354
|
/**
|
|
339
|
-
* The version of the data this library stores: the format of the clusterings `
|
|
355
|
+
* The version of the data this library stores: the format of the clusterings `buildClustering` writes (`getClusteringInfo`
|
|
340
356
|
* reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
|
|
341
357
|
* changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
|
|
342
358
|
* may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
|
|
@@ -355,16 +371,20 @@ export function init(options?: InitOptions): Promise<void>;
|
|
|
355
371
|
* cache or store next to the image. Cut it to a palette of any size with `getPaletteFromClustering`, or map pixels
|
|
356
372
|
* with `quantizeFromClustering`. An image with no visible pixels gives a clustering that cuts to an empty palette.
|
|
357
373
|
*/
|
|
374
|
+
export function buildClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
375
|
+
/** @deprecated Renamed {@link buildClustering} in 3.4.0 (the same function). Removed in 4.0. */
|
|
358
376
|
export function getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
359
377
|
|
|
360
378
|
/**
|
|
361
379
|
* A palette of at most `k` colours for `image` (fewer if it has fewer distinct colours), as flat RGB bytes in split
|
|
362
|
-
* order (see `getPaletteFromClustering`). It clusters the image each time: to try several sizes, call `
|
|
380
|
+
* order (see `getPaletteFromClustering`). It clusters the image each time: to try several sizes, call `buildClustering`
|
|
363
381
|
* once and cut it.
|
|
364
382
|
*
|
|
365
383
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
366
384
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
367
385
|
*/
|
|
386
|
+
export function buildPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
387
|
+
/** @deprecated Renamed {@link buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
|
|
368
388
|
export function getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
369
389
|
|
|
370
390
|
/**
|
|
@@ -401,10 +421,12 @@ export interface Swatches {
|
|
|
401
421
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
402
422
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
403
423
|
*/
|
|
424
|
+
export function buildSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
425
|
+
/** @deprecated Renamed {@link buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
|
|
404
426
|
export function getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
405
427
|
|
|
406
428
|
/**
|
|
407
|
-
* The same as `
|
|
429
|
+
* The same as `buildSwatches` from a clustering you already have, so trying another `k` costs well under a millisecond.
|
|
408
430
|
* Needs a clustering from 3.x; a 2.x clustering has no weights and is rejected.
|
|
409
431
|
*
|
|
410
432
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
@@ -485,7 +507,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
|
|
|
485
507
|
|
|
486
508
|
/**
|
|
487
509
|
* Like `quantize`, but returns each pixel's palette index instead of its colour, with the palette (for palette
|
|
488
|
-
* PNGs, pixel art and pattern generators). The palette is the one `
|
|
510
|
+
* PNGs, pixel art and pattern generators). The palette is the one `buildPalette` gives, except that with `transparent`
|
|
489
511
|
* pixels below the cutoff are left out of it.
|
|
490
512
|
*
|
|
491
513
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|