@64tensor/retouch-ml 0.0.0-stage → 0.3.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/CHANGELOG.md +4 -0
- package/LICENSE +21 -0
- package/README.md +264 -2
- package/THIRD_PARTY_NOTICES.md +371 -0
- package/dist/index.d.ts +972 -0
- package/dist/index.js +5636 -0
- package/dist/index.js.map +1 -0
- package/package.json +62 -3
- package/third-party-models.json +345 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
import * as Ort from "onnxruntime-web";
|
|
2
|
+
import { Retouch } from "@64tensor/retouch";
|
|
3
|
+
/**
|
|
4
|
+
* Model weight fetching with browser-side caching: weights are streamed once
|
|
5
|
+
* (with download progress) and stored via the Cache API, so subsequent
|
|
6
|
+
* sessions load instantly and offline.
|
|
7
|
+
*/
|
|
8
|
+
interface FetchProgress {
|
|
9
|
+
/** Bytes received so far. */
|
|
10
|
+
loaded: number;
|
|
11
|
+
/** Total bytes, or 0 when the server doesn't say. */
|
|
12
|
+
total: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Fetch a model file, reporting progress and caching the bytes. Falls back
|
|
16
|
+
* to a plain fetch where the Cache API is unavailable (private windows).
|
|
17
|
+
* Concurrent requests for the same URL share one download.
|
|
18
|
+
*/
|
|
19
|
+
export declare function fetchModel(url: string, onProgress?: (progress: FetchProgress) => void): Promise<ArrayBuffer>;
|
|
20
|
+
/**
|
|
21
|
+
* True when every file in `urls` is already saved on this device, so a run
|
|
22
|
+
* needs no download. False when any is missing — or when the Cache API is
|
|
23
|
+
* unavailable (private windows), since the run will download then.
|
|
24
|
+
*/
|
|
25
|
+
export declare function isModelCached(urls: readonly string[]): Promise<boolean>;
|
|
26
|
+
/** Drop every cached model (frees storage; next run re-downloads). */
|
|
27
|
+
export declare function clearModelCache(): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* ONNX Runtime Web session management: WebGPU when the browser has it,
|
|
30
|
+
* WASM otherwise. The runtime's .wasm binaries load from a CDN by default
|
|
31
|
+
* so bundlers never have to copy them; point `wasmPaths` at a self-hosted
|
|
32
|
+
* directory to stay first-party.
|
|
33
|
+
*/
|
|
34
|
+
interface RuntimeOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Directory the ORT .wasm binaries load from. Defaults to jsDelivr.
|
|
37
|
+
* Page-global: an explicit value applies to every later session too.
|
|
38
|
+
*/
|
|
39
|
+
wasmPaths?: string;
|
|
40
|
+
/** Execution providers in preference order. Defaults to WebGPU → WASM. */
|
|
41
|
+
executionProviders?: string[];
|
|
42
|
+
/**
|
|
43
|
+
* Sidecar weights for exports split into a graph stub plus an
|
|
44
|
+
* `.onnx.data` blob. Both files download through the model cache; the
|
|
45
|
+
* sidecar's filename must match what the graph references.
|
|
46
|
+
*/
|
|
47
|
+
externalDataUrl?: string;
|
|
48
|
+
onDownloadProgress?: (progress: FetchProgress) => void;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Download (or read back from cache) a model and create a session for it.
|
|
52
|
+
* Sessions are memoized per URL + provider list; a WebGPU failure at
|
|
53
|
+
* creation time retries on plain WASM. Some kernels only fail at inference
|
|
54
|
+
* time — callers doing heavy runs should catch and retry via
|
|
55
|
+
* `loadSession(url, { ...options, executionProviders: ["wasm"] })`.
|
|
56
|
+
*/
|
|
57
|
+
export declare function loadSession(url: string, options?: RuntimeOptions): Promise<Ort.InferenceSession>;
|
|
58
|
+
/**
|
|
59
|
+
* Drop a memoized session and free its native resources — used after a
|
|
60
|
+
* session proves unusable (e.g. WebGPU kernels failing at inference time).
|
|
61
|
+
*/
|
|
62
|
+
export declare function releaseSession(url: string, options?: RuntimeOptions): Promise<void>;
|
|
63
|
+
interface ResilientRunResult {
|
|
64
|
+
session: Ort.InferenceSession;
|
|
65
|
+
results: Awaited<ReturnType<Ort.InferenceSession["run"]>>;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Load the session for `url` and run `feeds` through it (serialized on the
|
|
69
|
+
* shared inference queue), falling back to WASM once when a WebGPU kernel
|
|
70
|
+
* fails at inference time — some devices only reject kernels mid-run. The
|
|
71
|
+
* fallback sticks per model URL for later calls. An explicit
|
|
72
|
+
* `executionProviders` list is respected verbatim: no automatic fallback.
|
|
73
|
+
*/
|
|
74
|
+
export declare function runResilient(url: string, options: RuntimeOptions, feeds: (session: Ort.InferenceSession) => Record<string, Ort.Tensor>): Promise<ResilientRunResult>;
|
|
75
|
+
/**
|
|
76
|
+
* Depth estimation via Depth Anything V2 Small (Apache-2.0, quantized
|
|
77
|
+
* ~27 MB — verified 0.9993-correlated with the fp32 export). Dynamic input
|
|
78
|
+
* dims (multiples of 14, longest edge ≈ 518), RGB /255 with ImageNet
|
|
79
|
+
* mean/std, no padding. Output is relative inverse depth at input dims:
|
|
80
|
+
* **higher = closer** (verified empirically). The bokeh built on it lives
|
|
81
|
+
* in bokeh.ts.
|
|
82
|
+
*/
|
|
83
|
+
export declare const DEFAULT_DEPTH_MODEL_URL = "https://huggingface.co/onnx-community/depth-anything-v2-small/resolve/4472b7362082ad9968fee890ca0f1e5aca36b93d/onnx/model_quantized.onnx";
|
|
84
|
+
interface DepthOptions extends RuntimeOptions {
|
|
85
|
+
modelUrl?: string;
|
|
86
|
+
}
|
|
87
|
+
/** Relative depth, normalized 0–1 (1 = closest), at model resolution. */
|
|
88
|
+
interface DepthMap {
|
|
89
|
+
data: Float32Array;
|
|
90
|
+
width: number;
|
|
91
|
+
height: number;
|
|
92
|
+
}
|
|
93
|
+
/** Model input dims: longest edge ≈ 518, both multiples of 14, aspect kept. */
|
|
94
|
+
export declare function depthResizedSize(width: number, height: number): {
|
|
95
|
+
width: number;
|
|
96
|
+
height: number;
|
|
97
|
+
};
|
|
98
|
+
/** RGBA bytes → CHW float tensor data: /255 then ImageNet mean/std. */
|
|
99
|
+
export declare function rgbaToDepthTensor(data: Uint8ClampedArray, width: number, height: number): Float32Array;
|
|
100
|
+
/** Min-max normalize raw model output to 0–1 (constant maps become 0). */
|
|
101
|
+
export declare function normalizeDepth(raw: Float32Array): Float32Array;
|
|
102
|
+
/** Bilinear depth sample at normalized (0–1) coordinates. */
|
|
103
|
+
export declare function depthAt(map: DepthMap, nx: number, ny: number): number;
|
|
104
|
+
/** Drop all cached depth maps. */
|
|
105
|
+
export declare function clearDepthCache(): void;
|
|
106
|
+
/** Estimate relative depth, memoized per element. Higher = closer. */
|
|
107
|
+
export declare function estimateDepth(source: HTMLImageElement | HTMLCanvasElement, options?: DepthOptions): Promise<DepthMap>;
|
|
108
|
+
/**
|
|
109
|
+
* A focus to start from, before any click: the nearer part of the photo's
|
|
110
|
+
* middle, where a subject usually is (three quarters of the way up the
|
|
111
|
+
* depths in the central box).
|
|
112
|
+
*/
|
|
113
|
+
export declare function suggestFocus(map: DepthMap): number;
|
|
114
|
+
/**
|
|
115
|
+
* Which pre-blurred levels to mix for a desired radius: the bracketing pair
|
|
116
|
+
* plus the interpolation factor. Radii must be ascending, starting at 0.
|
|
117
|
+
*/
|
|
118
|
+
export declare function blendWeights(radius: number, levelRadii: number[]): {
|
|
119
|
+
lo: number;
|
|
120
|
+
hi: number;
|
|
121
|
+
t: number;
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* How out of focus a depth is, 0 (sharp) to 1 (fully blurred), for a focus
|
|
125
|
+
* depth. Depth within IN_FOCUS of the focus stays sharp, so the whole
|
|
126
|
+
* subject does, not just the spot that was clicked.
|
|
127
|
+
*/
|
|
128
|
+
export declare function defocus(depth: number, focus: number): number;
|
|
129
|
+
/**
|
|
130
|
+
* The blur levels for one focus depth (see focusLayers). Each list holds
|
|
131
|
+
* levels 1… (index 0 is level 1): level 0 is the photo itself.
|
|
132
|
+
*/
|
|
133
|
+
interface FocusLayers {
|
|
134
|
+
focus: number;
|
|
135
|
+
/**
|
|
136
|
+
* The background's blur: normalized, with only what's behind the focus
|
|
137
|
+
* and out of it counting, so the blur around a subject is background.
|
|
138
|
+
*/
|
|
139
|
+
behind: Uint8ClampedArray[];
|
|
140
|
+
/** The near layer, premultiplied; null when nothing is in front of the focus. */
|
|
141
|
+
near: Uint8ClampedArray[] | null;
|
|
142
|
+
/** A plain blur, for the near layer's own pixels; null with `near`. */
|
|
143
|
+
plain: Uint8ClampedArray[] | null;
|
|
144
|
+
/** The near layer's defocus, averaged around each pixel: how far its blur spreads there. */
|
|
145
|
+
nearDefocus: Float32Array | null;
|
|
146
|
+
/** How much of each pixel the near layer holds (see nearMask). */
|
|
147
|
+
mask: Float32Array | null;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Blur the photo at `radii` for a focus depth: the slow part of the bokeh,
|
|
151
|
+
* so composing a new aperture reuses it. The blurs run at half size, a
|
|
152
|
+
* quarter of the work, and scale back up: blurred, nothing shows the seam.
|
|
153
|
+
*
|
|
154
|
+
* Behind the focus, the background blurs without the subject, which would
|
|
155
|
+
* otherwise glow into it. In front of the focus, a lens spreads the near
|
|
156
|
+
* layer over what's behind it, so the near layer is blurred on its own, to
|
|
157
|
+
* lay over the rest. Its own pixels take a plain blur: the near layer over
|
|
158
|
+
* an estimate of what it hides (the blur of everything else around) adds up
|
|
159
|
+
* to exactly that.
|
|
160
|
+
*/
|
|
161
|
+
export declare function focusLayers(base: Uint8ClampedArray, depth: Float32Array, width: number, height: number, focus: number, radii: number[]): FocusLayers;
|
|
162
|
+
/**
|
|
163
|
+
* Depth at the photo's size, with its edges on the photo's own. The model
|
|
164
|
+
* sees the photo at about 518 px, so scaled up, its edges are soft and
|
|
165
|
+
* stepped, and a blur that follows them cuts a jagged outline. A fast color
|
|
166
|
+
* guided filter (He et al.) fits depth as a linear function of color in
|
|
167
|
+
* each small window at the model's resolution, then applies the fitted
|
|
168
|
+
* coefficients to the full-size photo, where the edges are crisp.
|
|
169
|
+
*/
|
|
170
|
+
export declare function guidedDepth(depth: DepthMap, rgba: Uint8ClampedArray, width: number, height: number, radius?: number, eps?: number): Float32Array;
|
|
171
|
+
/** The photo and its depth at preview size, plus the blur layers for the last focus. */
|
|
172
|
+
interface BokehPrep {
|
|
173
|
+
width: number;
|
|
174
|
+
height: number;
|
|
175
|
+
/** The sharp photo, RGBA. */
|
|
176
|
+
base: Uint8ClampedArray;
|
|
177
|
+
/** Depth per pixel, 0–1, its edges on the photo's (see guidedDepth). */
|
|
178
|
+
depth: Float32Array;
|
|
179
|
+
levelRadii: number[];
|
|
180
|
+
/** The layers for the last focus composed, kept while the focus stays. */
|
|
181
|
+
layers: FocusLayers | null;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Draw the photo at preview size (long edge up to `maxDim`) and fit the
|
|
185
|
+
* depth map to it. The blur comes later, with the focus.
|
|
186
|
+
*/
|
|
187
|
+
export declare function prepareBokeh(source: HTMLImageElement | HTMLCanvasElement, depth: DepthMap, maxDim?: number): BokehPrep;
|
|
188
|
+
/**
|
|
189
|
+
* The bokeh's pixels at preview size for a focus depth (0–1, from a click)
|
|
190
|
+
* and aperture strength (0–1): the blur grows with distance from the focus.
|
|
191
|
+
* A new focus builds its blur layers first, the slow part; a new strength
|
|
192
|
+
* after that is cheap enough for every slider tick.
|
|
193
|
+
*/
|
|
194
|
+
export declare function composeBokehPixels(prep: BokehPrep, focus: number, strength: number): Uint8ClampedArray<ArrayBuffer>;
|
|
195
|
+
/** composeBokehPixels, on a canvas. */
|
|
196
|
+
export declare function composeBokeh(prep: BokehPrep, focus: number, strength: number): HTMLCanvasElement;
|
|
197
|
+
/**
|
|
198
|
+
* The bokeh at the photo's full size, matching the preview: the sharp photo,
|
|
199
|
+
* its depth and the near mask are full size, and the blur comes from the
|
|
200
|
+
* preview's layers, scaled up a strip at a time. They're smooth enough that
|
|
201
|
+
* scaling shows nothing, and it's far lighter than blurring at full size.
|
|
202
|
+
*/
|
|
203
|
+
export declare function renderBokeh(prep: BokehPrep, source: HTMLImageElement | HTMLCanvasElement, depth: DepthMap, focus: number, strength: number): HTMLCanvasElement;
|
|
204
|
+
/** renderBokeh's pixels, from the photo's RGBA at `width`×`height`. */
|
|
205
|
+
export declare function renderBokehPixels(prep: BokehPrep, base: Uint8ClampedArray, width: number, height: number, depth: DepthMap, focus: number, strength: number): Uint8ClampedArray<ArrayBuffer>;
|
|
206
|
+
/**
|
|
207
|
+
* Background removal via MODNet (Apache-2.0): the image runs through the
|
|
208
|
+
* network at a capped reference size, the predicted matte upsamples back to
|
|
209
|
+
* full resolution, and the result is the original RGBA with the matte as its
|
|
210
|
+
* alpha channel. Swap `modelUrl` for a BiRefNet ONNX export when quality
|
|
211
|
+
* matters more than the download.
|
|
212
|
+
*/
|
|
213
|
+
export declare const DEFAULT_CUTOUT_MODEL_URL = "https://huggingface.co/Xenova/modnet/resolve/fa2fa546052fba4c08921230a26cc69a333fca12/onnx/model.onnx";
|
|
214
|
+
interface CutoutOptions extends RuntimeOptions {
|
|
215
|
+
modelUrl?: string;
|
|
216
|
+
/** Network reference size (long edge). Defaults to MODNet's 512. */
|
|
217
|
+
refSize?: number;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Network input dimensions: long edge capped at `refSize`, both dimensions
|
|
221
|
+
* snapped to multiples of 32 (MODNet's stride).
|
|
222
|
+
*/
|
|
223
|
+
export declare function fitRefSize(width: number, height: number, refSize?: number): {
|
|
224
|
+
width: number;
|
|
225
|
+
height: number;
|
|
226
|
+
};
|
|
227
|
+
/** RGBA bytes → normalized CHW float tensor data, MODNet convention (x−0.5)/0.5. */
|
|
228
|
+
export declare function rgbaToNormalizedChw(data: Uint8ClampedArray, pixelCount: number): Float32Array;
|
|
229
|
+
/** Matte floats (0–1) → grayscale RGBA bytes, for canvas-based upsampling. */
|
|
230
|
+
export declare function matteToRgba(matte: Float32Array): Uint8ClampedArray<ArrayBuffer>;
|
|
231
|
+
/** Write a grayscale matte (as RGBA) into the alpha channel of `target`, in place. */
|
|
232
|
+
export declare function applyMatteAlpha(target: Uint8ClampedArray, matteRgba: Uint8ClampedArray): void;
|
|
233
|
+
/**
|
|
234
|
+
* Remove the background of an image or canvas. Returns a new canvas holding
|
|
235
|
+
* the original pixels with the predicted matte as alpha.
|
|
236
|
+
*/
|
|
237
|
+
export declare function removeBackground(source: HTMLImageElement | HTMLCanvasElement, options?: CutoutOptions): Promise<HTMLCanvasElement>;
|
|
238
|
+
/**
|
|
239
|
+
* Blind real-noise removal via SCUNet (Apache-2.0 or MIT; see
|
|
240
|
+
* THIRD_PARTY_NOTICES.md): the image runs through
|
|
241
|
+
* the network tile by tile at native resolution — RGB in 0–1, CHW, output
|
|
242
|
+
* the same shape. The export splits into a small graph stub plus a
|
|
243
|
+
* `.onnx.data` weights sidecar, loaded through the runtime's external-data
|
|
244
|
+
* support. Swin attention windows constrain every input dimension to a
|
|
245
|
+
* multiple of 64, so each tile pads up to the next multiple by replicating
|
|
246
|
+
* its edge pixels (verified: zero-padding bleeds a dark rim into cores that
|
|
247
|
+
* sit on the image border).
|
|
248
|
+
*/
|
|
249
|
+
export declare const DEFAULT_DENOISE_MODEL_URL = "https://huggingface.co/Heliosoph/scunet-onnx/resolve/6d11417ee2fbcc73783c502a238ac115097754fe/scunet_color_real_psnr.onnx";
|
|
250
|
+
export declare const DEFAULT_DENOISE_DATA_URL = "https://huggingface.co/Heliosoph/scunet-onnx/resolve/6d11417ee2fbcc73783c502a238ac115097754fe/scunet_color_real_psnr.onnx.data";
|
|
251
|
+
/** Every SCUNet input dimension must divide by this (Swin window math). */
|
|
252
|
+
export declare const DENOISE_DIM_MULTIPLE = 64;
|
|
253
|
+
interface DenoiseOptions extends RuntimeOptions {
|
|
254
|
+
modelUrl?: string;
|
|
255
|
+
/** Core tile edge in source pixels. Defaults to 192. */
|
|
256
|
+
tileSize?: number;
|
|
257
|
+
/** Context padding around each tile. Defaults to 16. */
|
|
258
|
+
tileOverlap?: number;
|
|
259
|
+
/** Reject sources with a longer edge than this. Defaults to 2048. */
|
|
260
|
+
maxInputDim?: number;
|
|
261
|
+
/** Tile-level progress — fires after each tile completes. */
|
|
262
|
+
onTileProgress?: (done: number, total: number) => void;
|
|
263
|
+
}
|
|
264
|
+
/** Round `value` up to the next multiple of `multiple` (at least one). */
|
|
265
|
+
export declare function ceilToMultiple(value: number, multiple: number): number;
|
|
266
|
+
/**
|
|
267
|
+
* Grow an RGBA buffer from sw×sh to pw×ph by clamping reads to the source
|
|
268
|
+
* edge — the classic replicate pad, so the network never sees a synthetic
|
|
269
|
+
* black border.
|
|
270
|
+
*/
|
|
271
|
+
export declare function padRgbaReplicate(data: Uint8ClampedArray, sw: number, sh: number, pw: number, ph: number): Uint8ClampedArray<ArrayBuffer>;
|
|
272
|
+
/**
|
|
273
|
+
* Denoise an image or canvas in place (1:1 dimensions). Returns a canvas
|
|
274
|
+
* at the source size with the noise removed and alpha carried through.
|
|
275
|
+
*/
|
|
276
|
+
export declare function denoiseImage(source: HTMLImageElement | HTMLCanvasElement, options?: DenoiseOptions): Promise<HTMLCanvasElement>;
|
|
277
|
+
/**
|
|
278
|
+
* Preview surface for the Depth tool: an overlay canvas that shows the
|
|
279
|
+
* composed bokeh in place of the plain preview and captures clicks to set
|
|
280
|
+
* the focal plane. Coordinates are normalized 0–1 over the image.
|
|
281
|
+
*/
|
|
282
|
+
interface DepthSurfaceHandle {
|
|
283
|
+
/** Show a composed preview (null clears it back to the plain image). */
|
|
284
|
+
setPreview(preview: HTMLCanvasElement | null): void;
|
|
285
|
+
setVisible(visible: boolean): void;
|
|
286
|
+
destroy(): void;
|
|
287
|
+
}
|
|
288
|
+
export declare function createDepthSurface(canvasArea: HTMLElement, onClick: (x: number, y: number) => void): DepthSurfaceHandle;
|
|
289
|
+
/**
|
|
290
|
+
* Detection models. Faces: UltraFace (MIT, ~1.2 MB) — the RFB-320 export
|
|
291
|
+
* decodes its priors in-graph, so the outputs are softmaxed scores [1,N,2]
|
|
292
|
+
* and normalized corner boxes [1,N,4]; threshold + NMS is all that's left.
|
|
293
|
+
* Objects: YOLOX-nano (Apache-2.0, ~3.5 MB) — raw per-anchor output
|
|
294
|
+
* [1,3549,85] decoded here (xy = (pred+grid)·stride, wh = exp(pred)·stride,
|
|
295
|
+
* score = objectness × class), 80 COCO classes.
|
|
296
|
+
*
|
|
297
|
+
* Conventions verified against the exports: UltraFace takes RGB CHW
|
|
298
|
+
* normalized (v−127)/128 at a fixed squashed 320×240. YOLOX takes **BGR**
|
|
299
|
+
* CHW in raw 0–255 (no normalization) on a 114-gray letterbox canvas,
|
|
300
|
+
* image pasted top-left at ratio = min(416/w, 416/h) — BGR confirmed
|
|
301
|
+
* empirically (person 0.90 vs 0.78 with RGB).
|
|
302
|
+
*/
|
|
303
|
+
export declare const DEFAULT_FACE_MODEL_URL = "https://raw.githubusercontent.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB/dffdddda9794a50607cba8f318507a28c1c27cab/models/onnx/version-RFB-320.onnx";
|
|
304
|
+
export declare const DEFAULT_OBJECT_MODEL_URL = "https://huggingface.co/hr16/yolox-onnx/resolve/a124b32c3b7c5cebda1c7cd96178f0f9d2050125/yolox_nano.onnx";
|
|
305
|
+
/** The 80 COCO class names, in YOLOX output order. */
|
|
306
|
+
export declare const COCO_CLASSES: string[];
|
|
307
|
+
/** A detected box, normalized 0–1 over the source image. */
|
|
308
|
+
interface Detection {
|
|
309
|
+
x: number;
|
|
310
|
+
y: number;
|
|
311
|
+
w: number;
|
|
312
|
+
h: number;
|
|
313
|
+
score: number;
|
|
314
|
+
/** COCO class name for object detections; faces leave it unset. */
|
|
315
|
+
label?: string;
|
|
316
|
+
}
|
|
317
|
+
interface DetectFacesOptions extends RuntimeOptions {
|
|
318
|
+
modelUrl?: string;
|
|
319
|
+
/** Minimum face probability. Defaults to 0.7. */
|
|
320
|
+
scoreThreshold?: number;
|
|
321
|
+
/** NMS overlap threshold. Defaults to 0.35. */
|
|
322
|
+
iouThreshold?: number;
|
|
323
|
+
}
|
|
324
|
+
interface DetectObjectsOptions extends RuntimeOptions {
|
|
325
|
+
modelUrl?: string;
|
|
326
|
+
/** Minimum objectness × class score. Defaults to 0.35. */
|
|
327
|
+
scoreThreshold?: number;
|
|
328
|
+
/** NMS overlap threshold (applied per class). Defaults to 0.45. */
|
|
329
|
+
iouThreshold?: number;
|
|
330
|
+
}
|
|
331
|
+
/** RGBA bytes → UltraFace tensor data: RGB CHW, (v−127)/128. */
|
|
332
|
+
export declare function rgbaToUltraFaceTensor(data: Uint8ClampedArray, pixelCount: number): Float32Array;
|
|
333
|
+
/** Intersection-over-union of two normalized boxes. */
|
|
334
|
+
export declare function iou(a: Detection, b: Detection): number;
|
|
335
|
+
/** Greedy non-maximum suppression, highest score first. */
|
|
336
|
+
export declare function nms(detections: Detection[], iouThreshold: number): Detection[];
|
|
337
|
+
/**
|
|
338
|
+
* Threshold the raw UltraFace outputs into candidate boxes (still
|
|
339
|
+
* overlapping — run `nms` after). Boxes are clamped to the frame; empty or
|
|
340
|
+
* inverted ones are dropped.
|
|
341
|
+
*/
|
|
342
|
+
export declare function decodeUltraFace(scores: Float32Array, boxes: Float32Array, count: number, scoreThreshold: number): Detection[];
|
|
343
|
+
/**
|
|
344
|
+
* Per-anchor grid coordinates and strides for YOLOX at 416: 52² + 26² + 13²
|
|
345
|
+
* anchors, level-major in stride order 8/16/32.
|
|
346
|
+
*/
|
|
347
|
+
export declare function buildYoloxGrid(): {
|
|
348
|
+
gridX: Int32Array;
|
|
349
|
+
gridY: Int32Array;
|
|
350
|
+
stride: Int32Array;
|
|
351
|
+
};
|
|
352
|
+
/**
|
|
353
|
+
* Letterboxed-canvas RGBA → YOLOX tensor data: CHW **BGR**, raw 0–255.
|
|
354
|
+
* The canvas is expected to already hold the 114-gray letterbox.
|
|
355
|
+
*/
|
|
356
|
+
export declare function rgbaToYoloxTensor(data: Uint8ClampedArray, pixelCount: number): Float32Array;
|
|
357
|
+
/**
|
|
358
|
+
* Decode raw YOLOX output [N,85] into thresholded candidate boxes,
|
|
359
|
+
* normalized 0–1 over the source (still overlapping — run `nms` after).
|
|
360
|
+
* `ratio` is the letterbox scale min(416/w, 416/h).
|
|
361
|
+
*/
|
|
362
|
+
export declare function decodeYolox(output: Float32Array, grid: {
|
|
363
|
+
gridX: Int32Array;
|
|
364
|
+
gridY: Int32Array;
|
|
365
|
+
stride: Int32Array;
|
|
366
|
+
}, ratio: number, srcWidth: number, srcHeight: number, scoreThreshold: number): Detection[];
|
|
367
|
+
/** NMS per class: boxes of different labels never suppress each other. */
|
|
368
|
+
export declare function nmsByClass(detections: Detection[], iouThreshold: number): Detection[];
|
|
369
|
+
/** Detect COCO objects in an image or canvas. Boxes come back normalized 0–1. */
|
|
370
|
+
export declare function detectObjects(source: HTMLImageElement | HTMLCanvasElement, options?: DetectObjectsOptions): Promise<Detection[]>;
|
|
371
|
+
/** Detect faces in an image or canvas. Boxes come back normalized 0–1. */
|
|
372
|
+
export declare function detectFaces(source: HTMLImageElement | HTMLCanvasElement, options?: DetectFacesOptions): Promise<Detection[]>;
|
|
373
|
+
/**
|
|
374
|
+
* Object erase via LaMa (Apache-2.0): the brush strokes define a hole, a
|
|
375
|
+
* padded square region around the hole runs through the network at its
|
|
376
|
+
* fixed 512×512 size, and the inpainted patch composites back at full
|
|
377
|
+
* resolution — masked pixels only, feathered edge.
|
|
378
|
+
*
|
|
379
|
+
* Conventions verified against the export: image RGB 0–1 CHW, mask 1=hole,
|
|
380
|
+
* output 0–255 with unmasked pixels passing through unchanged.
|
|
381
|
+
*/
|
|
382
|
+
export declare const DEFAULT_INPAINT_MODEL_URL = "https://huggingface.co/Carve/LaMa-ONNX/resolve/c3c0c9e468934d62e79c329e35d82dd09ff8c444/lama_fp32.onnx";
|
|
383
|
+
interface InpaintOptions extends RuntimeOptions {
|
|
384
|
+
modelUrl?: string;
|
|
385
|
+
}
|
|
386
|
+
/** One brush dab, normalized to the image: center (0–1), radius as a fraction of height. */
|
|
387
|
+
interface MaskStroke {
|
|
388
|
+
x: number;
|
|
389
|
+
y: number;
|
|
390
|
+
r: number;
|
|
391
|
+
}
|
|
392
|
+
interface Region {
|
|
393
|
+
x: number;
|
|
394
|
+
y: number;
|
|
395
|
+
w: number;
|
|
396
|
+
h: number;
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Pixel bounding box of the strokes plus context padding, clamped to the
|
|
400
|
+
* image. Returns null when there are no strokes.
|
|
401
|
+
*/
|
|
402
|
+
export declare function strokesBoundingBox(strokes: MaskStroke[], width: number, height: number, pad: number): Region | null;
|
|
403
|
+
/**
|
|
404
|
+
* Grow a region to a square (the network sees an undistorted patch),
|
|
405
|
+
* shifting inside the image when possible; where the image itself is
|
|
406
|
+
* smaller than the square, the region clamps to the image bounds.
|
|
407
|
+
*/
|
|
408
|
+
export declare function expandToSquare(region: Region, width: number, height: number): Region;
|
|
409
|
+
/**
|
|
410
|
+
* Pixel bounding box of the bright (>127) pixels of a grayscale RGBA mask,
|
|
411
|
+
* plus padding, clamped to the image. Null when the mask is empty.
|
|
412
|
+
*/
|
|
413
|
+
export declare function maskBoundingBox(gray: Uint8ClampedArray, width: number, height: number, pad: number): Region | null;
|
|
414
|
+
/**
|
|
415
|
+
* Grow the bright region of a grayscale RGBA mask by `radius` pixels
|
|
416
|
+
* (Chebyshev/square growth via a separable two-pass max filter) — used to
|
|
417
|
+
* dilate tight segmentation masks before inpainting so edges don't halo.
|
|
418
|
+
*/
|
|
419
|
+
export declare function dilateMask(gray: Uint8ClampedArray, width: number, height: number, radius: number): Uint8ClampedArray<ArrayBuffer>;
|
|
420
|
+
/** Grayscale mask RGBA → binary hole tensor (1 = inpaint). */
|
|
421
|
+
export declare function maskToTensor(data: Uint8ClampedArray, pixelCount: number): Float32Array;
|
|
422
|
+
/** CHW floats in 0–255 → opaque RGBA bytes. */
|
|
423
|
+
export declare function chw255ToRgba(chw: Float32Array, pixelCount: number): Uint8ClampedArray<ArrayBuffer>;
|
|
424
|
+
/**
|
|
425
|
+
* Erase the masked region of an image (white = remove on a black mask
|
|
426
|
+
* canvas at source resolution). Returns a full-resolution canvas: the
|
|
427
|
+
* original pixels everywhere, the network's fill where the mask is.
|
|
428
|
+
*/
|
|
429
|
+
export declare function inpaintMask(source: HTMLImageElement | HTMLCanvasElement, mask: HTMLCanvasElement, options?: InpaintOptions): Promise<HTMLCanvasElement>;
|
|
430
|
+
/**
|
|
431
|
+
* Erase the brushed region of an image — rasterizes the strokes into a
|
|
432
|
+
* full-resolution mask and delegates to `inpaintMask`. (Circles are now
|
|
433
|
+
* rasterized at source resolution and downscaled with the mask, which is
|
|
434
|
+
* visually identical to the previous vector redraw after thresholding.)
|
|
435
|
+
*/
|
|
436
|
+
export declare function inpaintStrokes(source: HTMLImageElement | HTMLCanvasElement, strokes: MaskStroke[], options?: InpaintOptions): Promise<HTMLCanvasElement>;
|
|
437
|
+
/**
|
|
438
|
+
* Brush surface for the Erase tool: a canvas overlaid on the editor's
|
|
439
|
+
* preview canvas where drags paint red mask dabs, under a ring the size of
|
|
440
|
+
* the brush. Strokes are stored normalized (x, y in 0–1; radius as a
|
|
441
|
+
* fraction of height), so they map straight onto the source image when
|
|
442
|
+
* geometry is neutral.
|
|
443
|
+
*/
|
|
444
|
+
interface EraseSurfaceHandle {
|
|
445
|
+
getStrokes(): MaskStroke[];
|
|
446
|
+
hasStrokes(): boolean;
|
|
447
|
+
clear(): void;
|
|
448
|
+
setBrush(sizeFraction: number): void;
|
|
449
|
+
setVisible(visible: boolean): void;
|
|
450
|
+
destroy(): void;
|
|
451
|
+
}
|
|
452
|
+
export declare function createEraseSurface(canvasArea: HTMLElement, onStrokesChange: () => void): EraseSurfaceHandle;
|
|
453
|
+
export declare const DEFAULT_TEXT_DETECTOR_URL = "https://huggingface.co/SWHL/RapidOCR/resolve/1cfba2e90fc938db55889873735088de210cc173/PP-OCRv4/ch_PP-OCRv4_det_infer.onnx";
|
|
454
|
+
export declare const DEFAULT_TEXT_RECOGNIZER_URL = "https://huggingface.co/monkt/paddleocr-onnx/resolve/7b02d0a30a07ba2b92ad1ff5a8941ae2c633de65/languages/latin/rec.onnx";
|
|
455
|
+
export declare const DEFAULT_TEXT_DICTIONARY_URL = "https://huggingface.co/monkt/paddleocr-onnx/resolve/7b02d0a30a07ba2b92ad1ff5a8941ae2c633de65/languages/latin/dict.txt";
|
|
456
|
+
type Point = readonly [x: number, y: number];
|
|
457
|
+
/** A rotated rectangle: center, unit axis along the line, and its size. */
|
|
458
|
+
interface TextBox {
|
|
459
|
+
cx: number;
|
|
460
|
+
cy: number;
|
|
461
|
+
/** Unit vector along the text; the other axis is (−uy, ux). */
|
|
462
|
+
ux: number;
|
|
463
|
+
uy: number;
|
|
464
|
+
/** Length along the text. */
|
|
465
|
+
width: number;
|
|
466
|
+
/** Thickness across it. */
|
|
467
|
+
height: number;
|
|
468
|
+
/** Mean text probability over the region. */
|
|
469
|
+
score: number;
|
|
470
|
+
}
|
|
471
|
+
/** A line of text, normalized 0–1 over the source image. */
|
|
472
|
+
interface TextLine {
|
|
473
|
+
text: string;
|
|
474
|
+
/** Mean per-character confidence, 0–1. */
|
|
475
|
+
score: number;
|
|
476
|
+
/** Corners clockwise from the line's top-left, normalized 0–1. */
|
|
477
|
+
quad: [Point, Point, Point, Point];
|
|
478
|
+
/** Axis-aligned bounds of the quad. */
|
|
479
|
+
x: number;
|
|
480
|
+
y: number;
|
|
481
|
+
w: number;
|
|
482
|
+
h: number;
|
|
483
|
+
}
|
|
484
|
+
interface OcrOptions extends RuntimeOptions {
|
|
485
|
+
detectorUrl?: string;
|
|
486
|
+
recognizerUrl?: string;
|
|
487
|
+
/** One character per line, in the recognizer's class order. */
|
|
488
|
+
dictionaryUrl?: string;
|
|
489
|
+
/** Long side of the detector's input. Defaults to 1280; small text reads better larger. */
|
|
490
|
+
maxSide?: number;
|
|
491
|
+
/** Probability a pixel needs to count as text. Defaults to 0.3. */
|
|
492
|
+
binaryThreshold?: number;
|
|
493
|
+
/** Mean probability a region needs to count as a line. Defaults to 0.6. */
|
|
494
|
+
boxThreshold?: number;
|
|
495
|
+
/** How far boxes grow past the network's shrunk kernels. Defaults to 1.5. */
|
|
496
|
+
unclipRatio?: number;
|
|
497
|
+
/** Lines read with less confidence are dropped. Defaults to 0.5. */
|
|
498
|
+
minScore?: number;
|
|
499
|
+
}
|
|
500
|
+
/** Convex hull (monotone chain), counter-clockwise in y-down coordinates. */
|
|
501
|
+
export declare function convexHull(points: readonly Point[]): Point[];
|
|
502
|
+
/**
|
|
503
|
+
* The smallest rotated rectangle around `points` (rotating calipers over
|
|
504
|
+
* the hull: the best rectangle has a side on a hull edge). The returned
|
|
505
|
+
* axis runs along the rectangle's longer side, pointing right.
|
|
506
|
+
*/
|
|
507
|
+
export declare function minAreaRect(points: readonly Point[]): Omit<TextBox, "score">;
|
|
508
|
+
/** Corners of a box, clockwise from top-left along its axis (y down). */
|
|
509
|
+
export declare function boxCorners(box: Omit<TextBox, "score">): [Point, Point, Point, Point];
|
|
510
|
+
/**
|
|
511
|
+
* Text regions in a DB probability map, in map pixels. Each 4-connected
|
|
512
|
+
* region over `binaryThreshold` becomes its minimum-area rectangle, kept
|
|
513
|
+
* when its mean probability clears `boxThreshold`, then grown by
|
|
514
|
+
* area × unclipRatio / perimeter on every side.
|
|
515
|
+
*/
|
|
516
|
+
export declare function textBoxesFromMap(prob: Float32Array, width: number, height: number, options?: {
|
|
517
|
+
binaryThreshold?: number;
|
|
518
|
+
boxThreshold?: number;
|
|
519
|
+
unclipRatio?: number;
|
|
520
|
+
}): TextBox[];
|
|
521
|
+
/** Detector input size: the long side at most `maxSide`, both sides multiples of 32. */
|
|
522
|
+
export declare function detectorSize(srcW: number, srcH: number, maxSide: number): [number, number];
|
|
523
|
+
/** RGBA bytes → detector tensor: BGR CHW, ImageNet mean/std (in PaddleOCR's channel order). */
|
|
524
|
+
export declare function rgbaToDetectorTensor(data: Uint8ClampedArray, pixelCount: number): Float32Array;
|
|
525
|
+
/** RGBA bytes → recognizer tensor: BGR CHW in [-1, 1]. */
|
|
526
|
+
export declare function rgbaToRecognizerTensor(data: Uint8ClampedArray, pixelCount: number): Float32Array;
|
|
527
|
+
/**
|
|
528
|
+
* Greedy CTC decode of [steps, classes] logits: best class per step,
|
|
529
|
+
* repeats merged, blanks (class 0) dropped. `charset[k]` names class k.
|
|
530
|
+
*/
|
|
531
|
+
export declare function ctcDecode(logits: Float32Array, steps: number, classes: number, charset: readonly string[]): {
|
|
532
|
+
text: string;
|
|
533
|
+
score: number;
|
|
534
|
+
};
|
|
535
|
+
/** The recognizer's classes: blank, the dictionary's characters, then a space. */
|
|
536
|
+
export declare function charsetFromDictionary(dictionary: string): string[];
|
|
537
|
+
/**
|
|
538
|
+
* Reading order: lines whose centers sit within half a line height of each
|
|
539
|
+
* other share a row, rows run top to bottom, lines in a row left to right.
|
|
540
|
+
*/
|
|
541
|
+
export declare function readingOrder<T extends {
|
|
542
|
+
x: number;
|
|
543
|
+
y: number;
|
|
544
|
+
w: number;
|
|
545
|
+
h: number;
|
|
546
|
+
}>(lines: readonly T[]): T[][];
|
|
547
|
+
/** The lines as plain text: one row per line, gaps between a row's pieces. */
|
|
548
|
+
export declare function linesToText(lines: readonly TextLine[]): string;
|
|
549
|
+
/**
|
|
550
|
+
* Find and read the text in an image or canvas. Lines come back in reading
|
|
551
|
+
* order, normalized 0–1, with their rotated corners and axis-aligned bounds.
|
|
552
|
+
*/
|
|
553
|
+
export declare function recognizeText(source: HTMLImageElement | HTMLCanvasElement, options?: OcrOptions): Promise<TextLine[]>;
|
|
554
|
+
/**
|
|
555
|
+
* Click-to-select via SlimSAM-77 (Apache-2.0): the image encodes once into
|
|
556
|
+
* embeddings (~40 MB of model across two files), then every click runs only
|
|
557
|
+
* the small prompt decoder, so refinement feels instant.
|
|
558
|
+
*
|
|
559
|
+
* Conventions verified against the exports: encoder takes RGB /255 with
|
|
560
|
+
* ImageNet mean/std, longest edge resized to 1024 and zero-padded
|
|
561
|
+
* bottom/right AFTER normalization; it emits image_embeddings AND
|
|
562
|
+
* image_positional_embeddings, both of which feed the decoder. Decoder
|
|
563
|
+
* points are in the 1024-resized space (scale = 1024/max(W,H)), labels are
|
|
564
|
+
* int64 (1 = keep, 0 = remove); it returns 3 candidate masks as 256×256
|
|
565
|
+
* logits with per-mask IoU scores. Post: pick argmax(iou), sigmoid → gray,
|
|
566
|
+
* bilinear-upsample, crop the padding, resize to the original, threshold.
|
|
567
|
+
*/
|
|
568
|
+
export declare const DEFAULT_SAM_ENCODER_URL = "https://huggingface.co/Xenova/slimsam-77-uniform/resolve/5850ab45f587c112167512ffef949107115e26a0/onnx/vision_encoder.onnx";
|
|
569
|
+
export declare const DEFAULT_SAM_DECODER_URL = "https://huggingface.co/Xenova/slimsam-77-uniform/resolve/5850ab45f587c112167512ffef949107115e26a0/onnx/prompt_encoder_mask_decoder.onnx";
|
|
570
|
+
/** The network's fixed spatial size. */
|
|
571
|
+
export declare const SAM_SIZE = 1024;
|
|
572
|
+
interface SamOptions extends RuntimeOptions {
|
|
573
|
+
encoderUrl?: string;
|
|
574
|
+
decoderUrl?: string;
|
|
575
|
+
}
|
|
576
|
+
/** One prompt click, normalized 0–1 over the source. 1 = keep, 0 = remove. */
|
|
577
|
+
interface SamPoint {
|
|
578
|
+
x: number;
|
|
579
|
+
y: number;
|
|
580
|
+
label: 0 | 1;
|
|
581
|
+
}
|
|
582
|
+
/** Cached per-image encoder outputs plus the source dimensions. */
|
|
583
|
+
interface SamEmbeddings {
|
|
584
|
+
image: Float32Array;
|
|
585
|
+
positional: Float32Array;
|
|
586
|
+
width: number;
|
|
587
|
+
height: number;
|
|
588
|
+
}
|
|
589
|
+
/** Longest edge → SAM_SIZE, the other side rounded (≥1), aspect kept. */
|
|
590
|
+
export declare function samResizedSize(width: number, height: number): {
|
|
591
|
+
width: number;
|
|
592
|
+
height: number;
|
|
593
|
+
};
|
|
594
|
+
/**
|
|
595
|
+
* Resized-image RGBA → CHW float tensor data at SAM_SIZE²: /255 then
|
|
596
|
+
* ImageNet-normalized, zero-padded bottom/right (padding stays 0 — the
|
|
597
|
+
* normalization is applied to image pixels only, per the HF processor).
|
|
598
|
+
*/
|
|
599
|
+
export declare function rgbaToSamTensor(data: Uint8ClampedArray, width: number, height: number): Float32Array;
|
|
600
|
+
/** Normalized clicks → decoder tensors (coords in the 1024-resized space). */
|
|
601
|
+
export declare function pointsToSamTensors(points: SamPoint[], srcWidth: number, srcHeight: number): {
|
|
602
|
+
coords: Float32Array;
|
|
603
|
+
labels: BigInt64Array;
|
|
604
|
+
};
|
|
605
|
+
/** The part of each low-res mask that holds the photo (the rest is padding). */
|
|
606
|
+
interface MaskRegion {
|
|
607
|
+
width: number;
|
|
608
|
+
height: number;
|
|
609
|
+
/** Row length of the mask grid. */
|
|
610
|
+
stride: number;
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* How stable a candidate mask is: of the pixels in at a logit threshold of
|
|
614
|
+
* −1, the share still in at +1. A crisp object scores near 1; a blob that
|
|
615
|
+
* fades into its surroundings scores low. Segment Anything's own mask
|
|
616
|
+
* generator filters on the same measure.
|
|
617
|
+
*/
|
|
618
|
+
export declare function maskStability(mask: Float32Array, region?: MaskRegion): number;
|
|
619
|
+
/**
|
|
620
|
+
* The decoder's candidates, best first. SlimSAM's IoU guesses sit close
|
|
621
|
+
* together and often favour a blob that spills past the object, so crisp
|
|
622
|
+
* candidates come first, ordered by IoU guess; the others follow, ordered
|
|
623
|
+
* by IoU guess weighted by stability.
|
|
624
|
+
*/
|
|
625
|
+
export declare function rankMasks(iouScores: Float32Array, masks: Float32Array, maskPixels: number, region?: MaskRegion): number[];
|
|
626
|
+
/** The best of the decoder's candidate masks (see rankMasks). */
|
|
627
|
+
export declare function pickBestMask(iouScores: Float32Array, masks: Float32Array, maskPixels: number, region?: MaskRegion): {
|
|
628
|
+
mask: Float32Array;
|
|
629
|
+
score: number;
|
|
630
|
+
};
|
|
631
|
+
/**
|
|
632
|
+
* Mask logits → opaque grayscale RGBA (sigmoid × 255), so a canvas bilinear
|
|
633
|
+
* upsample followed by a 127 threshold approximates interpolating the
|
|
634
|
+
* logits — verified equivalent on the reference implementation.
|
|
635
|
+
*/
|
|
636
|
+
export declare function maskLogitsToGray(mask: Float32Array): Uint8ClampedArray<ArrayBuffer>;
|
|
637
|
+
/** Drop all cached embeddings (frees ~8 MiB per analyzed image). */
|
|
638
|
+
export declare function clearSamCache(): void;
|
|
639
|
+
/**
|
|
640
|
+
* Encode an image into SAM embeddings, memoized per element. The decoder
|
|
641
|
+
* download is kicked off in parallel so the first click after analysis
|
|
642
|
+
* doesn't wait on it.
|
|
643
|
+
*/
|
|
644
|
+
export declare function encodeSamImage(source: HTMLImageElement | HTMLCanvasElement, options?: SamOptions): Promise<SamEmbeddings>;
|
|
645
|
+
/** Everything the decoder proposed for a set of clicks. */
|
|
646
|
+
interface SamCandidates {
|
|
647
|
+
/** Each candidate's 256×256 mask logits, one after another. */
|
|
648
|
+
masks: Float32Array;
|
|
649
|
+
/** The part of the 256² grid that holds the photo; the rest is padding. */
|
|
650
|
+
region: MaskRegion;
|
|
651
|
+
/** The candidates' indexes, best first (see rankMasks). */
|
|
652
|
+
order: number[];
|
|
653
|
+
/** The model's guess at each candidate's quality. */
|
|
654
|
+
iou: Float32Array;
|
|
655
|
+
/** The source's size. */
|
|
656
|
+
width: number;
|
|
657
|
+
height: number;
|
|
658
|
+
}
|
|
659
|
+
/** Run the prompt decoder for the given clicks, keeping every candidate. */
|
|
660
|
+
export declare function decodeSamCandidates(embeddings: SamEmbeddings, points: SamPoint[], options?: SamOptions): Promise<SamCandidates>;
|
|
661
|
+
/** One candidate's logits. */
|
|
662
|
+
export declare function candidateLogits(candidates: SamCandidates, index: number): Float32Array;
|
|
663
|
+
/**
|
|
664
|
+
* One candidate as a white-on-black mask, at the source's size or any
|
|
665
|
+
* other (a small one to draw on screen, say).
|
|
666
|
+
*/
|
|
667
|
+
export declare function candidateMask(candidates: SamCandidates, index: number, width?: number, height?: number): HTMLCanvasElement;
|
|
668
|
+
/**
|
|
669
|
+
* Run the prompt decoder for the given clicks. Returns a white-on-black
|
|
670
|
+
* binary mask canvas at the source resolution plus the model's confidence.
|
|
671
|
+
* `pick` steps through the candidates, best first (see rankMasks), and wraps
|
|
672
|
+
* around; `candidates` is how many there are to step through.
|
|
673
|
+
*/
|
|
674
|
+
export declare function decodeSamClicks(embeddings: SamEmbeddings, points: SamPoint[], options?: SamOptions, pick?: number): Promise<{
|
|
675
|
+
mask: HTMLCanvasElement;
|
|
676
|
+
score: number;
|
|
677
|
+
candidates: number;
|
|
678
|
+
}>;
|
|
679
|
+
/**
|
|
680
|
+
* Multi-object tracking by detection: the object detector runs on sampled
|
|
681
|
+
* frames, and each box is matched to the track it continues, so a bus is
|
|
682
|
+
* "bus #2" from the frame it enters to the frame it leaves. Matching is
|
|
683
|
+
* greedy on overlap with where each track should be by now (its last box
|
|
684
|
+
* moved on by its velocity), within a class — or across one when the boxes
|
|
685
|
+
* all but coincide, since detectors waver between neighbours like bicycle
|
|
686
|
+
* and motorcycle; a track is called what it was seen as most. A track is
|
|
687
|
+
* confirmed after a few sightings, so a one-frame false positive never gets
|
|
688
|
+
* a number, and it coasts through a few missed frames before it's dropped.
|
|
689
|
+
*/
|
|
690
|
+
interface TrackerOptions {
|
|
691
|
+
/**
|
|
692
|
+
* Least overlap (IoU) between a track's predicted box and a detection to
|
|
693
|
+
* match. Defaults to 0.2. Not `iouThreshold`, which is the detector's NMS.
|
|
694
|
+
*/
|
|
695
|
+
matchThreshold?: number;
|
|
696
|
+
/** Frames a track may go unseen before it's dropped. Defaults to 6. */
|
|
697
|
+
maxMissed?: number;
|
|
698
|
+
/** Sightings before a track is confirmed and numbered. Defaults to 3. */
|
|
699
|
+
minHits?: number;
|
|
700
|
+
/** Box centers kept per track. Defaults to 30. */
|
|
701
|
+
trailLength?: number;
|
|
702
|
+
}
|
|
703
|
+
/** A box that stays the same object from frame to frame. */
|
|
704
|
+
interface Track extends Detection {
|
|
705
|
+
/** 1, 2, 3… in order of confirmation. */
|
|
706
|
+
id: number;
|
|
707
|
+
label?: string;
|
|
708
|
+
/** Seconds, by the times passed to `update`. */
|
|
709
|
+
firstSeen: number;
|
|
710
|
+
lastSeen: number;
|
|
711
|
+
hits: number;
|
|
712
|
+
/** Updates since it was last seen; 0 when it's in this frame. */
|
|
713
|
+
missed: number;
|
|
714
|
+
/** Box centers, oldest first. */
|
|
715
|
+
trail: Point[];
|
|
716
|
+
}
|
|
717
|
+
interface Tracker {
|
|
718
|
+
/** Match one frame's detections; returns the confirmed tracks seen in it. */
|
|
719
|
+
update(found: readonly Detection[], time: number): Track[];
|
|
720
|
+
/** Every confirmed track so far, live or dropped, by id. */
|
|
721
|
+
tracks(): Track[];
|
|
722
|
+
reset(): void;
|
|
723
|
+
}
|
|
724
|
+
export declare function createTracker(options?: TrackerOptions): Tracker;
|
|
725
|
+
/** One tracked box in one frame, compact enough to save. */
|
|
726
|
+
interface TrackBox {
|
|
727
|
+
id: number;
|
|
728
|
+
label?: string;
|
|
729
|
+
x: number;
|
|
730
|
+
y: number;
|
|
731
|
+
w: number;
|
|
732
|
+
h: number;
|
|
733
|
+
score: number;
|
|
734
|
+
}
|
|
735
|
+
interface TrackedFrame {
|
|
736
|
+
/** Seconds into the video. */
|
|
737
|
+
time: number;
|
|
738
|
+
boxes: TrackBox[];
|
|
739
|
+
}
|
|
740
|
+
/** A track over the whole video. */
|
|
741
|
+
interface TrackSummary {
|
|
742
|
+
id: number;
|
|
743
|
+
label?: string;
|
|
744
|
+
firstSeen: number;
|
|
745
|
+
lastSeen: number;
|
|
746
|
+
/** Frames it was seen in. */
|
|
747
|
+
hits: number;
|
|
748
|
+
}
|
|
749
|
+
interface TrackedVideo {
|
|
750
|
+
fps: number;
|
|
751
|
+
frames: TrackedFrame[];
|
|
752
|
+
tracks: TrackSummary[];
|
|
753
|
+
}
|
|
754
|
+
interface TrackVideoOptions extends DetectObjectsOptions, TrackerOptions {
|
|
755
|
+
/** Frames analysed per second of video. Defaults to 6. */
|
|
756
|
+
fps?: number;
|
|
757
|
+
/** Seconds. Defaults to the whole video. */
|
|
758
|
+
start?: number;
|
|
759
|
+
end?: number;
|
|
760
|
+
/** Only these COCO classes are tracked; all of them by default. */
|
|
761
|
+
labels?: readonly string[];
|
|
762
|
+
/** Boxes smaller than this on their longer side (a fraction of the frame) are ignored. Defaults to 0. */
|
|
763
|
+
minSize?: number;
|
|
764
|
+
/** The longest edge frames are read at. Defaults to 640. */
|
|
765
|
+
maxSize?: number;
|
|
766
|
+
signal?: AbortSignal;
|
|
767
|
+
/** After each frame: its boxes, and how far through the range it is (0–1). */
|
|
768
|
+
onFrame?: (frame: TrackedFrame, progress: number) => void;
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Track objects through a video: seek to each sampled frame, detect, match.
|
|
772
|
+
* The video is paused and left at the last frame read. Boxes are normalized
|
|
773
|
+
* 0–1 over the frame.
|
|
774
|
+
*/
|
|
775
|
+
export declare function trackVideo(video: HTMLVideoElement, options?: TrackVideoOptions): Promise<TrackedVideo>;
|
|
776
|
+
/**
|
|
777
|
+
* Super-resolution via Real-ESRGAN (BSD-3-Clause): the image runs through
|
|
778
|
+
* the network tile by tile (with overlap so seams never show), each tile
|
|
779
|
+
* upscaled by the model's native factor. RGB in 0–1, CHW — the classic
|
|
780
|
+
* ESRGAN convention. Alpha, which the network doesn't model, upsamples
|
|
781
|
+
* separately with canvas filtering.
|
|
782
|
+
*/
|
|
783
|
+
export declare const DEFAULT_UPSCALE_MODEL_URL = "https://huggingface.co/fernandotonon/QtMeshEditor-realesrgan-onnx/resolve/766bac4b35aaeefe85a065ece8ee2f827b1314d8/RealESRGAN_x4plus.onnx";
|
|
784
|
+
interface UpscaleOptions extends RuntimeOptions {
|
|
785
|
+
modelUrl?: string;
|
|
786
|
+
/** Core tile edge in source pixels. Defaults to 64 (keeps WebGPU buffers small). */
|
|
787
|
+
tileSize?: number;
|
|
788
|
+
/** Context padding around each tile. Defaults to 8. */
|
|
789
|
+
tileOverlap?: number;
|
|
790
|
+
/** Reject sources with a longer edge than this. Defaults to 2048. */
|
|
791
|
+
maxInputDim?: number;
|
|
792
|
+
/** Tile-level progress — fires after each tile completes. */
|
|
793
|
+
onTileProgress?: (done: number, total: number) => void;
|
|
794
|
+
}
|
|
795
|
+
/** RGBA bytes → CHW float tensor data in 0–1 (ESRGAN convention). */
|
|
796
|
+
export declare function rgbaToChw01(data: Uint8ClampedArray, pixelCount: number): Float32Array;
|
|
797
|
+
/** CHW floats in 0–1 → opaque RGBA bytes, clamping out-of-range values. */
|
|
798
|
+
export declare function chw01ToRgba(chw: Float32Array, pixelCount: number): Uint8ClampedArray<ArrayBuffer>;
|
|
799
|
+
/**
|
|
800
|
+
* Upscale an image or canvas by the model's native factor. Returns a canvas
|
|
801
|
+
* at scale× the source dimensions.
|
|
802
|
+
*/
|
|
803
|
+
export declare function upscaleImage(source: HTMLImageElement | HTMLCanvasElement, options?: UpscaleOptions): Promise<HTMLCanvasElement>;
|
|
804
|
+
interface MlToolsOptions {
|
|
805
|
+
cutout?: CutoutOptions | false;
|
|
806
|
+
upscale?: UpscaleOptions | false;
|
|
807
|
+
erase?: InpaintOptions | false;
|
|
808
|
+
detect?: (DetectFacesOptions & {
|
|
809
|
+
objects?: DetectObjectsOptions;
|
|
810
|
+
}) | false;
|
|
811
|
+
select?: SamOptions | false;
|
|
812
|
+
depth?: DepthOptions | false;
|
|
813
|
+
denoise?: DenoiseOptions | false;
|
|
814
|
+
/** Read text: find the lines in a photo, then copy or pixelate them. */
|
|
815
|
+
text?: OcrOptions | false;
|
|
816
|
+
/** Track: follow each object through a video, then trim or crop to one. */
|
|
817
|
+
track?: Omit<TrackVideoOptions, "start" | "end" | "labels" | "signal" | "onFrame"> | false;
|
|
818
|
+
/**
|
|
819
|
+
* Open gallery results (upscale, Select's cut-out) in the editor when they finish,
|
|
820
|
+
* so the outcome is visible immediately. Defaults to true.
|
|
821
|
+
*/
|
|
822
|
+
openResults?: boolean;
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Register the ML feature groups on the editor. Call once, before opening
|
|
826
|
+
* the editor. The instance is needed so results (new images) can land in
|
|
827
|
+
* the gallery. Pass `false` per tool to skip it.
|
|
828
|
+
*/
|
|
829
|
+
export declare function installMlTools(retouch: Retouch, options?: MlToolsOptions): void;
|
|
830
|
+
/**
|
|
831
|
+
* Global inference queue: ONNX Runtime Web's WASM backend cannot run two
|
|
832
|
+
* inferences concurrently (it throws "Session already started" from a
|
|
833
|
+
* module-level guard), and interleaved WebGPU submissions compete for the
|
|
834
|
+
* same device memory. Serializing every run through one chain makes
|
|
835
|
+
* concurrent tool clicks safe instead of a crash.
|
|
836
|
+
*/
|
|
837
|
+
/** Run `task` after every previously enqueued task settles. */
|
|
838
|
+
export declare function enqueueInference<T>(task: () => Promise<T>): Promise<T>;
|
|
839
|
+
/**
|
|
840
|
+
* The Select tool's model of a selection, and the surface over the photo
|
|
841
|
+
* where you point and click. Pointing outlines what a click would select;
|
|
842
|
+
* a click selects it, and the rest of the photo dims. Adding to it and
|
|
843
|
+
* taking parts away are modes of their own (or Shift- and Alt-click), so a
|
|
844
|
+
* plain click never changes a selection by surprise.
|
|
845
|
+
*/
|
|
846
|
+
/** @deprecated Clicks no longer step through shapes; kept for the public API. */
|
|
847
|
+
export declare const SAME_SPOT = 0.015;
|
|
848
|
+
/**
|
|
849
|
+
* @deprecated Clicks no longer step through shapes; kept for the public API.
|
|
850
|
+
* True when a keep click lands on the last keep point again.
|
|
851
|
+
*/
|
|
852
|
+
export declare function isRepeatClick(points: SamPoint[], x: number, y: number, label: 0 | 1): boolean;
|
|
853
|
+
/** What a click on the photo does. */
|
|
854
|
+
type ClickMode = "new" | "add" | "remove";
|
|
855
|
+
/** The clicks that make a selection, and which of the model's shapes for them. */
|
|
856
|
+
interface Selection {
|
|
857
|
+
points: SamPoint[];
|
|
858
|
+
/** A candidate's index, or null for the one the model rates best. */
|
|
859
|
+
shape: number | null;
|
|
860
|
+
}
|
|
861
|
+
export declare const EMPTY_SELECTION: Selection;
|
|
862
|
+
/**
|
|
863
|
+
* The clicks after one more at (x, y). Shift adds and Alt takes away,
|
|
864
|
+
* whatever the mode. A new selection starts over from this click; null
|
|
865
|
+
* when there's nothing to take away from.
|
|
866
|
+
*/
|
|
867
|
+
export declare function clickedPoints(points: SamPoint[], mode: ClickMode, x: number, y: number, keys?: {
|
|
868
|
+
shift?: boolean;
|
|
869
|
+
alt?: boolean;
|
|
870
|
+
}): SamPoint[] | null;
|
|
871
|
+
interface SelectionHistory {
|
|
872
|
+
readonly current: Selection;
|
|
873
|
+
readonly canUndo: boolean;
|
|
874
|
+
readonly canRedo: boolean;
|
|
875
|
+
/** Move to a new selection, keeping the one before for undo. */
|
|
876
|
+
set(next: Selection): void;
|
|
877
|
+
/** Back one step; false when there's nothing to go back to. */
|
|
878
|
+
undo(): boolean;
|
|
879
|
+
/** Forward again after an undo; false when there's nothing undone. */
|
|
880
|
+
redo(): boolean;
|
|
881
|
+
/** Nothing selected and nothing to undo: the photo changed under it. */
|
|
882
|
+
reset(): void;
|
|
883
|
+
}
|
|
884
|
+
/** Every click, shape pick and Deselect is a step Undo takes back. */
|
|
885
|
+
export declare function createSelectionHistory(limit?: number): SelectionHistory;
|
|
886
|
+
/**
|
|
887
|
+
* The shapes worth offering for a click, smallest first: the model's
|
|
888
|
+
* candidates without the empty ones, and without any that are nearly the
|
|
889
|
+
* same as a better one.
|
|
890
|
+
*/
|
|
891
|
+
export declare function distinctShapes(candidates: SamCandidates, same?: number): number[];
|
|
892
|
+
/** Names for shapes listed smallest first. */
|
|
893
|
+
export declare function shapeLabels(count: number): string[];
|
|
894
|
+
/** True when (x, y), as fractions of the photo, falls inside the candidate. */
|
|
895
|
+
export declare function shapeContains(candidates: SamCandidates, index: number, x: number, y: number): boolean;
|
|
896
|
+
/**
|
|
897
|
+
* A square picture of just the selected thing, cut out of the photo and
|
|
898
|
+
* framed around it, as an image URL for a tile.
|
|
899
|
+
*/
|
|
900
|
+
export declare function shapeThumbnail(image: CanvasImageSource, candidates: SamCandidates, index: number, size?: number): string;
|
|
901
|
+
interface SelectSurfaceOptions {
|
|
902
|
+
/** The mouse moved over the photo (not a finger: touch has no pointing). */
|
|
903
|
+
onHover?: (x: number, y: number) => void;
|
|
904
|
+
onHoverEnd?: () => void;
|
|
905
|
+
onClick: (x: number, y: number, keys: {
|
|
906
|
+
shift: boolean;
|
|
907
|
+
alt: boolean;
|
|
908
|
+
}) => void;
|
|
909
|
+
}
|
|
910
|
+
/** What the pointer looks like over the photo. */
|
|
911
|
+
type SurfaceCursor = ClickMode | "busy" | "idle";
|
|
912
|
+
interface SelectSurfaceHandle {
|
|
913
|
+
/** The selection, drawn dimming the rest; null for none. */
|
|
914
|
+
setSelection(candidates: SamCandidates | null, index?: number): void;
|
|
915
|
+
/** What a click would select, outlined; null for none. */
|
|
916
|
+
setHover(candidates: SamCandidates | null, index?: number): void;
|
|
917
|
+
setPoints(points: SamPoint[]): void;
|
|
918
|
+
setCursor(cursor: SurfaceCursor): void;
|
|
919
|
+
setVisible(visible: boolean): void;
|
|
920
|
+
destroy(): void;
|
|
921
|
+
}
|
|
922
|
+
export declare function createSelectSurface(canvasArea: HTMLElement, handlers: SelectSurfaceOptions | ((x: number, y: number, shiftKey: boolean) => void)): SelectSurfaceHandle;
|
|
923
|
+
/**
|
|
924
|
+
* Tile-grid math for running super-resolution networks over large images:
|
|
925
|
+
* the image splits into core regions processed one at a time, each read
|
|
926
|
+
* with surrounding overlap so tile borders see real context, then only the
|
|
927
|
+
* core survives stitching — no visible seams.
|
|
928
|
+
*/
|
|
929
|
+
interface Tile {
|
|
930
|
+
/** Rect to read from the source (core plus clamped overlap). */
|
|
931
|
+
sx: number;
|
|
932
|
+
sy: number;
|
|
933
|
+
sw: number;
|
|
934
|
+
sh: number;
|
|
935
|
+
/** Core region to keep, relative to the read rect. */
|
|
936
|
+
keepX: number;
|
|
937
|
+
keepY: number;
|
|
938
|
+
keepW: number;
|
|
939
|
+
keepH: number;
|
|
940
|
+
/** Core position in source coordinates (where the kept region lands). */
|
|
941
|
+
dx: number;
|
|
942
|
+
dy: number;
|
|
943
|
+
}
|
|
944
|
+
/**
|
|
945
|
+
* Cover a width×height image with core tiles of `tileSize`, each padded by
|
|
946
|
+
* `overlap` on every side that has neighboring pixels. Cores partition the
|
|
947
|
+
* image exactly: no gaps, no double-writes.
|
|
948
|
+
*/
|
|
949
|
+
export declare function computeTileGrid(width: number, height: number, tileSize?: number, overlap?: number): Tile[];
|
|
950
|
+
/** The part of the frame on screen, 0–1. */
|
|
951
|
+
interface FrameRect {
|
|
952
|
+
x: number;
|
|
953
|
+
y: number;
|
|
954
|
+
width: number;
|
|
955
|
+
height: number;
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* The boxes at `time`, each glided between the two sampled frames around
|
|
959
|
+
* it. A track that ends or starts between them shows for the nearer half.
|
|
960
|
+
*/
|
|
961
|
+
export declare function boxesAt(result: TrackedVideo, time: number): TrackBox[];
|
|
962
|
+
/**
|
|
963
|
+
* When a track is first on screen: the first frame with its box. Later
|
|
964
|
+
* than its `firstSeen`, since a track gets its number a few sightings in.
|
|
965
|
+
*/
|
|
966
|
+
export declare function firstShown(result: TrackedVideo, id: number): number | null;
|
|
967
|
+
/**
|
|
968
|
+
* Everywhere a track went, as one box with some room around it — what
|
|
969
|
+
* "Crop to it" frames. Null when the track is never seen.
|
|
970
|
+
*/
|
|
971
|
+
export declare function trackBounds(result: TrackedVideo, id: number, margin?: number): FrameRect | null;
|
|
972
|
+
export type { BokehPrep, ClickMode, CutoutOptions, DenoiseOptions, DepthMap, DepthOptions, DepthSurfaceHandle, DetectFacesOptions, DetectObjectsOptions, Detection, EraseSurfaceHandle, FetchProgress, FocusLayers, InpaintOptions, MaskRegion, MaskStroke, MlToolsOptions, OcrOptions, Point, Region, ResilientRunResult, RuntimeOptions, SamCandidates, SamEmbeddings, SamOptions, SamPoint, SelectSurfaceHandle, SelectSurfaceOptions, Selection, SelectionHistory, SurfaceCursor, TextBox, TextLine, Tile, Track, TrackBox, TrackSummary, TrackVideoOptions, TrackedFrame, TrackedVideo, Tracker, TrackerOptions, UpscaleOptions };
|