@hackbuild/vision 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +198 -2
- package/dist/api.d.ts +55 -0
- package/dist/api.js +109 -0
- package/dist/faceapi.d.ts +37 -0
- package/dist/faceapi.js +23 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +12 -0
- package/dist/loaders.d.ts +28 -0
- package/dist/loaders.js +115 -0
- package/dist/loop.d.ts +70 -0
- package/dist/loop.js +153 -0
- package/dist/masks.d.ts +67 -0
- package/dist/masks.js +398 -0
- package/dist/mediapipe.d.ts +37 -0
- package/dist/mediapipe.js +116 -0
- package/dist/records.d.ts +22 -0
- package/dist/records.js +138 -0
- package/dist/segment.d.ts +43 -0
- package/dist/segment.js +85 -0
- package/dist/signals.d.ts +131 -0
- package/dist/signals.js +294 -0
- package/dist/single/index.iife.js +5318 -0
- package/dist/single/index.js +5236 -0
- package/dist/stubs.d.ts +26 -0
- package/dist/stubs.js +91 -0
- package/dist/types.d.ts +100 -0
- package/dist/types.js +2 -0
- package/dist/worker.d.ts +50 -0
- package/dist/worker.js +122 -0
- package/dist/yolo.d.ts +43 -0
- package/dist/yolo.js +113 -0
- package/how.ts +32 -0
- package/package.json +38 -4
package/dist/loop.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A perception loop beside a render loop: one step at a time (the earlier scan bench's
|
|
3
|
+
* busy guard), each step started no sooner than `interval(lastLatency)`
|
|
4
|
+
* after the previous one began (an earlier scene app detection cadence, the earlier chat build's fixed
|
|
5
|
+
* periods), stopped by `stop()` or an abort signal. The scheduler is
|
|
6
|
+
* injectable so tests run without timers.
|
|
7
|
+
*/
|
|
8
|
+
export interface LoopOptions<T> {
|
|
9
|
+
step: (tick: number) => Promise<T>;
|
|
10
|
+
/** ms between step starts given the last latency. Default a fixed 0 (every frame). */
|
|
11
|
+
interval?: (lastLatencyMs: number) => number;
|
|
12
|
+
onResult?: (r: T, latencyMs: number) => void;
|
|
13
|
+
onError?: (e: unknown) => void;
|
|
14
|
+
now?: () => number;
|
|
15
|
+
/** Frame scheduler; default requestAnimationFrame, else setTimeout 16 ms. */
|
|
16
|
+
schedule?: (fn: () => void) => void;
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
/** Called on each frame that found the previous step still running. */
|
|
19
|
+
onBusy?: () => void;
|
|
20
|
+
}
|
|
21
|
+
export interface Loop {
|
|
22
|
+
stop(): void;
|
|
23
|
+
readonly running: boolean;
|
|
24
|
+
readonly busy: boolean;
|
|
25
|
+
readonly lastLatencyMs: number;
|
|
26
|
+
readonly steps: number;
|
|
27
|
+
}
|
|
28
|
+
export declare function perceptionLoop<T>(o: LoopOptions<T>): Loop;
|
|
29
|
+
export interface ReadbackOptions<T> {
|
|
30
|
+
/** An async readback, e.g. three.js readRenderTargetPixelsAsync or a canvas createImageBitmap. */
|
|
31
|
+
read: () => Promise<T>;
|
|
32
|
+
/** Consumer of each frame; a slow consumer holds the loop (it runs inside the busy window). */
|
|
33
|
+
onFrame: (frame: T) => void | Promise<void>;
|
|
34
|
+
/** Rate cap. Default 10 Hz (as earlier builds did). */
|
|
35
|
+
maxHz?: number;
|
|
36
|
+
onError?: (e: unknown) => void;
|
|
37
|
+
now?: () => number;
|
|
38
|
+
schedule?: (fn: () => void) => void;
|
|
39
|
+
signal?: AbortSignal;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Agent eye style readback: one read at a time (a busy flag guards
|
|
43
|
+
* re-entry; frames while busy are counted as skipped instead of queued),
|
|
44
|
+
* capped at maxHz.
|
|
45
|
+
*/
|
|
46
|
+
export declare function readbackLoop<T>(o: ReadbackOptions<T>): Loop & {
|
|
47
|
+
readonly skipped: number;
|
|
48
|
+
};
|
|
49
|
+
/** A small LRU of results by key (an earlier relief bench keeps the depth map with the design so it never reruns). */
|
|
50
|
+
export declare class ResultCache<T> {
|
|
51
|
+
private readonly max;
|
|
52
|
+
private readonly m;
|
|
53
|
+
constructor(max?: number);
|
|
54
|
+
get(key: string): T | undefined;
|
|
55
|
+
set(key: string, v: T): void;
|
|
56
|
+
getOr(key: string, make: () => Promise<T>): Promise<T>;
|
|
57
|
+
get size(): number;
|
|
58
|
+
}
|
|
59
|
+
/** A depth map as an 8 bit grey RGBA buffer, for a canvas or a PNG (an earlier relief bench stores depth as a PNG data URL). */
|
|
60
|
+
export declare function depthToRgba(d: {
|
|
61
|
+
width: number;
|
|
62
|
+
height: number;
|
|
63
|
+
data: Float32Array;
|
|
64
|
+
}): Uint8ClampedArray;
|
|
65
|
+
/** Scale so the longest side is at most maxPx (as earlier builds did). */
|
|
66
|
+
export declare function fitSize(w: number, h: number, maxPx?: number): {
|
|
67
|
+
width: number;
|
|
68
|
+
height: number;
|
|
69
|
+
scale: number;
|
|
70
|
+
};
|
package/dist/loop.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A perception loop beside a render loop: one step at a time (the earlier scan bench's
|
|
3
|
+
* busy guard), each step started no sooner than `interval(lastLatency)`
|
|
4
|
+
* after the previous one began (an earlier scene app detection cadence, the earlier chat build's fixed
|
|
5
|
+
* periods), stopped by `stop()` or an abort signal. The scheduler is
|
|
6
|
+
* injectable so tests run without timers.
|
|
7
|
+
*/
|
|
8
|
+
export function perceptionLoop(o) {
|
|
9
|
+
const now = o.now ?? (() => (globalThis.performance ? performance.now() : Date.now()));
|
|
10
|
+
const g = globalThis;
|
|
11
|
+
const schedule = o.schedule ?? (g.requestAnimationFrame ? (f) => void g.requestAnimationFrame(f) : (f) => void setTimeout(f, 16));
|
|
12
|
+
let running = true;
|
|
13
|
+
let busy = false;
|
|
14
|
+
let last = 0;
|
|
15
|
+
let lastStart = -Infinity;
|
|
16
|
+
let steps = 0;
|
|
17
|
+
const pump = () => {
|
|
18
|
+
if (!running || o.signal?.aborted) {
|
|
19
|
+
running = false;
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const t = now();
|
|
23
|
+
if (busy)
|
|
24
|
+
o.onBusy?.();
|
|
25
|
+
else if (t - lastStart >= (o.interval?.(last) ?? 0)) {
|
|
26
|
+
busy = true;
|
|
27
|
+
lastStart = t;
|
|
28
|
+
const tick = steps++;
|
|
29
|
+
o.step(tick).then((r) => {
|
|
30
|
+
last = now() - t;
|
|
31
|
+
busy = false;
|
|
32
|
+
o.onResult?.(r, last);
|
|
33
|
+
}, (e) => {
|
|
34
|
+
last = now() - t;
|
|
35
|
+
busy = false;
|
|
36
|
+
o.onError?.(e);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
schedule(pump);
|
|
40
|
+
};
|
|
41
|
+
schedule(pump);
|
|
42
|
+
return {
|
|
43
|
+
stop: () => {
|
|
44
|
+
running = false;
|
|
45
|
+
},
|
|
46
|
+
get running() {
|
|
47
|
+
return running;
|
|
48
|
+
},
|
|
49
|
+
get busy() {
|
|
50
|
+
return busy;
|
|
51
|
+
},
|
|
52
|
+
get lastLatencyMs() {
|
|
53
|
+
return last;
|
|
54
|
+
},
|
|
55
|
+
get steps() {
|
|
56
|
+
return steps;
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Agent eye style readback: one read at a time (a busy flag guards
|
|
62
|
+
* re-entry; frames while busy are counted as skipped instead of queued),
|
|
63
|
+
* capped at maxHz.
|
|
64
|
+
*/
|
|
65
|
+
export function readbackLoop(o) {
|
|
66
|
+
let skipped = 0;
|
|
67
|
+
let inner = null;
|
|
68
|
+
const minMs = 1000 / (o.maxHz ?? 10);
|
|
69
|
+
const lo = {
|
|
70
|
+
step: async () => {
|
|
71
|
+
const f = await o.read();
|
|
72
|
+
await o.onFrame(f);
|
|
73
|
+
},
|
|
74
|
+
interval: () => minMs,
|
|
75
|
+
onBusy: () => skipped++,
|
|
76
|
+
};
|
|
77
|
+
if (o.onError)
|
|
78
|
+
lo.onError = o.onError;
|
|
79
|
+
if (o.now)
|
|
80
|
+
lo.now = o.now;
|
|
81
|
+
if (o.schedule)
|
|
82
|
+
lo.schedule = o.schedule;
|
|
83
|
+
if (o.signal)
|
|
84
|
+
lo.signal = o.signal;
|
|
85
|
+
inner = perceptionLoop(lo);
|
|
86
|
+
const l = inner;
|
|
87
|
+
return {
|
|
88
|
+
stop: () => l.stop(),
|
|
89
|
+
get running() {
|
|
90
|
+
return l.running;
|
|
91
|
+
},
|
|
92
|
+
get busy() {
|
|
93
|
+
return l.busy;
|
|
94
|
+
},
|
|
95
|
+
get lastLatencyMs() {
|
|
96
|
+
return l.lastLatencyMs;
|
|
97
|
+
},
|
|
98
|
+
get steps() {
|
|
99
|
+
return l.steps;
|
|
100
|
+
},
|
|
101
|
+
get skipped() {
|
|
102
|
+
return skipped;
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** A small LRU of results by key (an earlier relief bench keeps the depth map with the design so it never reruns). */
|
|
107
|
+
export class ResultCache {
|
|
108
|
+
max;
|
|
109
|
+
m = new Map();
|
|
110
|
+
constructor(max = 16) {
|
|
111
|
+
this.max = max;
|
|
112
|
+
}
|
|
113
|
+
get(key) {
|
|
114
|
+
const v = this.m.get(key);
|
|
115
|
+
if (v !== undefined) {
|
|
116
|
+
this.m.delete(key);
|
|
117
|
+
this.m.set(key, v);
|
|
118
|
+
}
|
|
119
|
+
return v;
|
|
120
|
+
}
|
|
121
|
+
set(key, v) {
|
|
122
|
+
this.m.delete(key);
|
|
123
|
+
this.m.set(key, v);
|
|
124
|
+
while (this.m.size > this.max)
|
|
125
|
+
this.m.delete(this.m.keys().next().value);
|
|
126
|
+
}
|
|
127
|
+
async getOr(key, make) {
|
|
128
|
+
const v = this.get(key);
|
|
129
|
+
if (v !== undefined)
|
|
130
|
+
return v;
|
|
131
|
+
const n = await make();
|
|
132
|
+
this.set(key, n);
|
|
133
|
+
return n;
|
|
134
|
+
}
|
|
135
|
+
get size() {
|
|
136
|
+
return this.m.size;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** A depth map as an 8 bit grey RGBA buffer, for a canvas or a PNG (an earlier relief bench stores depth as a PNG data URL). */
|
|
140
|
+
export function depthToRgba(d) {
|
|
141
|
+
const out = new Uint8ClampedArray(d.width * d.height * 4);
|
|
142
|
+
for (let i = 0; i < d.width * d.height; i++) {
|
|
143
|
+
const v = Math.round(Math.max(0, Math.min(1, d.data[i])) * 255);
|
|
144
|
+
out[i * 4] = out[i * 4 + 1] = out[i * 4 + 2] = v;
|
|
145
|
+
out[i * 4 + 3] = 255;
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
/** Scale so the longest side is at most maxPx (as earlier builds did). */
|
|
150
|
+
export function fitSize(w, h, maxPx = 1024) {
|
|
151
|
+
const s = Math.min(1, maxPx / Math.max(w, h));
|
|
152
|
+
return { width: Math.max(1, Math.round(w * s)), height: Math.max(1, Math.round(h * s)), scale: s };
|
|
153
|
+
}
|
package/dist/masks.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mask operations and mask export, as plain functions on `Mask` (0 to 255
|
|
3
|
+
* per pixel, 128 and up counts as inside). The operations are the earlier
|
|
4
|
+
* mask studio's set (union, subtract, invert, smooth, expand, shrink,
|
|
5
|
+
* keep the largest piece); dilate and erode use an exact distance
|
|
6
|
+
* transform, so a radius costs the same at any size and the image border
|
|
7
|
+
* is not eaten. Exports: grey PNG, PNG with the mask as alpha, an SVG
|
|
8
|
+
* outline, and COCO style run length JSON.
|
|
9
|
+
*/
|
|
10
|
+
import type { Mask, Pixels } from "./types.js";
|
|
11
|
+
/** An empty mask. */
|
|
12
|
+
export declare function emptyMask(width: number, height: number): Mask;
|
|
13
|
+
/** Inside pixels (128 and up). */
|
|
14
|
+
export declare function maskArea(m: Mask): number;
|
|
15
|
+
/** Every value to 0 or 255 at `t`. */
|
|
16
|
+
export declare function maskThreshold(m: Mask, t?: number): Mask;
|
|
17
|
+
export declare function maskUnion(a: Mask, b: Mask): Mask;
|
|
18
|
+
export declare function maskIntersect(a: Mask, b: Mask): Mask;
|
|
19
|
+
/** `a` with `b` taken out (shift with a selection tool in the earlier mask studio). */
|
|
20
|
+
export declare function maskSubtract(a: Mask, b: Mask): Mask;
|
|
21
|
+
export declare function maskInvert(m: Mask): Mask;
|
|
22
|
+
/** Grow by a disc of radius `r` pixels (expand). */
|
|
23
|
+
export declare function maskDilate(m: Mask, r: number): Mask;
|
|
24
|
+
/** Shrink by a disc of radius `r` pixels; the image border does not count as outside. */
|
|
25
|
+
export declare function maskErode(m: Mask, r: number): Mask;
|
|
26
|
+
/** Soft edges: a gaussian of radius `r` with sigma r / 2 (the earlier mask studio's smooth, before its rethreshold), edges clamped. */
|
|
27
|
+
export declare function maskFeather(m: Mask, r: number): Mask;
|
|
28
|
+
/** Keep only the largest connected piece (8 connected by default). */
|
|
29
|
+
export declare function maskLargestComponent(m: Mask, connectivity?: 4 | 8): Mask;
|
|
30
|
+
/** Grey RGBA, opaque, for a canvas or a PNG. */
|
|
31
|
+
export declare function maskToRgba(m: Mask): Uint8ClampedArray;
|
|
32
|
+
/** The image's RGBA with the mask as alpha (the cutout). */
|
|
33
|
+
export declare function cutoutRgba(image: Pixels, m: Mask): Uint8ClampedArray;
|
|
34
|
+
/**
|
|
35
|
+
* A PNG file from RGBA (4 channels) or grey (1 channel) bytes. Deflates
|
|
36
|
+
* through CompressionStream where the runtime has one, stored blocks
|
|
37
|
+
* otherwise or with `compress: false`.
|
|
38
|
+
*/
|
|
39
|
+
export declare function encodePng(width: number, height: number, data: ArrayLike<number>, o?: {
|
|
40
|
+
channels?: 1 | 4;
|
|
41
|
+
compress?: boolean;
|
|
42
|
+
}): Promise<Uint8Array>;
|
|
43
|
+
/** The mask as a grey PNG. */
|
|
44
|
+
export declare function maskToPng(m: Mask, o?: {
|
|
45
|
+
compress?: boolean;
|
|
46
|
+
}): Promise<Uint8Array>;
|
|
47
|
+
/** The image with the mask as alpha, as a PNG (the cutout). */
|
|
48
|
+
export declare function cutoutPng(image: Pixels, m: Mask, o?: {
|
|
49
|
+
compress?: boolean;
|
|
50
|
+
}): Promise<Uint8Array>;
|
|
51
|
+
/**
|
|
52
|
+
* Outline loops along pixel edges, inside on the right going clockwise
|
|
53
|
+
* in image space (y down); holes run the other way. Points are pixel
|
|
54
|
+
* corners, collinear runs merged.
|
|
55
|
+
*/
|
|
56
|
+
export declare function maskOutline(m: Mask): [number, number][][];
|
|
57
|
+
/** The outline as an SVG file, one even odd path in image pixels. */
|
|
58
|
+
export declare function maskToSvg(m: Mask, o?: {
|
|
59
|
+
fill?: string;
|
|
60
|
+
}): string;
|
|
61
|
+
/** COCO style uncompressed run length: column major, the first run counts outside pixels. */
|
|
62
|
+
export interface MaskRle {
|
|
63
|
+
size: [height: number, width: number];
|
|
64
|
+
counts: number[];
|
|
65
|
+
}
|
|
66
|
+
export declare function maskToRle(m: Mask): MaskRle;
|
|
67
|
+
export declare function maskFromRle(r: MaskRle): Mask;
|
package/dist/masks.js
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mask operations and mask export, as plain functions on `Mask` (0 to 255
|
|
3
|
+
* per pixel, 128 and up counts as inside). The operations are the earlier
|
|
4
|
+
* mask studio's set (union, subtract, invert, smooth, expand, shrink,
|
|
5
|
+
* keep the largest piece); dilate and erode use an exact distance
|
|
6
|
+
* transform, so a radius costs the same at any size and the image border
|
|
7
|
+
* is not eaten. Exports: grey PNG, PNG with the mask as alpha, an SVG
|
|
8
|
+
* outline, and COCO style run length JSON.
|
|
9
|
+
*/
|
|
10
|
+
const ON = 128;
|
|
11
|
+
function same(what, a, b) {
|
|
12
|
+
if (a.width !== b.width || a.height !== b.height)
|
|
13
|
+
throw new RangeError(`${what}: masks are ${a.width} x ${a.height} and ${b.width} x ${b.height}`);
|
|
14
|
+
}
|
|
15
|
+
const make = (m, data) => ({ width: m.width, height: m.height, data });
|
|
16
|
+
/** An empty mask. */
|
|
17
|
+
export function emptyMask(width, height) {
|
|
18
|
+
return { width, height, data: new Uint8Array(width * height) };
|
|
19
|
+
}
|
|
20
|
+
/** Inside pixels (128 and up). */
|
|
21
|
+
export function maskArea(m) {
|
|
22
|
+
let n = 0;
|
|
23
|
+
for (const v of m.data)
|
|
24
|
+
if (v >= ON)
|
|
25
|
+
n++;
|
|
26
|
+
return n;
|
|
27
|
+
}
|
|
28
|
+
/** Every value to 0 or 255 at `t`. */
|
|
29
|
+
export function maskThreshold(m, t = ON) {
|
|
30
|
+
return make(m, m.data.map((v) => (v >= t ? 255 : 0)));
|
|
31
|
+
}
|
|
32
|
+
export function maskUnion(a, b) {
|
|
33
|
+
same("maskUnion", a, b);
|
|
34
|
+
return make(a, a.data.map((v, i) => Math.max(v, b.data[i])));
|
|
35
|
+
}
|
|
36
|
+
export function maskIntersect(a, b) {
|
|
37
|
+
same("maskIntersect", a, b);
|
|
38
|
+
return make(a, a.data.map((v, i) => Math.min(v, b.data[i])));
|
|
39
|
+
}
|
|
40
|
+
/** `a` with `b` taken out (shift with a selection tool in the earlier mask studio). */
|
|
41
|
+
export function maskSubtract(a, b) {
|
|
42
|
+
same("maskSubtract", a, b);
|
|
43
|
+
return make(a, a.data.map((v, i) => Math.min(v, 255 - b.data[i])));
|
|
44
|
+
}
|
|
45
|
+
export function maskInvert(m) {
|
|
46
|
+
return make(m, m.data.map((v) => 255 - v));
|
|
47
|
+
}
|
|
48
|
+
const INF = 1e20;
|
|
49
|
+
/** Squared distance to the nearest source cell, exact (Felzenszwalb and Huttenlocher, 2012). */
|
|
50
|
+
function distance2(src, w, h) {
|
|
51
|
+
const d = new Float64Array(w * h);
|
|
52
|
+
for (let i = 0; i < w * h; i++)
|
|
53
|
+
d[i] = src(i) ? 0 : INF;
|
|
54
|
+
const n = Math.max(w, h);
|
|
55
|
+
const f = new Float64Array(n);
|
|
56
|
+
const out = new Float64Array(n);
|
|
57
|
+
const v = new Int32Array(n);
|
|
58
|
+
const z = new Float64Array(n + 1);
|
|
59
|
+
const pass = (len, get, put) => {
|
|
60
|
+
for (let q = 0; q < len; q++)
|
|
61
|
+
f[q] = get(q);
|
|
62
|
+
let k = 0;
|
|
63
|
+
v[0] = 0;
|
|
64
|
+
z[0] = -INF;
|
|
65
|
+
z[1] = INF;
|
|
66
|
+
for (let q = 1; q < len; q++) {
|
|
67
|
+
let s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
|
|
68
|
+
while (s <= z[k]) {
|
|
69
|
+
k--;
|
|
70
|
+
s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
|
|
71
|
+
}
|
|
72
|
+
k++;
|
|
73
|
+
v[k] = q;
|
|
74
|
+
z[k] = s;
|
|
75
|
+
z[k + 1] = INF;
|
|
76
|
+
}
|
|
77
|
+
k = 0;
|
|
78
|
+
for (let q = 0; q < len; q++) {
|
|
79
|
+
while (z[k + 1] < q)
|
|
80
|
+
k++;
|
|
81
|
+
out[q] = (q - v[k]) ** 2 + f[v[k]];
|
|
82
|
+
}
|
|
83
|
+
for (let q = 0; q < len; q++)
|
|
84
|
+
put(q, out[q]);
|
|
85
|
+
};
|
|
86
|
+
for (let x = 0; x < w; x++)
|
|
87
|
+
pass(h, (y) => d[y * w + x], (y, val) => (d[y * w + x] = val));
|
|
88
|
+
for (let y = 0; y < h; y++)
|
|
89
|
+
pass(w, (x) => d[y * w + x], (x, val) => (d[y * w + x] = val));
|
|
90
|
+
return d;
|
|
91
|
+
}
|
|
92
|
+
/** Grow by a disc of radius `r` pixels (expand). */
|
|
93
|
+
export function maskDilate(m, r) {
|
|
94
|
+
if (r <= 0)
|
|
95
|
+
return maskThreshold(m);
|
|
96
|
+
const d = distance2((i) => m.data[i] >= ON, m.width, m.height);
|
|
97
|
+
return make(m, Uint8Array.from(d, (v) => (v <= r * r ? 255 : 0)));
|
|
98
|
+
}
|
|
99
|
+
/** Shrink by a disc of radius `r` pixels; the image border does not count as outside. */
|
|
100
|
+
export function maskErode(m, r) {
|
|
101
|
+
if (r <= 0)
|
|
102
|
+
return maskThreshold(m);
|
|
103
|
+
const d = distance2((i) => m.data[i] < ON, m.width, m.height);
|
|
104
|
+
return make(m, Uint8Array.from(d, (v) => (v > r * r ? 255 : 0)));
|
|
105
|
+
}
|
|
106
|
+
/** Soft edges: a gaussian of radius `r` with sigma r / 2 (the earlier mask studio's smooth, before its rethreshold), edges clamped. */
|
|
107
|
+
export function maskFeather(m, r) {
|
|
108
|
+
if (r <= 0)
|
|
109
|
+
return make(m, m.data.slice());
|
|
110
|
+
const { width: w, height: h } = m;
|
|
111
|
+
const R = Math.ceil(r);
|
|
112
|
+
const sig = r / 2;
|
|
113
|
+
const k = new Float64Array(2 * R + 1);
|
|
114
|
+
let sum = 0;
|
|
115
|
+
for (let i = -R; i <= R; i++)
|
|
116
|
+
sum += k[i + R] = Math.exp(-(i * i) / (2 * sig * sig));
|
|
117
|
+
for (let i = 0; i < k.length; i++)
|
|
118
|
+
k[i] /= sum;
|
|
119
|
+
const tmp = new Float64Array(w * h);
|
|
120
|
+
for (let y = 0; y < h; y++)
|
|
121
|
+
for (let x = 0; x < w; x++) {
|
|
122
|
+
let v = 0;
|
|
123
|
+
for (let i = -R; i <= R; i++)
|
|
124
|
+
v += m.data[y * w + Math.min(w - 1, Math.max(0, x + i))] * k[i + R];
|
|
125
|
+
tmp[y * w + x] = v;
|
|
126
|
+
}
|
|
127
|
+
const out = new Uint8Array(w * h);
|
|
128
|
+
for (let y = 0; y < h; y++)
|
|
129
|
+
for (let x = 0; x < w; x++) {
|
|
130
|
+
let v = 0;
|
|
131
|
+
for (let i = -R; i <= R; i++)
|
|
132
|
+
v += tmp[Math.min(h - 1, Math.max(0, y + i)) * w + x] * k[i + R];
|
|
133
|
+
out[y * w + x] = Math.round(v);
|
|
134
|
+
}
|
|
135
|
+
return make(m, out);
|
|
136
|
+
}
|
|
137
|
+
/** Keep only the largest connected piece (8 connected by default). */
|
|
138
|
+
export function maskLargestComponent(m, connectivity = 8) {
|
|
139
|
+
const { width: w, height: h } = m;
|
|
140
|
+
const label = new Int32Array(w * h);
|
|
141
|
+
const stack = new Int32Array(w * h);
|
|
142
|
+
let best = 0;
|
|
143
|
+
let bestSize = 0;
|
|
144
|
+
let next = 0;
|
|
145
|
+
for (let s = 0; s < w * h; s++) {
|
|
146
|
+
if (label[s] || m.data[s] < ON)
|
|
147
|
+
continue;
|
|
148
|
+
next++;
|
|
149
|
+
let top = 0;
|
|
150
|
+
let size = 0;
|
|
151
|
+
stack[top++] = s;
|
|
152
|
+
label[s] = next;
|
|
153
|
+
while (top) {
|
|
154
|
+
const i = stack[--top];
|
|
155
|
+
size++;
|
|
156
|
+
const x = i % w;
|
|
157
|
+
const y = (i - x) / w;
|
|
158
|
+
for (let dy = -1; dy <= 1; dy++)
|
|
159
|
+
for (let dx = -1; dx <= 1; dx++) {
|
|
160
|
+
if ((!dx && !dy) || (connectivity === 4 && dx && dy))
|
|
161
|
+
continue;
|
|
162
|
+
const nx = x + dx;
|
|
163
|
+
const ny = y + dy;
|
|
164
|
+
if (nx < 0 || ny < 0 || nx >= w || ny >= h)
|
|
165
|
+
continue;
|
|
166
|
+
const j = ny * w + nx;
|
|
167
|
+
if (label[j] || m.data[j] < ON)
|
|
168
|
+
continue;
|
|
169
|
+
label[j] = next;
|
|
170
|
+
stack[top++] = j;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (size > bestSize) {
|
|
174
|
+
bestSize = size;
|
|
175
|
+
best = next;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return make(m, Uint8Array.from(label, (l) => (best && l === best ? 255 : 0)));
|
|
179
|
+
}
|
|
180
|
+
/** Grey RGBA, opaque, for a canvas or a PNG. */
|
|
181
|
+
export function maskToRgba(m) {
|
|
182
|
+
const out = new Uint8ClampedArray(m.width * m.height * 4);
|
|
183
|
+
for (let i = 0; i < m.data.length; i++) {
|
|
184
|
+
const v = m.data[i];
|
|
185
|
+
out[i * 4] = out[i * 4 + 1] = out[i * 4 + 2] = v;
|
|
186
|
+
out[i * 4 + 3] = 255;
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
190
|
+
/** The image's RGBA with the mask as alpha (the cutout). */
|
|
191
|
+
export function cutoutRgba(image, m) {
|
|
192
|
+
if (image.width !== m.width || image.height !== m.height)
|
|
193
|
+
throw new RangeError(`cutoutRgba: image is ${image.width} x ${image.height}, mask ${m.width} x ${m.height}`);
|
|
194
|
+
const out = new Uint8ClampedArray(image.data);
|
|
195
|
+
for (let i = 0; i < m.data.length; i++)
|
|
196
|
+
out[i * 4 + 3] = Math.min(out[i * 4 + 3], m.data[i]);
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
const CRC = (() => {
|
|
200
|
+
const t = new Uint32Array(256);
|
|
201
|
+
for (let n = 0; n < 256; n++) {
|
|
202
|
+
let c = n;
|
|
203
|
+
for (let k = 0; k < 8; k++)
|
|
204
|
+
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
205
|
+
t[n] = c >>> 0;
|
|
206
|
+
}
|
|
207
|
+
return t;
|
|
208
|
+
})();
|
|
209
|
+
function crc32(b) {
|
|
210
|
+
let c = 0xffffffff;
|
|
211
|
+
for (const v of b)
|
|
212
|
+
c = CRC[(c ^ v) & 0xff] ^ (c >>> 8);
|
|
213
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
214
|
+
}
|
|
215
|
+
/** zlib with stored blocks, for runtimes without CompressionStream. */
|
|
216
|
+
function zlibStored(raw) {
|
|
217
|
+
const blocks = Math.max(1, Math.ceil(raw.length / 65535));
|
|
218
|
+
const out = new Uint8Array(2 + raw.length + blocks * 5 + 4);
|
|
219
|
+
out[0] = 0x78;
|
|
220
|
+
out[1] = 0x01;
|
|
221
|
+
let o = 2;
|
|
222
|
+
for (let b = 0; b < blocks; b++) {
|
|
223
|
+
const s = b * 65535;
|
|
224
|
+
const n = Math.min(65535, raw.length - s);
|
|
225
|
+
out[o++] = b === blocks - 1 ? 1 : 0;
|
|
226
|
+
out[o++] = n & 0xff;
|
|
227
|
+
out[o++] = n >>> 8;
|
|
228
|
+
out[o++] = ~n & 0xff;
|
|
229
|
+
out[o++] = (~n >>> 8) & 0xff;
|
|
230
|
+
out.set(raw.subarray(s, s + n), o);
|
|
231
|
+
o += n;
|
|
232
|
+
}
|
|
233
|
+
let a = 1;
|
|
234
|
+
let c = 0;
|
|
235
|
+
for (const v of raw) {
|
|
236
|
+
a = (a + v) % 65521;
|
|
237
|
+
c = (c + a) % 65521;
|
|
238
|
+
}
|
|
239
|
+
new DataView(out.buffer).setUint32(o, ((c << 16) | a) >>> 0);
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
async function zlib(raw, compress) {
|
|
243
|
+
const CS = globalThis.CompressionStream;
|
|
244
|
+
if (!compress || !CS)
|
|
245
|
+
return zlibStored(raw);
|
|
246
|
+
const cs = new CS("deflate");
|
|
247
|
+
const w = cs.writable.getWriter();
|
|
248
|
+
void w.write(raw);
|
|
249
|
+
void w.close();
|
|
250
|
+
return new Uint8Array(await new Response(cs.readable).arrayBuffer());
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* A PNG file from RGBA (4 channels) or grey (1 channel) bytes. Deflates
|
|
254
|
+
* through CompressionStream where the runtime has one, stored blocks
|
|
255
|
+
* otherwise or with `compress: false`.
|
|
256
|
+
*/
|
|
257
|
+
export async function encodePng(width, height, data, o = {}) {
|
|
258
|
+
const ch = o.channels ?? 4;
|
|
259
|
+
if (data.length < width * height * ch)
|
|
260
|
+
throw new RangeError(`encodePng: ${data.length} bytes for ${width} x ${height} x ${ch}`);
|
|
261
|
+
const row = width * ch;
|
|
262
|
+
const raw = new Uint8Array((row + 1) * height);
|
|
263
|
+
for (let y = 0; y < height; y++)
|
|
264
|
+
for (let i = 0; i < row; i++)
|
|
265
|
+
raw[y * (row + 1) + 1 + i] = data[y * row + i];
|
|
266
|
+
const idat = await zlib(raw, o.compress ?? true);
|
|
267
|
+
const ihdr = new Uint8Array(13);
|
|
268
|
+
const dv = new DataView(ihdr.buffer);
|
|
269
|
+
dv.setUint32(0, width);
|
|
270
|
+
dv.setUint32(4, height);
|
|
271
|
+
ihdr[8] = 8;
|
|
272
|
+
ihdr[9] = ch === 4 ? 6 : 0;
|
|
273
|
+
const chunks = [
|
|
274
|
+
["IHDR", ihdr],
|
|
275
|
+
["IDAT", idat],
|
|
276
|
+
["IEND", new Uint8Array(0)],
|
|
277
|
+
];
|
|
278
|
+
const size = 8 + chunks.reduce((s, [, d]) => s + 12 + d.length, 0);
|
|
279
|
+
const out = new Uint8Array(size);
|
|
280
|
+
out.set([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
281
|
+
const ov = new DataView(out.buffer);
|
|
282
|
+
let p = 8;
|
|
283
|
+
for (const [t, d] of chunks) {
|
|
284
|
+
ov.setUint32(p, d.length);
|
|
285
|
+
const td = new Uint8Array(4 + d.length);
|
|
286
|
+
for (let i = 0; i < 4; i++)
|
|
287
|
+
td[i] = t.charCodeAt(i);
|
|
288
|
+
td.set(d, 4);
|
|
289
|
+
out.set(td, p + 4);
|
|
290
|
+
ov.setUint32(p + 8 + d.length, crc32(td));
|
|
291
|
+
p += 12 + d.length;
|
|
292
|
+
}
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
/** The mask as a grey PNG. */
|
|
296
|
+
export function maskToPng(m, o = {}) {
|
|
297
|
+
return encodePng(m.width, m.height, m.data, { ...o, channels: 1 });
|
|
298
|
+
}
|
|
299
|
+
/** The image with the mask as alpha, as a PNG (the cutout). */
|
|
300
|
+
export function cutoutPng(image, m, o = {}) {
|
|
301
|
+
return encodePng(m.width, m.height, cutoutRgba(image, m), { ...o, channels: 4 });
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Outline loops along pixel edges, inside on the right going clockwise
|
|
305
|
+
* in image space (y down); holes run the other way. Points are pixel
|
|
306
|
+
* corners, collinear runs merged.
|
|
307
|
+
*/
|
|
308
|
+
export function maskOutline(m) {
|
|
309
|
+
const { width: w, height: h } = m;
|
|
310
|
+
const W = w + 1;
|
|
311
|
+
const inside = (x, y) => x >= 0 && y >= 0 && x < w && y < h && m.data[y * w + x] >= ON;
|
|
312
|
+
const out = new Map();
|
|
313
|
+
const edge = (ax, ay, bx, by) => {
|
|
314
|
+
const k = ay * W + ax;
|
|
315
|
+
const l = out.get(k);
|
|
316
|
+
if (l)
|
|
317
|
+
l.push(by * W + bx);
|
|
318
|
+
else
|
|
319
|
+
out.set(k, [by * W + bx]);
|
|
320
|
+
};
|
|
321
|
+
for (let y = 0; y < h; y++)
|
|
322
|
+
for (let x = 0; x < w; x++) {
|
|
323
|
+
if (!inside(x, y))
|
|
324
|
+
continue;
|
|
325
|
+
if (!inside(x, y - 1))
|
|
326
|
+
edge(x, y, x + 1, y);
|
|
327
|
+
if (!inside(x + 1, y))
|
|
328
|
+
edge(x + 1, y, x + 1, y + 1);
|
|
329
|
+
if (!inside(x, y + 1))
|
|
330
|
+
edge(x + 1, y + 1, x, y + 1);
|
|
331
|
+
if (!inside(x - 1, y))
|
|
332
|
+
edge(x, y + 1, x, y);
|
|
333
|
+
}
|
|
334
|
+
const loops = [];
|
|
335
|
+
for (const start of [...out.keys()]) {
|
|
336
|
+
while (out.get(start)?.length) {
|
|
337
|
+
const pts = [start];
|
|
338
|
+
let cur = start;
|
|
339
|
+
for (;;) {
|
|
340
|
+
const l = out.get(cur);
|
|
341
|
+
const nx = l.pop();
|
|
342
|
+
if (!l.length)
|
|
343
|
+
out.delete(cur);
|
|
344
|
+
if (nx === start)
|
|
345
|
+
break;
|
|
346
|
+
pts.push(nx);
|
|
347
|
+
cur = nx;
|
|
348
|
+
}
|
|
349
|
+
const xy = pts.map((k) => [k % W, Math.floor(k / W)]);
|
|
350
|
+
const keep = xy.filter((p, i) => {
|
|
351
|
+
const a = xy[(i - 1 + xy.length) % xy.length];
|
|
352
|
+
const b = xy[(i + 1) % xy.length];
|
|
353
|
+
return (p[0] - a[0]) * (b[1] - p[1]) - (p[1] - a[1]) * (b[0] - p[0]) !== 0;
|
|
354
|
+
});
|
|
355
|
+
loops.push(keep);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return loops;
|
|
359
|
+
}
|
|
360
|
+
/** The outline as an SVG file, one even odd path in image pixels. */
|
|
361
|
+
export function maskToSvg(m, o = {}) {
|
|
362
|
+
const d = maskOutline(m)
|
|
363
|
+
.map((l) => `M${l.map((p) => `${p[0]} ${p[1]}`).join("L")}Z`)
|
|
364
|
+
.join("");
|
|
365
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${m.width} ${m.height}" width="${m.width}" height="${m.height}"><path d="${d}" fill="${o.fill ?? "#000"}" fill-rule="evenodd"/></svg>`;
|
|
366
|
+
}
|
|
367
|
+
export function maskToRle(m) {
|
|
368
|
+
const { width: w, height: h } = m;
|
|
369
|
+
const counts = [];
|
|
370
|
+
let cur = false;
|
|
371
|
+
let run = 0;
|
|
372
|
+
for (let x = 0; x < w; x++)
|
|
373
|
+
for (let y = 0; y < h; y++) {
|
|
374
|
+
const v = m.data[y * w + x] >= ON;
|
|
375
|
+
if (v !== cur) {
|
|
376
|
+
counts.push(run);
|
|
377
|
+
run = 0;
|
|
378
|
+
cur = v;
|
|
379
|
+
}
|
|
380
|
+
run++;
|
|
381
|
+
}
|
|
382
|
+
counts.push(run);
|
|
383
|
+
return { size: [h, w], counts };
|
|
384
|
+
}
|
|
385
|
+
export function maskFromRle(r) {
|
|
386
|
+
const [h, w] = r.size;
|
|
387
|
+
const data = new Uint8Array(w * h);
|
|
388
|
+
let i = 0;
|
|
389
|
+
r.counts.forEach((n, k) => {
|
|
390
|
+
if (k % 2)
|
|
391
|
+
for (let j = i; j < i + n; j++)
|
|
392
|
+
data[(j % h) * w + Math.floor(j / h)] = 255;
|
|
393
|
+
i += n;
|
|
394
|
+
});
|
|
395
|
+
if (i !== w * h)
|
|
396
|
+
throw new RangeError(`maskFromRle: counts cover ${i} pixels of ${w * h}`);
|
|
397
|
+
return { width: w, height: h, data };
|
|
398
|
+
}
|