agglomerative-clustering 4.0.0-beta.1 → 4.0.0-beta.3
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 +5 -5
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +37 -63
- package/dist/index.d.cts +15 -76
- package/dist/index.d.ts +15 -76
- package/dist/index.mjs +36 -57
- package/dist/shared.cjs +73 -79
- package/dist/shared.mjs +68 -73
- package/dist/worker-thread.mjs +15 -18
- package/dist/worker.cjs +139 -84
- package/dist/worker.d.cts +0 -32
- package/dist/worker.d.ts +0 -32
- package/dist/worker.mjs +138 -78
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -24,9 +24,9 @@ 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? See [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md). From 3.
|
|
27
|
+
Upgrading? See [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md). From 3.x, 4.0 removed the get… and …FromClustering functions, turned two warnings into errors (a bare RGB or grey array, and `transparent` on a format with no alpha), and needs Node 22.12+: see [From 3.x to 4.0](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md#from-3x-to-40). 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
|
-
It runs on Node
|
|
29
|
+
It runs on Node 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
|
|
|
31
31
|
## Usage
|
|
32
32
|
|
|
@@ -82,7 +82,7 @@ slider.oninput = async () => {
|
|
|
82
82
|
};
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
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, or premultiplied (canvas, Electron): pass `premultiplied: true` with `'rgba'` or `'bgra'`; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources and what to pass for each. Mapped output of a premultiplied image comes back premultiplied (palettes and indices are straight), so for an `ImageData` or a PNG encoder use the [straight-output recipe](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#straight-pixels-from-a-premultiplied-source). RGB bytes passed bare
|
|
85
|
+
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, or premultiplied (canvas, Electron): pass `premultiplied: true` with `'rgba'` or `'bgra'`; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources and what to pass for each. Mapped output of a premultiplied image comes back premultiplied (palettes and indices are straight), so for an `ImageData` or a PNG encoder use the [straight-output recipe](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#straight-pixels-from-a-premultiplied-source). RGB bytes passed bare would be read as RGBA; the library throws when it sees this, so pass them as `{ data, format: 'rgb' }`. To start from a PNG, JPEG, WebP or GIF file, decode it first: [Decoding image files](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#decoding-image-files) has a recipe for Node, browsers and edge runtimes. 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.
|
|
86
86
|
|
|
87
87
|
## How it works
|
|
88
88
|
|
|
@@ -105,11 +105,11 @@ The one-shot functions (`buildPalette`, `quantize`, …) do every step for you.
|
|
|
105
105
|
|
|
106
106
|
A clustering you hold has **methods** that take the colours from it, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `buildClustering` builds a clustering, and `init` loads the WebAssembly module (optional). Most code only needs the first column.
|
|
107
107
|
|
|
108
|
-
The verb says how much work a call does. `build…` clusters an image (tens of milliseconds for a photo). `get…` reads or cuts what a clustering or a worker handle already holds (well under a millisecond). `quantize…` maps pixels. So `buildPalette(image, k)` and `clustering.getPalette(k)` give the same kind of result from different starting points.
|
|
108
|
+
The verb says how much work a call does. `build…` clusters an image (tens of milliseconds for a photo). `get…` reads or cuts what a clustering or a worker handle already holds (well under a millisecond). `quantize…` maps pixels. So `buildPalette(image, k)` and `clustering.getPalette(k)` give the same kind of result from different starting points. [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md) lists the names 4.0 removed.
|
|
109
109
|
|
|
110
110
|
**Where to call them.** On the main thread, or in a Node script, use the methods: they are the shortest way to cut one clustering many times. **Off the thread, use a handle**: `worker.cluster(image)` keeps an image and its clustering in the worker, and `worker.load(clustering)` keeps a stored clustering (`await using loaded = await worker.load(stored)`, then `loaded.getPalette(k)` and `loaded.quantize(image, k)`). The methods always run on the thread that calls them, with the main entry, and reject with `wasm-load-failed` where only the worker entry is imported.
|
|
111
111
|
|
|
112
|
-
¹
|
|
112
|
+
¹ A clustering from storage is plain bytes: wrap it with `new Clustering(bytes)` to get the methods back, or off the thread load it with `worker.load(bytes)`. See [Clustering methods](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#clustering-methods).
|
|
113
113
|
|
|
114
114
|
Palettes come in **split order**: the palette for `k + 1` is the one for `k` with one colour split in two, so entries keep their place as `k` grows (they are not sorted by share). The options are `precision` (6 is about 3× faster at practically the same quality), `colorSpace` (`'rgb'` or `'oklab'`), `alpha`, `transparent`, `dither` (Floyd–Steinberg, Atkinson, or ordered for animation, which keeps still areas still), `width`, `signal` and `onProgress`: see the [API reference](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md).
|
|
115
115
|
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|
package/dist/index.cjs
CHANGED
|
@@ -46,7 +46,7 @@ Object.defineProperty(exports, "errorCodes", {
|
|
|
46
46
|
return _shared.errorCodes;
|
|
47
47
|
}
|
|
48
48
|
});
|
|
49
|
-
exports.
|
|
49
|
+
exports.formatVersion = void 0;
|
|
50
50
|
Object.defineProperty(exports, "imageFormats", {
|
|
51
51
|
enumerable: true,
|
|
52
52
|
get: function () {
|
|
@@ -60,7 +60,7 @@ Object.defineProperty(exports, "isCodedError", {
|
|
|
60
60
|
return _shared.isCodedError;
|
|
61
61
|
}
|
|
62
62
|
});
|
|
63
|
-
exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.
|
|
63
|
+
exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndices = exports.quantize = void 0;
|
|
64
64
|
Object.defineProperty(exports, "version", {
|
|
65
65
|
enumerable: true,
|
|
66
66
|
get: function () {
|
|
@@ -165,7 +165,7 @@ const hasSimd = () => {
|
|
|
165
165
|
}
|
|
166
166
|
};
|
|
167
167
|
// Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
|
|
168
|
-
// process.versions.node, but their navigator.userAgent says what they are (Node
|
|
168
|
+
// process.versions.node, but their navigator.userAgent says what they are (old Node versions have no navigator at all).
|
|
169
169
|
const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
|
|
170
170
|
// A browser page or worker, as opposed to a server-side runtime that isn't Node (Cloudflare Workers, Vercel's edge runtime,
|
|
171
171
|
// Deno Deploy): only those have a document, a worker scope or a browser's user agent.
|
|
@@ -480,23 +480,10 @@ const bytes = data => (0, _shared.isUint8Array)(data) ? data : new Uint8Array(da
|
|
|
480
480
|
// or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
|
|
481
481
|
// call returns; until then (the first call) a copy is kept for when it has loaded.
|
|
482
482
|
const held = data => Module ? data : data.slice();
|
|
483
|
-
|
|
484
|
-
// The bare-image warning (rgb-as-rgba, gray-as-rgba) for an image, decided before load() and given only once the call's own checks have passed,
|
|
485
|
-
// just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
|
|
486
|
-
const noWarning = () => {};
|
|
487
|
-
// A call whose signal is already aborted fails before any work, so it doesn't use the warning up either.
|
|
488
|
-
const warningFor = image => {
|
|
489
|
-
const warning = (0, _shared.bareImageWarning)(image);
|
|
490
|
-
return warning ? signal => {
|
|
491
|
-
if (!(signal && signal.aborted)) {
|
|
492
|
-
(0, _shared.warnOnce)(warning, image.byteLength);
|
|
493
|
-
}
|
|
494
|
-
} : noWarning;
|
|
495
|
-
};
|
|
496
483
|
const load = image => {
|
|
497
484
|
if ((0, _shared.isClustering)(image) || (0, _shared.isPalette)(image)) {
|
|
498
485
|
const what = (0, _shared.isClustering)(image) ? 'a clustering (from buildClustering)' : 'a palette';
|
|
499
|
-
const fix = (0, _shared.isClustering)(image) ? 'To cut a palette from it, use
|
|
486
|
+
const fix = (0, _shared.isClustering)(image) ? 'To cut a palette from it, use clustering.getPalette(k) (or clustering.quantize(image, k) to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
|
|
500
487
|
throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
|
|
501
488
|
}
|
|
502
489
|
if (ArrayBuffer.isView(image) && (0, _shared.isDetached)(image)) {
|
|
@@ -510,6 +497,10 @@ const load = image => {
|
|
|
510
497
|
if (image.length % 4 !== 0) {
|
|
511
498
|
throw (0, _shared.fail)('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
|
|
512
499
|
}
|
|
500
|
+
const bare = (0, _shared.bareImageError)(image);
|
|
501
|
+
if (bare) {
|
|
502
|
+
throw bare;
|
|
503
|
+
}
|
|
513
504
|
return {
|
|
514
505
|
data: held(image),
|
|
515
506
|
format: 'rgba',
|
|
@@ -534,13 +525,7 @@ const load = image => {
|
|
|
534
525
|
if (typeof image !== 'object' || !image || !image.data || !image.format) {
|
|
535
526
|
throw (0, _shared.fail)('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${(0, _shared.imageHint)(image)}`, 'image');
|
|
536
527
|
}
|
|
537
|
-
|
|
538
|
-
throw (0, _shared.fail)('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
|
|
539
|
-
}
|
|
540
|
-
if ((0, _shared.isDetached)(image.data)) {
|
|
541
|
-
throw (0, _shared.detachedError)('data');
|
|
542
|
-
}
|
|
543
|
-
const premultiplied = (0, _shared.checkImageObject)(image);
|
|
528
|
+
const premultiplied = (0, _shared.checkImageBody)(image);
|
|
544
529
|
return {
|
|
545
530
|
data: held(bytes(image.data)),
|
|
546
531
|
format: image.format,
|
|
@@ -705,6 +690,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
705
690
|
if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
|
|
706
691
|
throw (0, _shared.fail)('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
|
|
707
692
|
}
|
|
693
|
+
checkTransparentFormat(image, options);
|
|
708
694
|
|
|
709
695
|
// A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
|
|
710
696
|
if (transparent > 0 && options.alpha !== undefined) {
|
|
@@ -726,6 +712,15 @@ const parseOptions = (options, allowed, image) => {
|
|
|
726
712
|
};
|
|
727
713
|
};
|
|
728
714
|
const controlOptions = ['signal', 'onProgress'];
|
|
715
|
+
// `transparent: true` or a cutoff on a format with no alpha channel can't mean anything (no pixel is transparent), so it is
|
|
716
|
+
// an error rather than a silent no-op. Only the call's own options count: a clustering's stored cutoff never reaches here.
|
|
717
|
+
const checkTransparentFormat = (image, options) => {
|
|
718
|
+
if (!image || (0, _shared.hasAlpha)(image.format) || options.transparent === undefined || options.transparent === false) {
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
const hint = image.format === 'rgbx' || image.format === 'bgrx' ? " If the fourth byte really is alpha, use 'rgba' or 'bgra'." : '';
|
|
722
|
+
throw (0, _shared.fail)('invalid-argument', `Invalid transparent: '${image.format}' has no alpha, so no pixel can be transparent. Leave transparent out (false is accepted).${hint}`, 'options.transparent');
|
|
723
|
+
};
|
|
729
724
|
const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
|
|
730
725
|
const quantizeOptions = [...clusterOptions, 'dither', 'width'];
|
|
731
726
|
const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
|
|
@@ -1006,12 +1001,11 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
|
|
|
1006
1001
|
|
|
1007
1002
|
// The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
|
|
1008
1003
|
// anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
|
|
1009
|
-
// `name` is how the caller wrote the call
|
|
1010
|
-
//
|
|
1004
|
+
// `name` is how the caller wrote the call (the method, `clustering.getPalette`), whose message points at the method form
|
|
1005
|
+
// of mapping.
|
|
1011
1006
|
const noOptions = (name, extra) => {
|
|
1012
1007
|
if (extra.some(value => value !== undefined)) {
|
|
1013
|
-
|
|
1014
|
-
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');
|
|
1008
|
+
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 clustering.quantize(image, k, options).`, 'options');
|
|
1015
1009
|
}
|
|
1016
1010
|
};
|
|
1017
1011
|
|
|
@@ -1020,10 +1014,9 @@ const noOptions = (name, extra) => {
|
|
|
1020
1014
|
// happens before the call returns.
|
|
1021
1015
|
|
|
1022
1016
|
const buildClustering = async (image, options) => {
|
|
1023
|
-
|
|
1017
|
+
image = (0, _shared.imageCopy)(image);
|
|
1024
1018
|
image = load(image);
|
|
1025
1019
|
const o = parseOptions(options, clusterOptions, image);
|
|
1026
|
-
warn(o.signal);
|
|
1027
1020
|
const wasm = Module || (await acquire());
|
|
1028
1021
|
if (isControlled(o)) {
|
|
1029
1022
|
const report = reporter(o);
|
|
@@ -1033,15 +1026,12 @@ const buildClustering = async (image, options) => {
|
|
|
1033
1026
|
}
|
|
1034
1027
|
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, image.premultiplied));
|
|
1035
1028
|
};
|
|
1036
|
-
/** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
|
|
1037
1029
|
exports.buildClustering = buildClustering;
|
|
1038
|
-
const getClustering = exports.getClustering = buildClustering;
|
|
1039
1030
|
const buildPalette = async (image, k, options) => {
|
|
1040
|
-
|
|
1031
|
+
image = (0, _shared.imageCopy)(image);
|
|
1041
1032
|
image = load(image);
|
|
1042
1033
|
k = check(k);
|
|
1043
1034
|
const o = parseOptions(options, clusterOptions, image);
|
|
1044
|
-
warn(o.signal);
|
|
1045
1035
|
const wasm = Module || (await acquire());
|
|
1046
1036
|
if (isControlled(o)) {
|
|
1047
1037
|
const report = reporter(o);
|
|
@@ -1053,11 +1043,9 @@ const buildPalette = async (image, k, options) => {
|
|
|
1053
1043
|
}
|
|
1054
1044
|
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, image.premultiplied), (0, _shared.colorSpaceName)(o.colorSpace));
|
|
1055
1045
|
};
|
|
1056
|
-
/** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
|
|
1057
|
-
exports.buildPalette = buildPalette;
|
|
1058
|
-
const getPalette = exports.getPalette = buildPalette;
|
|
1059
1046
|
|
|
1060
|
-
// The cuts take the name they were called by, for their messages: the
|
|
1047
|
+
// The cuts take the name they were called by, for their messages: the methods on Clustering (or the function that cuts).
|
|
1048
|
+
exports.buildPalette = buildPalette;
|
|
1061
1049
|
const cutPalette = async (name, clustering, k, extra) => {
|
|
1062
1050
|
const header = (0, _shared.readHeader)(clustering);
|
|
1063
1051
|
k = check(k);
|
|
@@ -1066,10 +1054,8 @@ const cutPalette = async (name, clustering, k, extra) => {
|
|
|
1066
1054
|
const wasm = Module || (await acquire());
|
|
1067
1055
|
return (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
|
|
1068
1056
|
};
|
|
1069
|
-
const getPaletteFromClustering = (clustering, k, ...extra) => cutPalette('getPaletteFromClustering', clustering, k, extra);
|
|
1070
1057
|
|
|
1071
1058
|
// The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
|
|
1072
|
-
exports.getPaletteFromClustering = getPaletteFromClustering;
|
|
1073
1059
|
const weightsOf = (wasm, clustering, header, k) => {
|
|
1074
1060
|
const bytes = call(wasm, [clustering], clusteringPointer => wasm._get_palette_weights(clusteringPointer, clustering.length, k));
|
|
1075
1061
|
if (header.merges > 0 && bytes.length === 0) {
|
|
@@ -1114,23 +1100,21 @@ const cutSwatches = async (name, clustering, k, extra) => {
|
|
|
1114
1100
|
shares
|
|
1115
1101
|
};
|
|
1116
1102
|
};
|
|
1117
|
-
const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getSwatchesFromClustering', clustering, k, extra);
|
|
1118
1103
|
|
|
1119
|
-
// The same for an image: clusters it, then cuts, like
|
|
1120
|
-
exports.getSwatchesFromClustering = getSwatchesFromClustering;
|
|
1104
|
+
// The same for an image: clusters it, then cuts, like buildPalette.
|
|
1121
1105
|
const buildSwatches = async (image, k, options) => {
|
|
1106
|
+
image = (0, _shared.imageCopy)(image);
|
|
1122
1107
|
// Arguments are checked in the order they are given (image, then k, then options), as in every other function.
|
|
1108
|
+
// `load` only validates here (buildClustering loads again); both see the copy, so the caller's fields are read once.
|
|
1123
1109
|
load(image);
|
|
1124
1110
|
k = check(k);
|
|
1125
|
-
return
|
|
1111
|
+
return cutSwatches('buildSwatches', await buildClustering(image, options), k, []);
|
|
1126
1112
|
};
|
|
1127
|
-
/** @deprecated The same function as buildSwatches, its name before 3.4.0. Removed in 4.0. */
|
|
1128
|
-
exports.buildSwatches = buildSwatches;
|
|
1129
|
-
const getSwatches = exports.getSwatches = buildSwatches;
|
|
1130
1113
|
|
|
1131
1114
|
// What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
|
|
1132
1115
|
// squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
|
|
1133
1116
|
// weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
|
|
1117
|
+
exports.buildSwatches = buildSwatches;
|
|
1134
1118
|
const readInfo = async (name, clustering, extra) => {
|
|
1135
1119
|
const header = (0, _shared.readHeader)(clustering);
|
|
1136
1120
|
noOptions(name, extra);
|
|
@@ -1174,15 +1158,12 @@ const readInfo = async (name, clustering, extra) => {
|
|
|
1174
1158
|
}
|
|
1175
1159
|
return info;
|
|
1176
1160
|
};
|
|
1177
|
-
const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
|
|
1178
|
-
exports.getClusteringInfo = getClusteringInfo;
|
|
1179
1161
|
const quantize = async (image, k, options) => {
|
|
1180
|
-
|
|
1162
|
+
image = (0, _shared.imageCopy)(image);
|
|
1181
1163
|
const wrap = getWrapper(image);
|
|
1182
1164
|
image = load(image);
|
|
1183
1165
|
k = check(k);
|
|
1184
1166
|
const o = parseOptions(options, quantizeOptions, image);
|
|
1185
|
-
warn(o.signal);
|
|
1186
1167
|
const wasm = Module || (await acquire());
|
|
1187
1168
|
if (isControlled(o)) {
|
|
1188
1169
|
const report = reporter(o);
|
|
@@ -1199,14 +1180,13 @@ const quantize = async (image, k, options) => {
|
|
|
1199
1180
|
};
|
|
1200
1181
|
exports.quantize = quantize;
|
|
1201
1182
|
const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
1202
|
-
|
|
1183
|
+
image = (0, _shared.imageCopy)(image);
|
|
1203
1184
|
const wrap = getWrapper(image);
|
|
1204
1185
|
image = load(image);
|
|
1205
1186
|
(0, _shared.readHeader)(clustering);
|
|
1206
1187
|
k = check(k);
|
|
1207
1188
|
const o = parseOptions(options, mapOptions, image);
|
|
1208
1189
|
clustering = held(clustering);
|
|
1209
|
-
warn(o.signal);
|
|
1210
1190
|
const wasm = Module || (await acquire());
|
|
1211
1191
|
checkAborted(o.signal);
|
|
1212
1192
|
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
@@ -1222,9 +1202,8 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
|
1222
1202
|
const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
|
|
1223
1203
|
return result;
|
|
1224
1204
|
};
|
|
1225
|
-
exports.quantizeFromClustering = quantizeFromClustering;
|
|
1226
1205
|
const quantizeWithPalette = async (image, palette, options) => {
|
|
1227
|
-
|
|
1206
|
+
image = (0, _shared.imageCopy)(image);
|
|
1228
1207
|
const wrap = getWrapper(image);
|
|
1229
1208
|
image = load(image);
|
|
1230
1209
|
(0, _shared.checkPalette)(palette);
|
|
@@ -1232,7 +1211,6 @@ const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1232
1211
|
checkNotEmpty(palette, image, 1);
|
|
1233
1212
|
const space = matchingSpace(o, palette);
|
|
1234
1213
|
palette = held(palette);
|
|
1235
|
-
warn(o.signal);
|
|
1236
1214
|
const wasm = Module || (await acquire());
|
|
1237
1215
|
checkAborted(o.signal);
|
|
1238
1216
|
if (isControlled(o)) {
|
|
@@ -1248,12 +1226,11 @@ const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1248
1226
|
};
|
|
1249
1227
|
exports.quantizeWithPalette = quantizeWithPalette;
|
|
1250
1228
|
const quantizeToIndices = async (image, k, options) => {
|
|
1251
|
-
|
|
1229
|
+
image = (0, _shared.imageCopy)(image);
|
|
1252
1230
|
const original = image;
|
|
1253
1231
|
image = load(image);
|
|
1254
1232
|
k = check(k);
|
|
1255
1233
|
const o = parseOptions(options, quantizeIndexOptions, image);
|
|
1256
|
-
warn(o.signal);
|
|
1257
1234
|
const wasm = Module || (await acquire());
|
|
1258
1235
|
if (isControlled(o)) {
|
|
1259
1236
|
const report = reporter(o);
|
|
@@ -1270,14 +1247,13 @@ const quantizeToIndices = async (image, k, options) => {
|
|
|
1270
1247
|
};
|
|
1271
1248
|
exports.quantizeToIndices = quantizeToIndices;
|
|
1272
1249
|
const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
|
|
1273
|
-
|
|
1250
|
+
image = (0, _shared.imageCopy)(image);
|
|
1274
1251
|
const original = image;
|
|
1275
1252
|
image = load(image);
|
|
1276
1253
|
const header = (0, _shared.readHeader)(clustering);
|
|
1277
1254
|
k = check(k);
|
|
1278
1255
|
const o = parseOptions(options, mapIndexOptions, image);
|
|
1279
1256
|
clustering = held(clustering);
|
|
1280
|
-
warn(o.signal);
|
|
1281
1257
|
const wasm = Module || (await acquire());
|
|
1282
1258
|
checkAborted(o.signal);
|
|
1283
1259
|
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
@@ -1296,9 +1272,8 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
|
|
|
1296
1272
|
const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff), undefined, image.premultiplied), original, (0, _shared.colorSpaceName)(header.colorSpace));
|
|
1297
1273
|
return result;
|
|
1298
1274
|
};
|
|
1299
|
-
exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
|
|
1300
1275
|
const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
1301
|
-
|
|
1276
|
+
image = (0, _shared.imageCopy)(image);
|
|
1302
1277
|
const original = image;
|
|
1303
1278
|
image = load(image);
|
|
1304
1279
|
(0, _shared.checkPalette)(palette);
|
|
@@ -1307,7 +1282,6 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1307
1282
|
const space = matchingSpace(o, palette);
|
|
1308
1283
|
const paletteSpace = (0, _shared.isPalette)(palette) ? palette.colorSpace : (0, _shared.colorSpaceName)(space);
|
|
1309
1284
|
palette = held(palette);
|
|
1310
|
-
warn(o.signal);
|
|
1311
1285
|
const wasm = Module || (await acquire());
|
|
1312
1286
|
checkAborted(o.signal);
|
|
1313
1287
|
if (isControlled(o)) {
|
package/dist/index.d.cts
CHANGED
|
@@ -17,7 +17,8 @@ export type ImageFormat = 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx';
|
|
|
17
17
|
* newer format version or one using a colour space it doesn't know, or an older one that lacks what was asked for),
|
|
18
18
|
* `out-of-memory`, `wasm-load-failed` (the WebAssembly module could not be loaded or compiled: a missing or blocked file, a
|
|
19
19
|
* browser without SIMD, or a `.wasm` from another version of the library), and in the worker entry
|
|
20
|
-
* `worker-terminated`, `worker-failed`
|
|
20
|
+
* `worker-terminated`, `worker-failed` (the worker could not start, crashed, or runs a script from another version of the
|
|
21
|
+
* package) and `invalid-handle`.
|
|
21
22
|
*/
|
|
22
23
|
export type ErrorCode = 'invalid-argument' | 'invalid-clustering' | 'unsupported-version' | 'out-of-memory' | 'wasm-load-failed'
|
|
23
24
|
| 'worker-terminated' | 'worker-failed' | 'invalid-handle';
|
|
@@ -165,7 +166,7 @@ export class Palette extends Uint8Array {
|
|
|
165
166
|
* `Uint8Array`, which functions still accept at run time; `new Clustering(bytes)` gives them the type back (TypeScript
|
|
166
167
|
* wants it) and checks they are a clustering.
|
|
167
168
|
*
|
|
168
|
-
* It has methods for the cluster-once workflow: `clustering.getPalette(k)`
|
|
169
|
+
* It has methods for the cluster-once workflow: `clustering.getPalette(k)` cuts a palette from it, and
|
|
169
170
|
* so on. They run on the calling thread with the main entry, so in a worker-only app they compile but reject with
|
|
170
171
|
* `wasm-load-failed`. They exist only on values from this library or `new Clustering(bytes)`: slices and clones are plain
|
|
171
172
|
* bytes, and a cast (`bytes as Clustering`) or a `structuredClone` keeps the type without them: wrap those with
|
|
@@ -274,7 +275,7 @@ export interface ClusteringOptions extends ProgressOptions {
|
|
|
274
275
|
* PNG), and it gives the same palette everywhere: `buildPalette(image, k, { transparent })` is the palette
|
|
275
276
|
* `quantizeToIndices(image, k, { transparent })` uses, apart from that function's extra transparent entry.
|
|
276
277
|
* Cluster with it to get the palette you will map with (see `IndexOptions.transparent`). The cutoff is recorded in the
|
|
277
|
-
* clustering (see `ClusteringInfo.transparent`), and `
|
|
278
|
+
* clustering (see `ClusteringInfo.transparent`), and `clustering.quantizeToIndices(image, k)` uses it unless you name one.
|
|
278
279
|
* It replaces `alpha` (with a cutoff, pixels count whole or not at all), so giving both is an `invalid-argument` error.
|
|
279
280
|
*/
|
|
280
281
|
transparent?: boolean | number | undefined;
|
|
@@ -305,11 +306,11 @@ export type DitherOptions =
|
|
|
305
306
|
| { method?: 'floyd-steinberg' | 'atkinson' | undefined; strength?: number | undefined; steps?: undefined }
|
|
306
307
|
| { method: 'ordered'; strength?: number | undefined; steps?: DitherSteps | undefined };
|
|
307
308
|
|
|
308
|
-
/** Options for mapping pixels to a palette: `
|
|
309
|
+
/** Options for mapping pixels to a palette: `clustering.quantize`, `quantizeWithPalette`, and the mapping half of `quantize` and `quantizeToIndices`. With `signal` or `onProgress`, mapping runs in slices, as clustering does. */
|
|
309
310
|
export interface MappingOptions extends ProgressOptions {
|
|
310
311
|
/**
|
|
311
312
|
* The space pixels are matched to their nearest palette colour in. The default is the space the colours were made in:
|
|
312
|
-
* the clustering's in `
|
|
313
|
+
* the clustering's in `clustering.quantize`, a `Palette`'s own in `quantizeWithPalette` and
|
|
313
314
|
* `quantizeToIndicesWithPalette`; `'rgb'` for plain bytes, and in `quantize` and `quantizeToIndices`, which match in the
|
|
314
315
|
* space they cluster in.
|
|
315
316
|
*/
|
|
@@ -343,14 +344,14 @@ export interface IndexOptions {
|
|
|
343
344
|
* this function builds the palette itself it also leaves the pixels below the cutoff out of clustering (see
|
|
344
345
|
* `ClusteringOptions.transparent`), so its palette is `buildPalette(image, k - 1, { transparent })`'s. With a palette
|
|
345
346
|
* you supply (`quantizeToIndicesWithPalette`) there is no `k`: the entry is added to your palette as it is. In
|
|
346
|
-
* `
|
|
347
|
+
* `clustering.quantizeToIndices` the default is the cutoff the clustering was made with.
|
|
347
348
|
*/
|
|
348
349
|
transparent?: boolean | number | undefined;
|
|
349
350
|
}
|
|
350
351
|
|
|
351
352
|
/** The options of `quantizeToIndices`: clustering, mapping and indexed-output options. */
|
|
352
353
|
export type QuantizeIndexOptions = QuantizeOptions & IndexOptions;
|
|
353
|
-
/** The options of `
|
|
354
|
+
/** The options of `clustering.quantizeToIndices` and `quantizeToIndicesWithPalette`: mapping and indexed-output options. */
|
|
354
355
|
export type MappingIndexOptions = MappingOptions & IndexOptions;
|
|
355
356
|
|
|
356
357
|
interface IndexedImageFields {
|
|
@@ -401,10 +402,10 @@ export interface InitOptions {
|
|
|
401
402
|
export const version: string;
|
|
402
403
|
|
|
403
404
|
/**
|
|
404
|
-
* The version of the data this library stores: the format of the clusterings `buildClustering` writes (`getClusteringInfo`
|
|
405
|
+
* The version of the data this library stores: the format of the clusterings `buildClustering` writes (`clustering.getClusteringInfo()`
|
|
405
406
|
* reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
|
|
406
407
|
* changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
|
|
407
|
-
* may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
|
|
408
|
+
* may raise it. Every earlier format from 2 on stays readable (see `clustering.getClusteringInfo()` for what 2.x clusterings lack).
|
|
408
409
|
*/
|
|
409
410
|
export const formatVersion: number;
|
|
410
411
|
|
|
@@ -417,12 +418,10 @@ export function init(options?: InitOptions): Promise<void>;
|
|
|
417
418
|
|
|
418
419
|
/**
|
|
419
420
|
* Builds the colour hierarchy for an image: the expensive step, done once. The result is a `Clustering` (opaque bytes) you can
|
|
420
|
-
* cache or store next to the image. Cut it to a palette of any size with `
|
|
421
|
-
* with `
|
|
421
|
+
* cache or store next to the image. Cut it to a palette of any size with `clustering.getPalette(k)`, or map pixels
|
|
422
|
+
* with `clustering.quantize(image, k)`. An image with no visible pixels gives a clustering that cuts to an empty palette.
|
|
422
423
|
*/
|
|
423
424
|
export function buildClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
424
|
-
/** @deprecated Renamed {@link buildClustering} in 3.4.0 (the same function). Removed in 4.0. */
|
|
425
|
-
export function getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
426
425
|
|
|
427
426
|
/**
|
|
428
427
|
* A palette of at most `k` colours for `image` (fewer if it has fewer distinct colours), as flat RGB bytes in split
|
|
@@ -433,20 +432,6 @@ export function getClustering(image: ImageLike, options?: ClusteringOptions): Pr
|
|
|
433
432
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
434
433
|
*/
|
|
435
434
|
export function buildPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
436
|
-
/** @deprecated Renamed {@link buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
|
|
437
|
-
export function getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
438
|
-
|
|
439
|
-
/**
|
|
440
|
-
* Cuts a clustering to at most `k` colours, in split order: index 0 is the dominant colour at two colours and keeps its
|
|
441
|
-
* place as the palette grows (it is not always the heaviest entry of a larger one), and the palette for
|
|
442
|
-
* `k + 1` is the palette for `k` with one entry refined and one colour appended.
|
|
443
|
-
*
|
|
444
|
-
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
445
|
-
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
446
|
-
*
|
|
447
|
-
* @deprecated Use `clustering.getPalette(k)`; off the main thread, `(await worker.load(clustering)).getPalette(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
448
|
-
*/
|
|
449
|
-
export function getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
|
|
450
435
|
|
|
451
436
|
/**
|
|
452
437
|
* A palette with how much of the image each of its colours covers, for swatches with percentages. The three arrays come
|
|
@@ -473,21 +458,8 @@ export interface Swatches {
|
|
|
473
458
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
474
459
|
*/
|
|
475
460
|
export function buildSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
476
|
-
/** @deprecated Renamed {@link buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
|
|
477
|
-
export function getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
478
461
|
|
|
479
|
-
/**
|
|
480
|
-
* The same as `buildSwatches` from a clustering you already have, so trying another `k` costs well under a millisecond.
|
|
481
|
-
* Needs a clustering from 3.x; a 2.x clustering has no weights and is rejected.
|
|
482
|
-
*
|
|
483
|
-
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
484
|
-
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
485
|
-
*
|
|
486
|
-
* @deprecated Use `clustering.getSwatches(k)`; off the main thread, `(await worker.load(clustering)).getSwatches(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
487
|
-
*/
|
|
488
|
-
export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
|
|
489
|
-
|
|
490
|
-
/** What a clustering holds (`getClusteringInfo`). */
|
|
462
|
+
/** What a clustering holds (`clustering.getClusteringInfo()`). */
|
|
491
463
|
export interface ClusteringInfo {
|
|
492
464
|
/**
|
|
493
465
|
* The format of the clustering's bytes: the data version (compare it with the exported `formatVersion`, the one this
|
|
@@ -499,7 +471,7 @@ export interface ClusteringInfo {
|
|
|
499
471
|
precision: number;
|
|
500
472
|
/**
|
|
501
473
|
* The alpha cutoff (1-255) the clustering was made with (`transparent` in `ClusteringOptions`), or `false` for none. It is
|
|
502
|
-
* the default `transparent` of `
|
|
474
|
+
* the default `transparent` of `clustering.quantizeToIndices`, so clustering and mapping agree unless you name another.
|
|
503
475
|
*/
|
|
504
476
|
transparent: false | number;
|
|
505
477
|
/** The largest palette it can be cut to: its number of distinct clustered colours (fewer than the image's own when `precision` is below 8). */
|
|
@@ -523,15 +495,6 @@ export interface ClusteringInfo {
|
|
|
523
495
|
explained: Float64Array;
|
|
524
496
|
}
|
|
525
497
|
|
|
526
|
-
/**
|
|
527
|
-
* Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
|
|
528
|
-
* clustering recorded no weights, so it is rejected with `unsupported-version` (as `clustering.getSwatches(k)` rejects it);
|
|
529
|
-
* the palette and mapping functions still read it.
|
|
530
|
-
*
|
|
531
|
-
* @deprecated Use `clustering.getClusteringInfo()`; off the main thread, `(await worker.load(clustering)).getClusteringInfo()` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
532
|
-
*/
|
|
533
|
-
export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
|
|
534
|
-
|
|
535
498
|
/**
|
|
536
499
|
* Reduces `image` to at most `k` colours and returns the mapped image as the same kind of thing you gave: a `Uint8Array`
|
|
537
500
|
* for a `Uint8Array`, `ImageData` for `ImageData`, an object with the same `format` for a `RawImage` (`ImageResult`; a
|
|
@@ -542,22 +505,10 @@ export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInf
|
|
|
542
505
|
*/
|
|
543
506
|
export function quantize<I extends ImageLike>(image: I, k: number, options?: QuantizeOptions): Promise<ImageResult<I>>;
|
|
544
507
|
|
|
545
|
-
/**
|
|
546
|
-
* Maps `image` to the `k`-colour cut of a clustering you already have, so trying another `k` or another image mapping
|
|
547
|
-
* costs milliseconds. Matches in the clustering's colour space unless `colorSpace` is given. Returns the same kind of
|
|
548
|
-
* thing as `quantize`.
|
|
549
|
-
*
|
|
550
|
-
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
551
|
-
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
552
|
-
*
|
|
553
|
-
* @deprecated Use `clustering.quantize(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantize(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
554
|
-
*/
|
|
555
|
-
export function quantizeFromClustering<I extends ImageLike>(image: I, clustering: Clustering, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
|
|
556
|
-
|
|
557
508
|
/**
|
|
558
509
|
* Maps each pixel of `image` to its nearest colour in a palette you supply (an edited swatch, a brand palette, one cut
|
|
559
510
|
* from a clustering). Pixels are matched in the palette's own colour space if it is a `Palette` (one this library made),
|
|
560
|
-
* so an OKLab palette maps the way `
|
|
511
|
+
* so an OKLab palette maps the way `clustering.quantize` does; plain bytes carry no space and are matched in RGB. Name a
|
|
561
512
|
* `colorSpace` to override either. Returns the same kind of thing as `quantize`.
|
|
562
513
|
*/
|
|
563
514
|
export function quantizeWithPalette<I extends ImageLike>(image: I, palette: PaletteLike, options?: MappingOptions): Promise<ImageResult<I>>;
|
|
@@ -574,18 +525,6 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
|
|
|
574
525
|
*/
|
|
575
526
|
export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
|
|
576
527
|
|
|
577
|
-
/**
|
|
578
|
-
* Like `quantizeFromClustering`, but returns palette indices. The palette is `clustering.getPalette(k)`'s.
|
|
579
|
-
*
|
|
580
|
-
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
|
581
|
-
* if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
|
|
582
|
-
* A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
|
|
583
|
-
* `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
|
|
584
|
-
*
|
|
585
|
-
* @deprecated Use `clustering.quantizeToIndices(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantizeToIndices(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
586
|
-
*/
|
|
587
|
-
export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
588
|
-
|
|
589
528
|
/** Like `quantizeWithPalette`, but returns indices into `palette`, which is returned too. */
|
|
590
529
|
export function quantizeToIndicesWithPalette(image: ImageLike, palette: PaletteLike, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
591
530
|
export {};
|