agglomerative-clustering 1.0.3 â 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -23
- package/dist/clustering.js +2 -14
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +152 -33
- package/dist/index.d.ts +28 -0
- package/dist/index.mjs +152 -33
- package/package.json +11 -5
package/README.md
CHANGED
|
@@ -10,7 +10,8 @@ It includes an interface for performing image clustering, palette extraction, an
|
|
|
10
10
|
- đ¨ Generate color palettes from raw images or clustering
|
|
11
11
|
- âī¸ Quantize images using clustering or palette data
|
|
12
12
|
- đšī¸ Async interface with lazy WASM initialization
|
|
13
|
-
- đž Works
|
|
13
|
+
- đž Works with `Uint8Array`, `Uint8ClampedArray`, and `ImageData` inputs (`rgb` or `rgba`)
|
|
14
|
+
- đĻ TypeScript declarations included
|
|
14
15
|
|
|
15
16
|
## Installation
|
|
16
17
|
|
|
@@ -18,44 +19,104 @@ It includes an interface for performing image clustering, palette extraction, an
|
|
|
18
19
|
npm install agglomerative-clustering
|
|
19
20
|
```
|
|
20
21
|
|
|
22
|
+
## Input types
|
|
23
|
+
|
|
24
|
+
All functions that accept an image accept any of the following input types:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// Plain raw RGBA buffer â format defaults to 'rgba'
|
|
28
|
+
Uint8Array
|
|
29
|
+
|
|
30
|
+
// Browser Canvas ImageData â always treated as 'rgba'
|
|
31
|
+
ImageData
|
|
32
|
+
|
|
33
|
+
// Explicit format object â use this for 'rgb' data or Uint8ClampedArray buffers
|
|
34
|
+
{ data: Uint8Array | Uint8ClampedArray, format: 'rgb' | 'rgba' }
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The three `quantize*` functions mirror the input type in their return value: passing a `Uint8Array` returns a `Uint8Array`, passing an `ImageData` returns an `ImageData`, and passing an object returns an object with the same `format`.
|
|
38
|
+
|
|
21
39
|
## Usage
|
|
40
|
+
|
|
41
|
+
### Node.js (with sharp)
|
|
42
|
+
|
|
22
43
|
```js
|
|
23
44
|
import { quantize } from 'agglomerative-clustering';
|
|
24
45
|
import sharp from 'sharp';
|
|
25
46
|
|
|
26
47
|
async function loadImage(path) {
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
return { width: info.width, height: info.height, data: data }
|
|
48
|
+
const { data, info } = await sharp(path).raw().ensureAlpha().toBuffer({ resolveWithObject: true });
|
|
49
|
+
return { width: info.width, height: info.height, data: new Uint8Array(data.buffer) };
|
|
30
50
|
}
|
|
31
51
|
|
|
32
52
|
async function saveImage(path, width, height, data) {
|
|
33
|
-
await sharp(data, {
|
|
34
|
-
raw: {
|
|
35
|
-
width: width,
|
|
36
|
-
height: height,
|
|
37
|
-
channels: 4,
|
|
38
|
-
}
|
|
39
|
-
}).toFile(path);
|
|
53
|
+
await sharp(data, { raw: { width, height, channels: 4 } }).toFile(path);
|
|
40
54
|
}
|
|
41
55
|
|
|
42
56
|
(async () => {
|
|
43
57
|
|
|
44
|
-
// Number of clusters
|
|
45
58
|
const k = 8;
|
|
46
|
-
|
|
47
|
-
// Load the image
|
|
48
59
|
const { width, height, data } = await loadImage('example.png');
|
|
49
|
-
const array = new Uint8Array(data.length);
|
|
50
|
-
array.set(data);
|
|
51
60
|
|
|
52
|
-
//
|
|
53
|
-
const processed = await quantize(
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
// Save the result
|
|
57
|
-
await saveImage('example_quantized.png', width, height, buffer);
|
|
61
|
+
// Quantize â result is the same type as the input (Uint8Array here)
|
|
62
|
+
const processed = await quantize(data, k);
|
|
63
|
+
|
|
64
|
+
await saveImage('example_quantized.png', width, height, Buffer.from(processed));
|
|
58
65
|
|
|
59
66
|
})();
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Browser (with Canvas)
|
|
70
|
+
|
|
71
|
+
```js
|
|
72
|
+
import { quantize } from 'agglomerative-clustering';
|
|
73
|
+
|
|
74
|
+
const canvas = document.getElementById('canvas');
|
|
75
|
+
const ctx = canvas.getContext('2d');
|
|
76
|
+
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
77
|
+
|
|
78
|
+
// Pass ImageData directly â result is a new ImageData with the same dimensions
|
|
79
|
+
const result = await quantize(imageData, 8);
|
|
80
|
+
ctx.putImageData(result, 0, 0);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Reusing clustering across multiple palette sizes
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
import { getClustering, getPaletteFromClustering, quantizeWithClustering } from 'agglomerative-clustering';
|
|
87
|
+
|
|
88
|
+
const data = new Uint8Array(/* raw rgba bytes */);
|
|
89
|
+
|
|
90
|
+
// Compute clustering once
|
|
91
|
+
const clustering = await getClustering(data);
|
|
92
|
+
|
|
93
|
+
// Derive different palette sizes without recomputing the clustering
|
|
94
|
+
const palette4 = await getPaletteFromClustering(clustering, 4);
|
|
95
|
+
const palette16 = await getPaletteFromClustering(clustering, 16);
|
|
96
|
+
|
|
97
|
+
// Quantize using the precomputed clustering
|
|
98
|
+
const quantized = await quantizeWithClustering(data, clustering, 8);
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## API
|
|
102
|
+
|
|
103
|
+
### `init(): Promise<void>`
|
|
104
|
+
Pre-initializes the WASM module. All other functions call this lazily, so explicit use is optional â useful for warming up the module before processing a batch of images.
|
|
105
|
+
|
|
106
|
+
### `getClustering(image): Promise<Uint8Array>`
|
|
107
|
+
Computes a compact hierarchical clustering from the image's color histogram. The result can be passed to `getPaletteFromClustering` or `quantizeWithClustering` to avoid redundant work.
|
|
108
|
+
|
|
109
|
+
### `getPalette(image, k): Promise<Uint8Array>`
|
|
110
|
+
Returns a palette of up to `k` colors as a flat RGB byte array (`k * 3` bytes).
|
|
111
|
+
|
|
112
|
+
### `getPaletteFromClustering(clustering, k): Promise<Uint8Array>`
|
|
113
|
+
Derives a palette of up to `k` colors from a precomputed clustering.
|
|
114
|
+
|
|
115
|
+
### `quantize(image, k): Promise<Uint8Array | ImageData | RawImage>`
|
|
116
|
+
Quantizes the image to at most `k` colors. Return type matches the input type.
|
|
117
|
+
|
|
118
|
+
### `quantizeWithClustering(image, clustering, k): Promise<Uint8Array | ImageData | RawImage>`
|
|
119
|
+
Quantizes using a precomputed clustering. Return type matches the input type.
|
|
60
120
|
|
|
61
|
-
|
|
121
|
+
### `quantizeWithPalette(image, palette): Promise<Uint8Array | ImageData | RawImage>`
|
|
122
|
+
Quantizes using an already-computed palette. Return type matches the input type.
|
package/dist/clustering.js
CHANGED
|
@@ -1,14 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
return (
|
|
4
|
-
async function(moduleArg = {}) {
|
|
5
|
-
var moduleRtn;
|
|
6
|
-
|
|
7
|
-
var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("module");var require=createRequire(import.meta.url)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(_scriptName.startsWith("file:")){scriptDirectory=nodePath.dirname(require("url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var wasmMemory;var ABORT=false;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;var isFileURI=filename=>filename.startsWith("file://");function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["e"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["d"];updateMemoryViews();removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{resolve(receiveInstance(mod,inst))})})}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}catch(e){readyPromiseReject(e);return Promise.reject(e)}}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var __abort_js=()=>abort("");var abortOnCannotGrowMemory=requestedSize=>{abort("OOM")};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;abortOnCannotGrowMemory(requestedSize)};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"]}var wasmImports={a:___cxa_throw,b:__abort_js,c:_emscripten_resize_heap};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["e"];var _malloc=Module["_malloc"]=wasmExports["f"];var _get_clustering=Module["_get_clustering"]=wasmExports["g"];var _get_palette=Module["_get_palette"]=wasmExports["h"];var _get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["i"];var _quantize=Module["_quantize"]=wasmExports["j"];var _quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["k"];var _quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["l"];var _free=Module["_free"]=wasmExports["m"];function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}function preInit(){if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}preInit();run();moduleRtn=readyPromise;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
return moduleRtn;
|
|
11
|
-
}
|
|
12
|
-
);
|
|
13
|
-
})();
|
|
14
|
-
export default createWasmModule;
|
|
1
|
+
async function createWasmModule(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("node:module");var require=createRequire(import.meta.url)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var readyPromiseResolve,readyPromiseReject;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["e"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP16;var HEAP32;var HEAP64;var HEAP8;var HEAPF32;var HEAPF64;var HEAPU16;var HEAPU32;var HEAPU64;var HEAPU8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;abort()};var __abort_js=()=>abort("");var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}var _malloc,_get_clustering,_get_palette,_get_palette_from_clustering,_quantize,_quantize_with_clustering,_quantize_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["f"];_get_clustering=Module["_get_clustering"]=wasmExports["g"];_get_palette=Module["_get_palette"]=wasmExports["h"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["i"];_quantize=Module["_quantize"]=wasmExports["j"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["k"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["l"];_free=Module["_free"]=wasmExports["m"];memory=wasmMemory=wasmExports["d"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={a:___cxa_throw,b:__abort_js,c:_emscripten_resize_heap};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
|
|
2
|
+
;return moduleRtn}export default createWasmModule;
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|
package/dist/index.cjs
CHANGED
|
@@ -51,16 +51,46 @@ var load = function load(image) {
|
|
|
51
51
|
format: 'rgba'
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
|
+
if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
|
|
55
|
+
return {
|
|
56
|
+
data: new Uint8Array(image.data.buffer),
|
|
57
|
+
format: 'rgba'
|
|
58
|
+
};
|
|
59
|
+
}
|
|
54
60
|
if (_typeof(image) !== 'object' || !image || !image.data || !image.format) {
|
|
55
61
|
throw new Error("Invalid image: expected object with `data` and `format`.");
|
|
56
62
|
}
|
|
57
|
-
if (!(image.data instanceof Uint8Array)) {
|
|
58
|
-
throw new Error("Invalid image data: must be Uint8Array.");
|
|
63
|
+
if (!(image.data instanceof Uint8Array) && !(image.data instanceof Uint8ClampedArray)) {
|
|
64
|
+
throw new Error("Invalid image data: must be Uint8Array or Uint8ClampedArray.");
|
|
59
65
|
}
|
|
60
66
|
if (!Object.keys(codes).includes(image.format)) {
|
|
61
67
|
throw new Error("Invalid format: must be 'rgb' or 'rgba'.");
|
|
62
68
|
}
|
|
63
|
-
return
|
|
69
|
+
return {
|
|
70
|
+
data: image.data instanceof Uint8ClampedArray ? new Uint8Array(image.data.buffer) : image.data,
|
|
71
|
+
format: image.format
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
var getWrapper = function getWrapper(image) {
|
|
75
|
+
if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
|
|
76
|
+
var width = image.width,
|
|
77
|
+
height = image.height;
|
|
78
|
+
return function (output) {
|
|
79
|
+
return new ImageData(new Uint8ClampedArray(output.buffer), width, height);
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
if (!(image instanceof Uint8Array) && _typeof(image) === 'object' && image && image.data && image.format) {
|
|
83
|
+
var format = image.format;
|
|
84
|
+
return function (output) {
|
|
85
|
+
return {
|
|
86
|
+
data: output,
|
|
87
|
+
format: format
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return function (output) {
|
|
92
|
+
return output;
|
|
93
|
+
};
|
|
64
94
|
};
|
|
65
95
|
var check = function check(k) {
|
|
66
96
|
if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
|
|
@@ -69,7 +99,7 @@ var check = function check(k) {
|
|
|
69
99
|
};
|
|
70
100
|
var getClustering = exports.getClustering = /*#__PURE__*/function () {
|
|
71
101
|
var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(image) {
|
|
72
|
-
var imagePointer, outputPointer
|
|
102
|
+
var imagePointer, outputPointer;
|
|
73
103
|
return _regenerator().w(function (_context2) {
|
|
74
104
|
while (1) switch (_context2.n) {
|
|
75
105
|
case 0:
|
|
@@ -78,14 +108,26 @@ var getClustering = exports.getClustering = /*#__PURE__*/function () {
|
|
|
78
108
|
case 1:
|
|
79
109
|
image = load(image);
|
|
80
110
|
imagePointer = Module._malloc(image.data.length);
|
|
111
|
+
if (imagePointer) {
|
|
112
|
+
_context2.n = 2;
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
116
|
+
case 2:
|
|
117
|
+
outputPointer = 0;
|
|
118
|
+
_context2.p = 3;
|
|
81
119
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
82
120
|
outputPointer = Module._get_clustering(imagePointer, image.data.length, codes[image.format]);
|
|
83
|
-
|
|
121
|
+
return _context2.a(2, unpack(outputPointer));
|
|
122
|
+
case 4:
|
|
123
|
+
_context2.p = 4;
|
|
84
124
|
Module._free(imagePointer);
|
|
85
|
-
Module._free(outputPointer);
|
|
86
|
-
return _context2.
|
|
125
|
+
if (outputPointer) Module._free(outputPointer);
|
|
126
|
+
return _context2.f(4);
|
|
127
|
+
case 5:
|
|
128
|
+
return _context2.a(2);
|
|
87
129
|
}
|
|
88
|
-
}, _callee2);
|
|
130
|
+
}, _callee2, null, [[3,, 4, 5]]);
|
|
89
131
|
}));
|
|
90
132
|
return function getClustering(_x) {
|
|
91
133
|
return _ref2.apply(this, arguments);
|
|
@@ -93,7 +135,7 @@ var getClustering = exports.getClustering = /*#__PURE__*/function () {
|
|
|
93
135
|
}();
|
|
94
136
|
var getPalette = exports.getPalette = /*#__PURE__*/function () {
|
|
95
137
|
var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(image, k) {
|
|
96
|
-
var imagePointer, outputPointer
|
|
138
|
+
var imagePointer, outputPointer;
|
|
97
139
|
return _regenerator().w(function (_context3) {
|
|
98
140
|
while (1) switch (_context3.n) {
|
|
99
141
|
case 0:
|
|
@@ -103,14 +145,26 @@ var getPalette = exports.getPalette = /*#__PURE__*/function () {
|
|
|
103
145
|
image = load(image);
|
|
104
146
|
check(k);
|
|
105
147
|
imagePointer = Module._malloc(image.data.length);
|
|
148
|
+
if (imagePointer) {
|
|
149
|
+
_context3.n = 2;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
153
|
+
case 2:
|
|
154
|
+
outputPointer = 0;
|
|
155
|
+
_context3.p = 3;
|
|
106
156
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
107
157
|
outputPointer = Module._get_palette(imagePointer, image.data.length, codes[image.format], k);
|
|
108
|
-
|
|
158
|
+
return _context3.a(2, unpack(outputPointer));
|
|
159
|
+
case 4:
|
|
160
|
+
_context3.p = 4;
|
|
109
161
|
Module._free(imagePointer);
|
|
110
|
-
Module._free(outputPointer);
|
|
111
|
-
return _context3.
|
|
162
|
+
if (outputPointer) Module._free(outputPointer);
|
|
163
|
+
return _context3.f(4);
|
|
164
|
+
case 5:
|
|
165
|
+
return _context3.a(2);
|
|
112
166
|
}
|
|
113
|
-
}, _callee3);
|
|
167
|
+
}, _callee3, null, [[3,, 4, 5]]);
|
|
114
168
|
}));
|
|
115
169
|
return function getPalette(_x2, _x3) {
|
|
116
170
|
return _ref3.apply(this, arguments);
|
|
@@ -118,7 +172,7 @@ var getPalette = exports.getPalette = /*#__PURE__*/function () {
|
|
|
118
172
|
}();
|
|
119
173
|
var getPaletteFromClustering = exports.getPaletteFromClustering = /*#__PURE__*/function () {
|
|
120
174
|
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(clustering, k) {
|
|
121
|
-
var clusteringPointer, outputPointer
|
|
175
|
+
var clusteringPointer, outputPointer;
|
|
122
176
|
return _regenerator().w(function (_context4) {
|
|
123
177
|
while (1) switch (_context4.n) {
|
|
124
178
|
case 0:
|
|
@@ -127,14 +181,26 @@ var getPaletteFromClustering = exports.getPaletteFromClustering = /*#__PURE__*/f
|
|
|
127
181
|
case 1:
|
|
128
182
|
check(k);
|
|
129
183
|
clusteringPointer = Module._malloc(clustering.length);
|
|
184
|
+
if (clusteringPointer) {
|
|
185
|
+
_context4.n = 2;
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
189
|
+
case 2:
|
|
190
|
+
outputPointer = 0;
|
|
191
|
+
_context4.p = 3;
|
|
130
192
|
Module.HEAPU8.set(clustering, clusteringPointer);
|
|
131
193
|
outputPointer = Module._get_palette_from_clustering(clusteringPointer, clustering.length, k);
|
|
132
|
-
|
|
194
|
+
return _context4.a(2, unpack(outputPointer));
|
|
195
|
+
case 4:
|
|
196
|
+
_context4.p = 4;
|
|
133
197
|
Module._free(clusteringPointer);
|
|
134
|
-
Module._free(outputPointer);
|
|
135
|
-
return _context4.
|
|
198
|
+
if (outputPointer) Module._free(outputPointer);
|
|
199
|
+
return _context4.f(4);
|
|
200
|
+
case 5:
|
|
201
|
+
return _context4.a(2);
|
|
136
202
|
}
|
|
137
|
-
}, _callee4);
|
|
203
|
+
}, _callee4, null, [[3,, 4, 5]]);
|
|
138
204
|
}));
|
|
139
205
|
return function getPaletteFromClustering(_x4, _x5) {
|
|
140
206
|
return _ref4.apply(this, arguments);
|
|
@@ -142,24 +208,37 @@ var getPaletteFromClustering = exports.getPaletteFromClustering = /*#__PURE__*/f
|
|
|
142
208
|
}();
|
|
143
209
|
var quantize = exports.quantize = /*#__PURE__*/function () {
|
|
144
210
|
var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(image, k) {
|
|
145
|
-
var imagePointer, outputPointer
|
|
211
|
+
var wrap, imagePointer, outputPointer;
|
|
146
212
|
return _regenerator().w(function (_context5) {
|
|
147
213
|
while (1) switch (_context5.n) {
|
|
148
214
|
case 0:
|
|
149
215
|
_context5.n = 1;
|
|
150
216
|
return init();
|
|
151
217
|
case 1:
|
|
218
|
+
wrap = getWrapper(image);
|
|
152
219
|
image = load(image);
|
|
153
220
|
check(k);
|
|
154
221
|
imagePointer = Module._malloc(image.data.length);
|
|
222
|
+
if (imagePointer) {
|
|
223
|
+
_context5.n = 2;
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
227
|
+
case 2:
|
|
228
|
+
outputPointer = 0;
|
|
229
|
+
_context5.p = 3;
|
|
155
230
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
156
231
|
outputPointer = Module._quantize(imagePointer, image.data.length, codes[image.format], k);
|
|
157
|
-
|
|
232
|
+
return _context5.a(2, wrap(unpack(outputPointer)));
|
|
233
|
+
case 4:
|
|
234
|
+
_context5.p = 4;
|
|
158
235
|
Module._free(imagePointer);
|
|
159
|
-
Module._free(outputPointer);
|
|
160
|
-
return _context5.
|
|
236
|
+
if (outputPointer) Module._free(outputPointer);
|
|
237
|
+
return _context5.f(4);
|
|
238
|
+
case 5:
|
|
239
|
+
return _context5.a(2);
|
|
161
240
|
}
|
|
162
|
-
}, _callee5);
|
|
241
|
+
}, _callee5, null, [[3,, 4, 5]]);
|
|
163
242
|
}));
|
|
164
243
|
return function quantize(_x6, _x7) {
|
|
165
244
|
return _ref5.apply(this, arguments);
|
|
@@ -167,27 +246,47 @@ var quantize = exports.quantize = /*#__PURE__*/function () {
|
|
|
167
246
|
}();
|
|
168
247
|
var quantizeWithClustering = exports.quantizeWithClustering = /*#__PURE__*/function () {
|
|
169
248
|
var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, clustering, k) {
|
|
170
|
-
var imagePointer, clusteringPointer, outputPointer
|
|
249
|
+
var wrap, imagePointer, clusteringPointer, outputPointer;
|
|
171
250
|
return _regenerator().w(function (_context6) {
|
|
172
251
|
while (1) switch (_context6.n) {
|
|
173
252
|
case 0:
|
|
174
253
|
_context6.n = 1;
|
|
175
254
|
return init();
|
|
176
255
|
case 1:
|
|
256
|
+
wrap = getWrapper(image);
|
|
177
257
|
image = load(image);
|
|
178
258
|
check(k);
|
|
179
259
|
imagePointer = Module._malloc(image.data.length);
|
|
260
|
+
if (imagePointer) {
|
|
261
|
+
_context6.n = 2;
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
265
|
+
case 2:
|
|
180
266
|
clusteringPointer = Module._malloc(clustering.length);
|
|
267
|
+
if (clusteringPointer) {
|
|
268
|
+
_context6.n = 3;
|
|
269
|
+
break;
|
|
270
|
+
}
|
|
271
|
+
Module._free(imagePointer);
|
|
272
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
273
|
+
case 3:
|
|
274
|
+
outputPointer = 0;
|
|
275
|
+
_context6.p = 4;
|
|
181
276
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
182
277
|
Module.HEAPU8.set(clustering, clusteringPointer);
|
|
183
278
|
outputPointer = Module._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k);
|
|
184
|
-
|
|
279
|
+
return _context6.a(2, wrap(unpack(outputPointer)));
|
|
280
|
+
case 5:
|
|
281
|
+
_context6.p = 5;
|
|
185
282
|
Module._free(imagePointer);
|
|
186
283
|
Module._free(clusteringPointer);
|
|
187
|
-
Module._free(outputPointer);
|
|
188
|
-
return _context6.
|
|
284
|
+
if (outputPointer) Module._free(outputPointer);
|
|
285
|
+
return _context6.f(5);
|
|
286
|
+
case 6:
|
|
287
|
+
return _context6.a(2);
|
|
189
288
|
}
|
|
190
|
-
}, _callee6);
|
|
289
|
+
}, _callee6, null, [[4,, 5, 6]]);
|
|
191
290
|
}));
|
|
192
291
|
return function quantizeWithClustering(_x8, _x9, _x0) {
|
|
193
292
|
return _ref6.apply(this, arguments);
|
|
@@ -195,26 +294,46 @@ var quantizeWithClustering = exports.quantizeWithClustering = /*#__PURE__*/funct
|
|
|
195
294
|
}();
|
|
196
295
|
var quantizeWithPalette = exports.quantizeWithPalette = /*#__PURE__*/function () {
|
|
197
296
|
var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(image, palette) {
|
|
198
|
-
var imagePointer, palettePointer, outputPointer
|
|
297
|
+
var wrap, imagePointer, palettePointer, outputPointer;
|
|
199
298
|
return _regenerator().w(function (_context7) {
|
|
200
299
|
while (1) switch (_context7.n) {
|
|
201
300
|
case 0:
|
|
202
301
|
_context7.n = 1;
|
|
203
302
|
return init();
|
|
204
303
|
case 1:
|
|
304
|
+
wrap = getWrapper(image);
|
|
205
305
|
image = load(image);
|
|
206
306
|
imagePointer = Module._malloc(image.data.length);
|
|
307
|
+
if (imagePointer) {
|
|
308
|
+
_context7.n = 2;
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
312
|
+
case 2:
|
|
207
313
|
palettePointer = Module._malloc(palette.length);
|
|
314
|
+
if (palettePointer) {
|
|
315
|
+
_context7.n = 3;
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
Module._free(imagePointer);
|
|
319
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
320
|
+
case 3:
|
|
321
|
+
outputPointer = 0;
|
|
322
|
+
_context7.p = 4;
|
|
208
323
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
209
324
|
Module.HEAPU8.set(palette, palettePointer);
|
|
210
325
|
outputPointer = Module._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length);
|
|
211
|
-
|
|
326
|
+
return _context7.a(2, wrap(unpack(outputPointer)));
|
|
327
|
+
case 5:
|
|
328
|
+
_context7.p = 5;
|
|
212
329
|
Module._free(imagePointer);
|
|
213
330
|
Module._free(palettePointer);
|
|
214
|
-
Module._free(outputPointer);
|
|
215
|
-
return _context7.
|
|
331
|
+
if (outputPointer) Module._free(outputPointer);
|
|
332
|
+
return _context7.f(5);
|
|
333
|
+
case 6:
|
|
334
|
+
return _context7.a(2);
|
|
216
335
|
}
|
|
217
|
-
}, _callee7);
|
|
336
|
+
}, _callee7, null, [[4,, 5, 6]]);
|
|
218
337
|
}));
|
|
219
338
|
return function quantizeWithPalette(_x1, _x10) {
|
|
220
339
|
return _ref7.apply(this, arguments);
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export type ImageFormat = 'rgb' | 'rgba';
|
|
2
|
+
|
|
3
|
+
export interface RawImage {
|
|
4
|
+
data: Uint8Array | Uint8ClampedArray;
|
|
5
|
+
format: ImageFormat;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type ImageLike = Uint8Array | ImageData | RawImage;
|
|
9
|
+
|
|
10
|
+
export function init(): Promise<void>;
|
|
11
|
+
|
|
12
|
+
export function getClustering(image: ImageLike): Promise<Uint8Array>;
|
|
13
|
+
|
|
14
|
+
export function getPalette(image: ImageLike, k: number): Promise<Uint8Array>;
|
|
15
|
+
|
|
16
|
+
export function getPaletteFromClustering(clustering: Uint8Array, k: number): Promise<Uint8Array>;
|
|
17
|
+
|
|
18
|
+
export function quantize(image: Uint8Array, k: number): Promise<Uint8Array>;
|
|
19
|
+
export function quantize(image: ImageData, k: number): Promise<ImageData>;
|
|
20
|
+
export function quantize(image: RawImage, k: number): Promise<RawImage>;
|
|
21
|
+
|
|
22
|
+
export function quantizeWithClustering(image: Uint8Array, clustering: Uint8Array, k: number): Promise<Uint8Array>;
|
|
23
|
+
export function quantizeWithClustering(image: ImageData, clustering: Uint8Array, k: number): Promise<ImageData>;
|
|
24
|
+
export function quantizeWithClustering(image: RawImage, clustering: Uint8Array, k: number): Promise<RawImage>;
|
|
25
|
+
|
|
26
|
+
export function quantizeWithPalette(image: Uint8Array, palette: Uint8Array): Promise<Uint8Array>;
|
|
27
|
+
export function quantizeWithPalette(image: ImageData, palette: Uint8Array): Promise<ImageData>;
|
|
28
|
+
export function quantizeWithPalette(image: RawImage, palette: Uint8Array): Promise<RawImage>;
|
package/dist/index.mjs
CHANGED
|
@@ -44,16 +44,46 @@ var load = function load(image) {
|
|
|
44
44
|
format: 'rgba'
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
|
+
if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
|
|
48
|
+
return {
|
|
49
|
+
data: new Uint8Array(image.data.buffer),
|
|
50
|
+
format: 'rgba'
|
|
51
|
+
};
|
|
52
|
+
}
|
|
47
53
|
if (_typeof(image) !== 'object' || !image || !image.data || !image.format) {
|
|
48
54
|
throw new Error("Invalid image: expected object with `data` and `format`.");
|
|
49
55
|
}
|
|
50
|
-
if (!(image.data instanceof Uint8Array)) {
|
|
51
|
-
throw new Error("Invalid image data: must be Uint8Array.");
|
|
56
|
+
if (!(image.data instanceof Uint8Array) && !(image.data instanceof Uint8ClampedArray)) {
|
|
57
|
+
throw new Error("Invalid image data: must be Uint8Array or Uint8ClampedArray.");
|
|
52
58
|
}
|
|
53
59
|
if (!Object.keys(codes).includes(image.format)) {
|
|
54
60
|
throw new Error("Invalid format: must be 'rgb' or 'rgba'.");
|
|
55
61
|
}
|
|
56
|
-
return
|
|
62
|
+
return {
|
|
63
|
+
data: image.data instanceof Uint8ClampedArray ? new Uint8Array(image.data.buffer) : image.data,
|
|
64
|
+
format: image.format
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
var getWrapper = function getWrapper(image) {
|
|
68
|
+
if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
|
|
69
|
+
var width = image.width,
|
|
70
|
+
height = image.height;
|
|
71
|
+
return function (output) {
|
|
72
|
+
return new ImageData(new Uint8ClampedArray(output.buffer), width, height);
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
if (!(image instanceof Uint8Array) && _typeof(image) === 'object' && image && image.data && image.format) {
|
|
76
|
+
var format = image.format;
|
|
77
|
+
return function (output) {
|
|
78
|
+
return {
|
|
79
|
+
data: output,
|
|
80
|
+
format: format
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
return function (output) {
|
|
85
|
+
return output;
|
|
86
|
+
};
|
|
57
87
|
};
|
|
58
88
|
var check = function check(k) {
|
|
59
89
|
if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
|
|
@@ -62,7 +92,7 @@ var check = function check(k) {
|
|
|
62
92
|
};
|
|
63
93
|
export var getClustering = /*#__PURE__*/function () {
|
|
64
94
|
var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(image) {
|
|
65
|
-
var imagePointer, outputPointer
|
|
95
|
+
var imagePointer, outputPointer;
|
|
66
96
|
return _regenerator().w(function (_context2) {
|
|
67
97
|
while (1) switch (_context2.n) {
|
|
68
98
|
case 0:
|
|
@@ -71,14 +101,26 @@ export var getClustering = /*#__PURE__*/function () {
|
|
|
71
101
|
case 1:
|
|
72
102
|
image = load(image);
|
|
73
103
|
imagePointer = Module._malloc(image.data.length);
|
|
104
|
+
if (imagePointer) {
|
|
105
|
+
_context2.n = 2;
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
109
|
+
case 2:
|
|
110
|
+
outputPointer = 0;
|
|
111
|
+
_context2.p = 3;
|
|
74
112
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
75
113
|
outputPointer = Module._get_clustering(imagePointer, image.data.length, codes[image.format]);
|
|
76
|
-
|
|
114
|
+
return _context2.a(2, unpack(outputPointer));
|
|
115
|
+
case 4:
|
|
116
|
+
_context2.p = 4;
|
|
77
117
|
Module._free(imagePointer);
|
|
78
|
-
Module._free(outputPointer);
|
|
79
|
-
return _context2.
|
|
118
|
+
if (outputPointer) Module._free(outputPointer);
|
|
119
|
+
return _context2.f(4);
|
|
120
|
+
case 5:
|
|
121
|
+
return _context2.a(2);
|
|
80
122
|
}
|
|
81
|
-
}, _callee2);
|
|
123
|
+
}, _callee2, null, [[3,, 4, 5]]);
|
|
82
124
|
}));
|
|
83
125
|
return function getClustering(_x) {
|
|
84
126
|
return _ref2.apply(this, arguments);
|
|
@@ -86,7 +128,7 @@ export var getClustering = /*#__PURE__*/function () {
|
|
|
86
128
|
}();
|
|
87
129
|
export var getPalette = /*#__PURE__*/function () {
|
|
88
130
|
var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(image, k) {
|
|
89
|
-
var imagePointer, outputPointer
|
|
131
|
+
var imagePointer, outputPointer;
|
|
90
132
|
return _regenerator().w(function (_context3) {
|
|
91
133
|
while (1) switch (_context3.n) {
|
|
92
134
|
case 0:
|
|
@@ -96,14 +138,26 @@ export var getPalette = /*#__PURE__*/function () {
|
|
|
96
138
|
image = load(image);
|
|
97
139
|
check(k);
|
|
98
140
|
imagePointer = Module._malloc(image.data.length);
|
|
141
|
+
if (imagePointer) {
|
|
142
|
+
_context3.n = 2;
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
146
|
+
case 2:
|
|
147
|
+
outputPointer = 0;
|
|
148
|
+
_context3.p = 3;
|
|
99
149
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
100
150
|
outputPointer = Module._get_palette(imagePointer, image.data.length, codes[image.format], k);
|
|
101
|
-
|
|
151
|
+
return _context3.a(2, unpack(outputPointer));
|
|
152
|
+
case 4:
|
|
153
|
+
_context3.p = 4;
|
|
102
154
|
Module._free(imagePointer);
|
|
103
|
-
Module._free(outputPointer);
|
|
104
|
-
return _context3.
|
|
155
|
+
if (outputPointer) Module._free(outputPointer);
|
|
156
|
+
return _context3.f(4);
|
|
157
|
+
case 5:
|
|
158
|
+
return _context3.a(2);
|
|
105
159
|
}
|
|
106
|
-
}, _callee3);
|
|
160
|
+
}, _callee3, null, [[3,, 4, 5]]);
|
|
107
161
|
}));
|
|
108
162
|
return function getPalette(_x2, _x3) {
|
|
109
163
|
return _ref3.apply(this, arguments);
|
|
@@ -111,7 +165,7 @@ export var getPalette = /*#__PURE__*/function () {
|
|
|
111
165
|
}();
|
|
112
166
|
export var getPaletteFromClustering = /*#__PURE__*/function () {
|
|
113
167
|
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(clustering, k) {
|
|
114
|
-
var clusteringPointer, outputPointer
|
|
168
|
+
var clusteringPointer, outputPointer;
|
|
115
169
|
return _regenerator().w(function (_context4) {
|
|
116
170
|
while (1) switch (_context4.n) {
|
|
117
171
|
case 0:
|
|
@@ -120,14 +174,26 @@ export var getPaletteFromClustering = /*#__PURE__*/function () {
|
|
|
120
174
|
case 1:
|
|
121
175
|
check(k);
|
|
122
176
|
clusteringPointer = Module._malloc(clustering.length);
|
|
177
|
+
if (clusteringPointer) {
|
|
178
|
+
_context4.n = 2;
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
182
|
+
case 2:
|
|
183
|
+
outputPointer = 0;
|
|
184
|
+
_context4.p = 3;
|
|
123
185
|
Module.HEAPU8.set(clustering, clusteringPointer);
|
|
124
186
|
outputPointer = Module._get_palette_from_clustering(clusteringPointer, clustering.length, k);
|
|
125
|
-
|
|
187
|
+
return _context4.a(2, unpack(outputPointer));
|
|
188
|
+
case 4:
|
|
189
|
+
_context4.p = 4;
|
|
126
190
|
Module._free(clusteringPointer);
|
|
127
|
-
Module._free(outputPointer);
|
|
128
|
-
return _context4.
|
|
191
|
+
if (outputPointer) Module._free(outputPointer);
|
|
192
|
+
return _context4.f(4);
|
|
193
|
+
case 5:
|
|
194
|
+
return _context4.a(2);
|
|
129
195
|
}
|
|
130
|
-
}, _callee4);
|
|
196
|
+
}, _callee4, null, [[3,, 4, 5]]);
|
|
131
197
|
}));
|
|
132
198
|
return function getPaletteFromClustering(_x4, _x5) {
|
|
133
199
|
return _ref4.apply(this, arguments);
|
|
@@ -135,24 +201,37 @@ export var getPaletteFromClustering = /*#__PURE__*/function () {
|
|
|
135
201
|
}();
|
|
136
202
|
export var quantize = /*#__PURE__*/function () {
|
|
137
203
|
var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(image, k) {
|
|
138
|
-
var imagePointer, outputPointer
|
|
204
|
+
var wrap, imagePointer, outputPointer;
|
|
139
205
|
return _regenerator().w(function (_context5) {
|
|
140
206
|
while (1) switch (_context5.n) {
|
|
141
207
|
case 0:
|
|
142
208
|
_context5.n = 1;
|
|
143
209
|
return init();
|
|
144
210
|
case 1:
|
|
211
|
+
wrap = getWrapper(image);
|
|
145
212
|
image = load(image);
|
|
146
213
|
check(k);
|
|
147
214
|
imagePointer = Module._malloc(image.data.length);
|
|
215
|
+
if (imagePointer) {
|
|
216
|
+
_context5.n = 2;
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
220
|
+
case 2:
|
|
221
|
+
outputPointer = 0;
|
|
222
|
+
_context5.p = 3;
|
|
148
223
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
149
224
|
outputPointer = Module._quantize(imagePointer, image.data.length, codes[image.format], k);
|
|
150
|
-
|
|
225
|
+
return _context5.a(2, wrap(unpack(outputPointer)));
|
|
226
|
+
case 4:
|
|
227
|
+
_context5.p = 4;
|
|
151
228
|
Module._free(imagePointer);
|
|
152
|
-
Module._free(outputPointer);
|
|
153
|
-
return _context5.
|
|
229
|
+
if (outputPointer) Module._free(outputPointer);
|
|
230
|
+
return _context5.f(4);
|
|
231
|
+
case 5:
|
|
232
|
+
return _context5.a(2);
|
|
154
233
|
}
|
|
155
|
-
}, _callee5);
|
|
234
|
+
}, _callee5, null, [[3,, 4, 5]]);
|
|
156
235
|
}));
|
|
157
236
|
return function quantize(_x6, _x7) {
|
|
158
237
|
return _ref5.apply(this, arguments);
|
|
@@ -160,27 +239,47 @@ export var quantize = /*#__PURE__*/function () {
|
|
|
160
239
|
}();
|
|
161
240
|
export var quantizeWithClustering = /*#__PURE__*/function () {
|
|
162
241
|
var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, clustering, k) {
|
|
163
|
-
var imagePointer, clusteringPointer, outputPointer
|
|
242
|
+
var wrap, imagePointer, clusteringPointer, outputPointer;
|
|
164
243
|
return _regenerator().w(function (_context6) {
|
|
165
244
|
while (1) switch (_context6.n) {
|
|
166
245
|
case 0:
|
|
167
246
|
_context6.n = 1;
|
|
168
247
|
return init();
|
|
169
248
|
case 1:
|
|
249
|
+
wrap = getWrapper(image);
|
|
170
250
|
image = load(image);
|
|
171
251
|
check(k);
|
|
172
252
|
imagePointer = Module._malloc(image.data.length);
|
|
253
|
+
if (imagePointer) {
|
|
254
|
+
_context6.n = 2;
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
258
|
+
case 2:
|
|
173
259
|
clusteringPointer = Module._malloc(clustering.length);
|
|
260
|
+
if (clusteringPointer) {
|
|
261
|
+
_context6.n = 3;
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
Module._free(imagePointer);
|
|
265
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
266
|
+
case 3:
|
|
267
|
+
outputPointer = 0;
|
|
268
|
+
_context6.p = 4;
|
|
174
269
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
175
270
|
Module.HEAPU8.set(clustering, clusteringPointer);
|
|
176
271
|
outputPointer = Module._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k);
|
|
177
|
-
|
|
272
|
+
return _context6.a(2, wrap(unpack(outputPointer)));
|
|
273
|
+
case 5:
|
|
274
|
+
_context6.p = 5;
|
|
178
275
|
Module._free(imagePointer);
|
|
179
276
|
Module._free(clusteringPointer);
|
|
180
|
-
Module._free(outputPointer);
|
|
181
|
-
return _context6.
|
|
277
|
+
if (outputPointer) Module._free(outputPointer);
|
|
278
|
+
return _context6.f(5);
|
|
279
|
+
case 6:
|
|
280
|
+
return _context6.a(2);
|
|
182
281
|
}
|
|
183
|
-
}, _callee6);
|
|
282
|
+
}, _callee6, null, [[4,, 5, 6]]);
|
|
184
283
|
}));
|
|
185
284
|
return function quantizeWithClustering(_x8, _x9, _x0) {
|
|
186
285
|
return _ref6.apply(this, arguments);
|
|
@@ -188,26 +287,46 @@ export var quantizeWithClustering = /*#__PURE__*/function () {
|
|
|
188
287
|
}();
|
|
189
288
|
export var quantizeWithPalette = /*#__PURE__*/function () {
|
|
190
289
|
var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(image, palette) {
|
|
191
|
-
var imagePointer, palettePointer, outputPointer
|
|
290
|
+
var wrap, imagePointer, palettePointer, outputPointer;
|
|
192
291
|
return _regenerator().w(function (_context7) {
|
|
193
292
|
while (1) switch (_context7.n) {
|
|
194
293
|
case 0:
|
|
195
294
|
_context7.n = 1;
|
|
196
295
|
return init();
|
|
197
296
|
case 1:
|
|
297
|
+
wrap = getWrapper(image);
|
|
198
298
|
image = load(image);
|
|
199
299
|
imagePointer = Module._malloc(image.data.length);
|
|
300
|
+
if (imagePointer) {
|
|
301
|
+
_context7.n = 2;
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
305
|
+
case 2:
|
|
200
306
|
palettePointer = Module._malloc(palette.length);
|
|
307
|
+
if (palettePointer) {
|
|
308
|
+
_context7.n = 3;
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
Module._free(imagePointer);
|
|
312
|
+
throw new Error("Failed to allocate WASM memory.");
|
|
313
|
+
case 3:
|
|
314
|
+
outputPointer = 0;
|
|
315
|
+
_context7.p = 4;
|
|
201
316
|
Module.HEAPU8.set(image.data, imagePointer);
|
|
202
317
|
Module.HEAPU8.set(palette, palettePointer);
|
|
203
318
|
outputPointer = Module._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length);
|
|
204
|
-
|
|
319
|
+
return _context7.a(2, wrap(unpack(outputPointer)));
|
|
320
|
+
case 5:
|
|
321
|
+
_context7.p = 5;
|
|
205
322
|
Module._free(imagePointer);
|
|
206
323
|
Module._free(palettePointer);
|
|
207
|
-
Module._free(outputPointer);
|
|
208
|
-
return _context7.
|
|
324
|
+
if (outputPointer) Module._free(outputPointer);
|
|
325
|
+
return _context7.f(5);
|
|
326
|
+
case 6:
|
|
327
|
+
return _context7.a(2);
|
|
209
328
|
}
|
|
210
|
-
}, _callee7);
|
|
329
|
+
}, _callee7, null, [[4,, 5, 6]]);
|
|
211
330
|
}));
|
|
212
331
|
return function quantizeWithPalette(_x1, _x10) {
|
|
213
332
|
return _ref7.apply(this, arguments);
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agglomerative-clustering",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Fast hierarchical agglomerative clustering powered by WebAssembly.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Rohan Fredriksson",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"main": "./dist/index.cjs",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
9
10
|
"repository": {
|
|
10
11
|
"type": "git",
|
|
11
12
|
"url": "https://github.com/RohanFredriksson/agglomerative-clustering.git"
|
|
@@ -32,6 +33,7 @@
|
|
|
32
33
|
],
|
|
33
34
|
"exports": {
|
|
34
35
|
".": {
|
|
36
|
+
"types": "./dist/index.d.ts",
|
|
35
37
|
"require": "./dist/index.cjs",
|
|
36
38
|
"import": "./dist/index.mjs"
|
|
37
39
|
}
|
|
@@ -41,19 +43,23 @@
|
|
|
41
43
|
"README.md"
|
|
42
44
|
],
|
|
43
45
|
"scripts": {
|
|
44
|
-
"build:wasm": "mkdirp dist && emcc src/clustering.cpp -O3 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s EXPORTED_FUNCTIONS=\"['_get_clustering',
|
|
46
|
+
"build:wasm": "mkdirp dist && emcc src/clustering.cpp -O3 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=32MB -s MAXIMUM_MEMORY=2147483648 -s EXPORTED_FUNCTIONS=\"['_get_clustering','_get_palette','_get_palette_from_clustering','_quantize','_quantize_with_clustering','_quantize_with_palette','_malloc','_free']\" -s EXPORTED_RUNTIME_METHODS=\"['HEAPU8']\" -o dist/clustering.js",
|
|
45
47
|
"build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir dist --extensions \".js\" --out-file-extension .cjs",
|
|
46
48
|
"build:esm": "cross-env BABEL_ENV=esm babel src --out-dir dist --extensions \".js\" --out-file-extension .mjs",
|
|
47
|
-
"build:
|
|
49
|
+
"build:types": "mkdirp dist && node -e \"require('fs').copyFileSync('src/index.d.ts', 'dist/index.d.ts')\"",
|
|
50
|
+
"build:js": "npm run build:types && npm run build:cjs && npm run build:esm",
|
|
48
51
|
"build": "npm run build:wasm && npm run build:js",
|
|
49
|
-
"prepublishOnly": "npm run build"
|
|
52
|
+
"prepublishOnly": "npm run build",
|
|
53
|
+
"test": "vitest run"
|
|
50
54
|
},
|
|
51
55
|
"devDependencies": {
|
|
52
56
|
"@babel/cli": "^7.27.2",
|
|
53
57
|
"@babel/core": "^7.27.4",
|
|
54
58
|
"@babel/plugin-transform-modules-commonjs": "^7.27.1",
|
|
55
59
|
"@babel/preset-env": "^7.27.2",
|
|
60
|
+
"canvas": "^3.2.3",
|
|
56
61
|
"cross-env": "^7.0.3",
|
|
57
|
-
"mkdirp": "^3.0.1"
|
|
62
|
+
"mkdirp": "^3.0.1",
|
|
63
|
+
"vitest": "^4.1.5"
|
|
58
64
|
}
|
|
59
65
|
}
|