inlaytrace 0.3.1 → 0.5.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 CHANGED
@@ -1,5 +1,27 @@
1
1
  # inlaytrace
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - New `deblur` option (and `--deblur` on the command line) for soft photos, screenshots and enlarged copies of flat-colour art. A blurred edge is a ramp, and its middle traced as a band of an in-between colour round every shape. `deblur` measures the blur place by place, finds the flat colours the image is made of, and works out the flat shapes that, blurred the same way, look like the image; those are traced instead, their straight edges drawn as true lines and their corners kept. It tells a lens's blur from a resize's, which decides where each edge sits, and takes out a colour fringe on the way. Images whose edges measure crisp are left as they are. `traceAsync` reports it as a `'deblur'` stage, pausing after each sweep of its search, so it can be cancelled. On a soft photo of a dump-truck logo the Logo SVG went from 411 KB with a halo round every shape to 71 KB without. Also exported: `deblur(rgba, width, height)` and `edgeBlur(rgba, width, height)`, which measures how soft an image's edges are, in px.
8
+ - Exact shapes are chosen by drawing them: a shape near the fit limits is kept only if it covers the region as well as the free fit, and a small regular polygon (a hexagon a few pixels across) is no longer drawn as a circle.
9
+ - New `traceAsync(image, { signal, onProgress, …options })`: the same trace as `trace`, but it pauses between stages to report progress, gives the thread time to do other work, and stops when its `AbortSignal` aborts.
10
+
11
+ ### Patch Changes
12
+
13
+ - Logo and Illustration keep a flat colour that sits close to another one, when there's room under the colour cap: a truck logo's neutral-grey grille bars and tyre treads, 0.057 from its blue-grey cab in OKLab, used to trace as the cab, smeared with navy. Only flat art gets this (four in five pixels flat), and gradients' in-between shades are left out, so photos and soft shading trace as before. A shade between two close colours (the truck's bumper) now takes one of them for its whole region, instead of blotches of both.
14
+ - A barely-there gradient in a background (a near-white vignette) no longer traces as ragged bands of close tints: Logo, Illustration and Outline art join them into one flat shape in their commonest colour. Only close colours the image passes between without an edge are joined, so a pale fill on white stays a shape, and your own palette keeps every colour. On a dump-truck logo the Logo SVG went from 107 to 63 KB.
15
+
16
+ ## 0.4.0
17
+
18
+ ### Minor Changes
19
+
20
+ - A command line: `npx inlaytrace logo.png -o logo.svg --preset logo`. PNGs are read with Node's own zlib, so the package still has no dependencies; JPEG, WebP, GIF and TIFF use sharp when it's installed beside it. `--help` lists the flags, which follow the trace options.
21
+ - New `grayscale` option for the colour presets (not `pixel`): trace in greys only, `colors` of them, each pixel taken as the grey of its own OKLab lightness.
22
+ - Presets in the package, and a simpler call: `trace(image, { preset: 'logo' })`. `image` is anything shaped like ImageData (`{ data, width, height }`). The seven presets the app uses (`logo`, `illustration`, `outline`, `lineart`, `centerline`, `poster`, `pixel`) each pick their own palette and carry their own defaults, and any option overrides them. `palette` traces in your own colours, `layers` replaces `stacked`, `invert` traces light ink, and `presets` lists every default. Centerline paths are now `{ d, fill, stroke }` like Outline art's lines (`fill` the colour, `stroke` the width). `trace(rgba, width, height, options)`, `traceCenterline` and `centerlineToSvg` still work but are deprecated, and go in 1.0.
23
+ - The package entry no longer exports `mergeLabels`, `otsu`, `staircase` or `colorAt`. They were internals, exported for the app's tests and never documented. Everything left is in the API reference and stays through 1.0.
24
+
3
25
  ## 0.3.1
4
26
 
5
27
  ### Patch Changes
package/README.md CHANGED
@@ -27,38 +27,54 @@ shows which commit built it.
27
27
  Versions are 0.x while the API settles: a minor version (0.1 → 0.2) may change
28
28
  it, and the [changelog](https://github.com/mtblck/inlaytrace/blob/main/packages/inlay/CHANGELOG.md)
29
29
  says how.
30
+ From 1.0, a minor version can change the traced output (different paths or
31
+ colours) but not the API, and never makes the measured quality worse; a major
32
+ version is any change to an export, option, preset or result type. Pin an exact
33
+ version if you need byte-identical SVGs. The [full policy](https://github.com/mtblck/inlaytrace/blob/main/docs/package.md#versions)
34
+ says what counts as what.
30
35
 
31
36
  ## Use
32
37
 
33
38
  ```ts
34
- import { trace, toSvg, peakPalette } from 'inlaytrace'
39
+ import { trace, toSvg } from 'inlaytrace'
35
40
 
36
- // RGBA pixels, e.g. from canvas getImageData().data
37
- const result = trace(rgba, width, height, {
38
- mode: 'palette',
39
- palette: peakPalette(rgba, 8), // the image's main colours, as #rrggbb
40
- speckle: 8, // merge regions smaller than 8 × 8 px into their surroundings
41
- tolerance: 1, // px the fitted outline may stray from the pixels
42
- cornerAngle: 45, // turns sharper than this stay corners
43
- })
41
+ // Anything shaped like ImageData: { data: RGBA bytes, width, height }
42
+ const result = trace(image, { preset: 'logo' })
44
43
 
45
44
  result.paths // [{ d: 'M…Z', fill: '#rrggbb' }, …] largest first, nonzero fill;
46
- // with `strokes`, lines last: { d, fill, stroke: width }, stroked in `fill`, unfilled
45
+ // lines (Outline art, Centerline) are { d, fill, stroke: width }, stroked in `fill`, unfilled
47
46
  toSvg(result) // '<svg …>…</svg>'
48
47
  ```
49
48
 
50
- ### Modes
49
+ ### Command line
51
50
 
52
- | Options | For |
51
+ ```bash
52
+ npx inlaytrace logo.png -o logo.svg
53
+ npx inlaytrace photo.jpg -o photo.svg --preset poster --colors 16
54
+ ```
55
+
56
+ PNGs need nothing else. For JPEG, WebP, GIF or TIFF, install
57
+ [sharp](https://sharp.pixelplumbing.com/) beside it (`npm install sharp`). Without
58
+ `-o` the SVG goes to stdout. `npx inlaytrace --help` lists the options.
59
+
60
+ ### Presets
61
+
62
+ | Preset | For |
53
63
  | --- | --- |
54
- | `mode: 'palette', palette` | Flat colour art. `palette` is the colours to label pixels with: `peakPalette(rgba, n, { width })` takes the sharp peaks of the histogram (flat art's real colours), and given the image's width also pale tints found by their flatness (a light fill on white); `exactPalette(rgba, n)` takes the image's exact colours, most-used first. |
55
- | `mode: 'palette', palette, merge` | Fold colours together before regions are built, so the edge between them disappears: `{ '#from': '#into' }`. |
56
- | `mode: 'palette', palette: exactPalette(…), pixels: true` | Pixel art: no clean-up of lone pixels, no curve fitting; every boundary is its pixel staircase with straight runs joined. |
57
- | `mode: 'palette', palette, strokes: true` | Outline art: colours drawn mostly as thin, long lines (2.5–8 px wide; give `scale` if the image was enlarged) are traced down their middle as round-capped strokes at the measured width, and the shapes either side meet beneath them. Short marks, small lettering and solid shapes stay shapes. |
58
- | `mode: 'palette', palette, gradients: true` | Soft shading as gradients: neighbouring tints that are bands of one smooth shade become one shape with a linear or radial gradient (`path.gradient`; `fill` is its average colour), when the gradient fits far better than a flat colour. For screens and print, not cutters. |
59
- | `mode: 'palette', palette, stacked: true` | Flat art as layers: each shape whole, back to front. Which of two touching shapes is in front comes from the junctions where their edge ends, and a shape partly hidden is completed underneath (a circle, a corner, or a smooth continuation), so a disc behind a bar is a whole disc. |
60
- | `mode: 'palette', palette: quantizePalette(…), stacked: true, photo: true` | Photos as flat colour bands. `quantizePalette(rgba, n)` clusters the image's colours (k-means in OKLab, deterministic); `stacked` draws each shape whole, larger first, instead of cutting holes. |
61
- | `mode: 'binary', threshold` | Line art: ink darker than `threshold` (0–255), the image's own ink/paper split when `'auto'` (Otsu; coloured ink works too), or adaptive per neighbourhood when `null`. Only the ink is drawn. |
64
+ | `logo` (default) | Few flat colours (8), crisp corners, shapes cut out to tile, exact circles and rectangles. |
65
+ | `illustration` | More colours (24), smooth curves, shapes in layers (each whole, a disc behind a bar stays a disc), soft shading as gradients. |
66
+ | `outline` | Illustration, with thin drawn outlines (2.5–8 px; give `scale` if the image was enlarged) traced down their middle as round-capped strokes, and the shapes either side meeting beneath them. |
67
+ | `lineart` | Ink drawings and scans: ink darker than the image's own ink/paper split (Otsu; coloured ink works too), small breaks in lines closed. Only the ink is drawn. |
68
+ | `centerline` | Single strokes down the middle of the ink, at the width measured from it, for pen plotters and engraving. |
69
+ | `poster` | Photos as flat colour bands: colours clustered (k-means in OKLab, deterministic), each shape whole, larger first. |
70
+ | `pixel` | Pixel art: exact colours, no clean-up of lone pixels, no curve fitting; every boundary is its pixel staircase. |
71
+
72
+ Any option overrides the preset: `colors`, `palette` (your own colours, as
73
+ `#rrggbb`), `merge` (`{ '#from': '#into' }`), `speckle`, `tolerance`,
74
+ `cornerAngle`, `layers`, `shapes`, `strokes`, `gradients`, `closeGaps`,
75
+ `threshold`, `invert`, `strokeWidth`, `deblur`, `smoothShading`, `keepOutlines`, `grayscale` and
76
+ `scale`. [Options](https://github.com/mtblck/inlaytrace/blob/main/docs/package/options.md)
77
+ says what each does.
62
78
 
63
79
  ### Also exported
64
80
 
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The command line (#165): `npx inlaytrace logo.png -o logo.svg --preset logo`.
4
+ *
5
+ * PNGs are decoded here with Node's own zlib, so the package keeps no
6
+ * dependencies. JPEG, WebP and anything else go through sharp when it's
7
+ * installed (`npm install sharp`), and the error says so when it isn't.
8
+ */
9
+ import { readFile, writeFile } from 'node:fs/promises'
10
+ import { parseArgs } from 'node:util'
11
+ import { presets, toSvg, trace } from '../dist/index.js'
12
+ import { decodePng, isPng } from './png.mjs'
13
+
14
+ const HELP = `Usage: inlaytrace <image> [-o out.svg] [options]
15
+
16
+ Traces a PNG (or, with sharp installed, a JPEG, WebP, GIF or TIFF) into an SVG.
17
+ Writes to stdout without -o.
18
+
19
+ -o, --output <file> where to write the SVG
20
+ -p, --preset <name> ${Object.keys(presets).join(', ')} (default logo)
21
+ -c, --colors <n> at most this many colours
22
+ --palette <list> your own colours, comma-separated: '#111111,#e63946'
23
+ --speckle <px> merge regions smaller than this square
24
+ --tolerance <px> how far the outline may stray from the pixels
25
+ --corner <deg> turns sharper than this stay corners
26
+ --layers shapes whole, in layers (--no-layers: cut out)
27
+ --exact-shapes draw circles and rectangles exactly (--no-exact-shapes)
28
+ --threshold <0-255> lineart and centerline: ink is darker than this
29
+ --invert lineart and centerline: light ink on a dark background
30
+ --deblur colour presets: take the blur out of a soft image first
31
+ --grayscale colour presets: greys only, --colors of them
32
+ --stroke-width <px> centerline: the stroke width
33
+ -h, --help
34
+ -v, --version`
35
+
36
+ const { values, positionals } = parseArgs({
37
+ allowPositionals: true,
38
+ allowNegative: true,
39
+ options: {
40
+ output: { type: 'string', short: 'o' },
41
+ preset: { type: 'string', short: 'p' },
42
+ colors: { type: 'string', short: 'c' },
43
+ palette: { type: 'string' },
44
+ speckle: { type: 'string' },
45
+ tolerance: { type: 'string' },
46
+ corner: { type: 'string' },
47
+ layers: { type: 'boolean' },
48
+ 'exact-shapes': { type: 'boolean' },
49
+ threshold: { type: 'string' },
50
+ invert: { type: 'boolean' },
51
+ deblur: { type: 'boolean' },
52
+ grayscale: { type: 'boolean' },
53
+ 'stroke-width': { type: 'string' },
54
+ help: { type: 'boolean', short: 'h' },
55
+ version: { type: 'boolean', short: 'v' },
56
+ },
57
+ })
58
+
59
+ if (values.version) {
60
+ const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'))
61
+ console.log(pkg.version)
62
+ process.exit(0)
63
+ }
64
+ if (values.help || positionals.length !== 1) {
65
+ console.log(HELP)
66
+ process.exit(values.help ? 0 : 1)
67
+ }
68
+
69
+ const fail = (message) => {
70
+ console.error(`inlaytrace: ${message}`)
71
+ process.exit(1)
72
+ }
73
+ const num = (name, v) => {
74
+ if (v === undefined) return undefined
75
+ const n = Number(v)
76
+ if (!Number.isFinite(n) || n < 0) fail(`--${name} needs a number, not "${v}"`)
77
+ return n
78
+ }
79
+
80
+ const options = {
81
+ preset: values.preset,
82
+ colors: num('colors', values.colors),
83
+ palette: values.palette?.split(',').map((c) => c.trim().toLowerCase()),
84
+ speckle: num('speckle', values.speckle),
85
+ tolerance: num('tolerance', values.tolerance),
86
+ cornerAngle: num('corner', values.corner),
87
+ layers: values.layers,
88
+ shapes: values['exact-shapes'],
89
+ threshold: values.threshold === undefined ? undefined : values.threshold === 'auto' ? 'auto' : num('threshold', values.threshold),
90
+ invert: values.invert,
91
+ deblur: values.deblur,
92
+ grayscale: values.grayscale,
93
+ strokeWidth: num('stroke-width', values['stroke-width']),
94
+ }
95
+ if (options.preset && !(options.preset in presets)) fail(`no preset "${options.preset}". Use one of: ${Object.keys(presets).join(', ')}`)
96
+ for (const c of options.palette ?? []) if (!/^#[0-9a-f]{6}$/.test(c)) fail(`--palette colours are #rrggbb, not "${c}"`)
97
+
98
+ const [input] = positionals
99
+ let bytes
100
+ try {
101
+ bytes = await readFile(input)
102
+ } catch (e) {
103
+ fail(`can't read ${input}: ${e.code ?? e.message}`)
104
+ }
105
+
106
+ let image
107
+ try {
108
+ try {
109
+ image = isPng(bytes) ? decodePng(bytes) : await decodeWithSharp(bytes, input)
110
+ } catch (e) {
111
+ if (!e.interlaced) throw e
112
+ image = await decodeWithSharp(bytes, 'an interlaced PNG')
113
+ }
114
+ } catch (e) {
115
+ fail(`can't decode ${input}: ${e.message}`)
116
+ }
117
+ let svg
118
+ try {
119
+ svg = toSvg(trace(image, options))
120
+ } catch (e) {
121
+ fail(`can't trace ${input}: ${e.message}`)
122
+ }
123
+ if (values.output) {
124
+ try {
125
+ await writeFile(values.output, svg)
126
+ } catch (e) {
127
+ fail(`can't write ${values.output}: ${e.code ?? e.message}`)
128
+ }
129
+ console.error(`inlaytrace: ${input} → ${values.output} (${image.width} × ${image.height}, ${(svg.length / 1024).toFixed(1)} KB)`)
130
+ } else process.stdout.write(svg)
131
+
132
+ async function decodeWithSharp(b, name) {
133
+ let sharp
134
+ try {
135
+ sharp = (await import('sharp')).default
136
+ } catch {
137
+ fail(`${name} isn't a PNG. For JPEG, WebP and other formats, install sharp next to inlaytrace (npm install sharp), or convert it to PNG.`)
138
+ }
139
+ // rotate() with no angle turns a phone photo upright by its EXIF orientation.
140
+ const { data, info } = await sharp(b).rotate().ensureAlpha().raw().toBuffer({ resolveWithObject: true })
141
+ return { data, width: info.width, height: info.height }
142
+ }
package/bin/png.mjs ADDED
@@ -0,0 +1,123 @@
1
+ /**
2
+ * A small PNG decoder for the command line, on Node's own zlib, so the
3
+ * package needs no dependencies.
4
+ */
5
+ import { inflateSync } from 'node:zlib'
6
+
7
+ export function isPng(b) {
8
+ return b.length > 8 && b.readUInt32BE(0) === 0x89504e47 && b.readUInt32BE(4) === 0x0d0a1a0a
9
+ }
10
+
11
+ /**
12
+ * A PNG as RGBA: every colour type, bit depths 1–16, transparency (tRNS).
13
+ * Interlaced files are rare and left to sharp.
14
+ */
15
+ export function decodePng(b) {
16
+ let pos = 8
17
+ let width = 0
18
+ let height = 0
19
+ let depth = 0
20
+ let type = 0
21
+ let interlace = 0
22
+ let palette = null
23
+ let trns = null
24
+ const idat = []
25
+ while (pos + 8 <= b.length) {
26
+ const len = b.readUInt32BE(pos)
27
+ const kind = b.toString('latin1', pos + 4, pos + 8)
28
+ const body = b.subarray(pos + 8, pos + 8 + len)
29
+ if (kind === 'IHDR') {
30
+ width = body.readUInt32BE(0)
31
+ height = body.readUInt32BE(4)
32
+ depth = body[8]
33
+ type = body[9]
34
+ interlace = body[12]
35
+ } else if (kind === 'PLTE') palette = body
36
+ else if (kind === 'tRNS') trns = body
37
+ else if (kind === 'IDAT') idat.push(body)
38
+ else if (kind === 'IEND') break
39
+ pos += 12 + len
40
+ }
41
+ if (!width || !height) throw new Error('the PNG has no image header')
42
+ if (interlace) throw Object.assign(new Error('interlaced PNGs need sharp'), { interlaced: true })
43
+ const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[type]
44
+ if (!channels) throw new Error(`unknown PNG colour type ${type}`)
45
+ const bpp = Math.max(1, (channels * depth) >> 3) // bytes per pixel, for filtering
46
+ const stride = Math.ceil((width * channels * depth) / 8)
47
+ const raw = inflateSync(Buffer.concat(idat))
48
+ // Checked before anything is sized from the header, so a cut-off download or a lying header fails here.
49
+ if (raw.length < (stride + 1) * height) throw new Error('the PNG is truncated')
50
+ const rows = Buffer.alloc(stride * height)
51
+ let prev = Buffer.alloc(stride)
52
+ for (let y = 0; y < height; y++) {
53
+ const filter = raw[y * (stride + 1)]
54
+ const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1))
55
+ const out = rows.subarray(y * stride, (y + 1) * stride)
56
+ for (let i = 0; i < stride; i++) {
57
+ const a = i >= bpp ? out[i - bpp] : 0
58
+ const up = prev[i]
59
+ const c = i >= bpp ? prev[i - bpp] : 0
60
+ const x = line[i]
61
+ out[i] =
62
+ filter === 0 ? x
63
+ : filter === 1 ? x + a
64
+ : filter === 2 ? x + up
65
+ : filter === 3 ? x + ((a + up) >> 1)
66
+ : x + paeth(a, up, c)
67
+ }
68
+ prev = out
69
+ }
70
+ // Each sample scaled to 0–255; 16-bit keeps its high byte.
71
+ const sample = (row, i) => {
72
+ if (depth === 8) return row[i]
73
+ if (depth === 16) return row[i * 2]
74
+ const bit = i * depth
75
+ const v = (row[bit >> 3] >> (8 - depth - (bit & 7))) & ((1 << depth) - 1)
76
+ return type === 3 ? v : Math.round((v * 255) / ((1 << depth) - 1))
77
+ }
78
+ // A sample as stored, unscaled, to compare with tRNS's key colour.
79
+ const stored = (row, i) => {
80
+ if (depth === 16) return row.readUInt16BE(i * 2)
81
+ if (depth === 8) return row[i]
82
+ const bit = i * depth
83
+ return (row[bit >> 3] >> (8 - depth - (bit & 7))) & ((1 << depth) - 1)
84
+ }
85
+ const data = new Uint8ClampedArray(width * height * 4)
86
+ for (let y = 0; y < height; y++) {
87
+ const row = rows.subarray(y * stride, (y + 1) * stride)
88
+ for (let x = 0; x < width; x++) {
89
+ const o = (y * width + x) * 4
90
+ let r, g, bl, al = 255
91
+ if (type === 3) {
92
+ const k = sample(row, x)
93
+ r = palette[k * 3]
94
+ g = palette[k * 3 + 1]
95
+ bl = palette[k * 3 + 2]
96
+ if (trns && k < trns.length) al = trns[k]
97
+ } else if (type === 0 || type === 4) {
98
+ r = g = bl = sample(row, x * channels)
99
+ if (type === 4) al = sample(row, x * channels + 1)
100
+ else if (trns && stored(row, x) === trns.readUInt16BE(0)) al = 0
101
+ } else {
102
+ r = sample(row, x * channels)
103
+ g = sample(row, x * channels + 1)
104
+ bl = sample(row, x * channels + 2)
105
+ if (type === 6) al = sample(row, x * channels + 3)
106
+ else if (trns && stored(row, x * 3) === trns.readUInt16BE(0) && stored(row, x * 3 + 1) === trns.readUInt16BE(2) && stored(row, x * 3 + 2) === trns.readUInt16BE(4)) al = 0
107
+ }
108
+ data[o] = r
109
+ data[o + 1] = g
110
+ data[o + 2] = bl
111
+ data[o + 3] = al
112
+ }
113
+ }
114
+ return { data, width, height }
115
+ }
116
+
117
+ function paeth(a, b, c) {
118
+ const p = a + b - c
119
+ const pa = Math.abs(p - a)
120
+ const pb = Math.abs(p - b)
121
+ const pc = Math.abs(p - c)
122
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c
123
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,10 @@
1
- //#region src/path.d.ts
1
+ /**
2
+ * Inlay: a raster-to-vector tracer whose shapes share their edges exactly,
3
+ * like inlaid wood. Every boundary between two colours is traced and fitted
4
+ * once and used by both neighbours, so layers never gap or overlap.
5
+ *
6
+ * Pure TypeScript, no DOM: runs in browsers, workers and Node.
7
+ */
2
8
  /**
3
9
  * SVG path data as editable nodes, and back.
4
10
  *
@@ -33,8 +39,6 @@ type Subpath = {
33
39
  export declare function parsePath(d: string): Subpath[];
34
40
  export declare function serializePath(subs: Subpath[]): string;
35
41
  export declare function mapPoints(subs: Subpath[], f: (p: Pt) => Pt): Subpath[];
36
- //#endregion
37
- //#region src/fit.d.ts
38
42
  type FitOptions = {
39
43
  /** Max distance in pixels between the outline and the fitted path. */
40
44
  tolerance: number;
@@ -66,8 +70,6 @@ export declare function isFlat([p0, c1, c2, p3]: Cubic): boolean;
66
70
  */
67
71
  export declare function fitChain(points: Pt[], closed: boolean, o: FitOptions, fine?: Pt[]): Cubic[];
68
72
  export declare function pointAt(b: Cubic, t: number): Pt;
69
- //#endregion
70
- //#region src/palette.d.ts
71
73
  /**
72
74
  * Palette extraction for flat artwork.
73
75
  *
@@ -87,7 +89,9 @@ export declare function pointAt(b: Cubic, t: number): Pt;
87
89
  * share (a decal, lettering) is still a colour if it isn't a blend of two
88
90
  * colours already accepted (an anti-aliased edge between them).
89
91
  * 4. Stop at the requested count.
90
- * 5. Given the image's `width`, fill what's left of the count with pale tints:
92
+ * 5. Given the image's `width`, add close fills: flat colours step 3 found
93
+ * too near a picked one (neutral-grey bars beside a blue-grey cab).
94
+ * 6. Then fill what's left of the count with pale tints:
91
95
  * light flat colours (pixels that match their four neighbours) too close to a
92
96
  * picked colour for step 3. A light-blue fill on white is 0.03 from it in
93
97
  * OKLab and lies on the line from white to the blue ink, so step 3 calls
@@ -131,8 +135,6 @@ export declare function quantizePalette(rgba: ArrayLike<number>, maxColors: numb
131
135
  * rarest ones take their nearest kept colour when pixels are labelled.
132
136
  */
133
137
  export declare function exactPalette(rgba: ArrayLike<number>, maxColors: number): string[];
134
- //#endregion
135
- //#region src/gradient.d.ts
136
138
  type GradientStop = {
137
139
  offset: number;
138
140
  color: string;
@@ -152,10 +154,6 @@ type Gradient = {
152
154
  r: number;
153
155
  stops: GradientStop[];
154
156
  };
155
- /** A gradient's colour at a point. */
156
- export declare const colorAt: (g: Gradient, x: number, y: number) => Rgb;
157
- //#endregion
158
- //#region src/inlay.d.ts
159
157
  type InlayOptions = FitOptions & {
160
158
  /** Regions smaller than speckle × speckle pixels are merged into their surroundings. */
161
159
  speckle: number;
@@ -213,6 +211,14 @@ type InlayOptions = FitOptions & {
213
211
  * pixel art. Off by default: a cutter or a plotter can't draw a gradient.
214
212
  */
215
213
  gradients?: boolean;
214
+ /**
215
+ * Faint shading as one shape: neighbouring regions in close colours that
216
+ * the image passes between without an edge (a barely-there gradient in a
217
+ * background, banded by close tints) join, in their commonest colour.
218
+ * Palette mode, not photos or pixel art. On by default; the presets turn it
219
+ * off with your own palette, whose every colour you chose.
220
+ */
221
+ faint?: boolean;
216
222
  /**
217
223
  * Painted lines (one entry per pixel, non-zero on a line), as `boostLines`
218
224
  * marks them. A region mostly on them is a drawn line, not one ink's two
@@ -267,29 +273,110 @@ type InlayResult = {
267
273
  width: number;
268
274
  height: number;
269
275
  paths: InlayPath[];
276
+ /** Centerline only: the stroke width measured from the ink, in px (whatever `strokeWidth` asked for). */
277
+ measuredWidth?: number;
270
278
  };
271
279
  /** The trace as an SVG document. */
272
280
  export declare function toSvg(r: InlayResult): string;
273
- /** Trace to an SVG string; `trace` gives the shapes as data. */
274
- export declare const traceInlay: (rgba: ArrayLike<number>, w: number, h: number, o: InlayOptions) => string;
281
+ /** What a trace is doing: take the blur out (only with `deblur`), pick the palette, label the pixels, clean up the labels, find the regions and their edges, fit the edges, build the shapes. */
282
+ type TraceStage = 'deblur' | 'palette' | 'label' | 'clean' | 'regions' | 'fit' | 'shapes';
283
+ /** A point a trace can pause at: the stage, and how far through it (0 to 1). */
284
+ type TraceStep = {
285
+ stage: TraceStage;
286
+ done: number;
287
+ };
288
+ type PresetName = 'logo' | 'illustration' | 'outline' | 'lineart' | 'centerline' | 'poster' | 'pixel';
289
+ /** Anything shaped like ImageData: RGBA bytes, row by row, and the size. sharp's `{ data, info }` gives `data` and `info.width`/`info.height`. */
290
+ type ImageLike = {
291
+ data: ArrayLike<number>;
292
+ width: number;
293
+ height: number;
294
+ };
295
+ type TraceOptions = {
296
+ /** What the image is: picks the palette, the steps before tracing and every default below. Default 'logo'. */
297
+ preset?: PresetName;
298
+ /** Colour presets: at most this many colours. */
299
+ colors?: number;
300
+ /** Colour presets: trace with exactly these colours (#rrggbb), instead of picking them from the image. */
301
+ palette?: string[];
302
+ /** Fold colours together before tracing, so the edge between them disappears: { '#from': '#into' }, traced hex to traced hex. */
303
+ merge?: Record<string, string>;
304
+ /** Regions smaller than speckle × speckle px merge into their surroundings. */
305
+ speckle?: number;
306
+ /** How far, in px, the fitted outline may stray from the pixels. */
307
+ tolerance?: number;
308
+ /** Turns sharper than this (degrees) stay corners. */
309
+ cornerAngle?: number;
310
+ /** Half-window in px of the smoothing over the pixel staircase (default 12). */
311
+ smoothing?: number;
312
+ /** Draw circles, ellipses, (rounded) rectangles and regular polygons exactly. */
313
+ shapes?: boolean;
314
+ /** Shapes drawn whole, in layers, instead of cut out to tile (cut out is what cutters want). */
315
+ layers?: boolean;
316
+ /** Thin drawn lines as stroked paths (Outline art). */
317
+ strokes?: boolean;
318
+ /** Soft shading as gradient fills. Off with your own `palette`, whose colours a gradient would leave. */
319
+ gradients?: boolean;
320
+ /** Join lines' ends across small breaks before tracing. */
321
+ closeGaps?: boolean;
322
+ /** How many times the image was enlarged before tracing: line widths and gap sizes grow with it. Default 1. */
323
+ scale?: number;
324
+ /** Ink presets (lineart, centerline): ink is darker than this (0–255), the image's own split when 'auto', adaptive when null. */
325
+ threshold?: number | 'auto' | null;
326
+ /** Ink presets: light ink on a dark background. */
327
+ invert?: boolean;
328
+ /** Centerline: the stroke width in px; measured from the ink when left out. */
329
+ strokeWidth?: number;
330
+ /** Colour presets but pixel art: take the blur out of a soft image before picking colours, so it doesn't trace as a band round every shape. Does nothing to crisp images. */
331
+ deblur?: boolean;
332
+ /** Colour presets: even out painted shading (brush and JPEG noise) before picking colours. */
333
+ smoothShading?: boolean;
334
+ /** Colour presets: darken faint painted outlines first, so the shapes they part don't merge. */
335
+ keepOutlines?: boolean;
336
+ /** Colour presets but pixel art: trace in greys only, `colors` of them (each pixel's OKLab lightness, as a grey). */
337
+ grayscale?: boolean;
338
+ };
339
+ /** A preset's defaults: what `trace` uses for every option not given. */
340
+ type PresetDefaults = Readonly<Pick<TraceOptions, 'colors' | 'speckle' | 'tolerance' | 'cornerAngle' | 'shapes' | 'layers' | 'strokes' | 'gradients' | 'closeGaps' | 'threshold'>> & {
341
+ /** Which kind of trace: filled colour shapes, one ink's shapes, or strokes down the ink's middle. */
342
+ readonly kind: 'colour' | 'ink' | 'centerline';
343
+ };
344
+ /** Every preset's defaults, as the app shows them. */
345
+ export declare const presets: Readonly<Record<PresetName, PresetDefaults>>;
275
346
  /**
276
- * Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
277
- * into filled shapes that share their edges exactly.
347
+ * Trace an image into filled shapes that share their edges exactly (or, with
348
+ * the centerline preset, strokes down the ink's middle).
349
+ *
350
+ * trace(imageData, { preset: 'logo' })
351
+ * trace({ data, width, height }, { preset: 'poster', colors: 16 })
278
352
  */
279
- export declare function trace(rgba: ArrayLike<number>, w: number, h: number, o: InlayOptions): InlayResult;
353
+ export declare function trace(image: ImageLike, options?: TraceOptions): InlayResult;
354
+ /** @deprecated Since 0.4: use `trace({ data: rgba, width, height }, { preset, … })`. This form goes in 1.0. */
355
+ export declare function trace(rgba: ArrayLike<number>, width: number, height: number, options: InlayOptions): InlayResult;
356
+ /** `toSvg(trace(…))` in one call, in either form. */
357
+ export declare function traceInlay(image: ImageLike, options?: TraceOptions): string;
358
+ /** @deprecated Since 0.4: use `traceInlay({ data: rgba, width, height }, { preset, … })`. This form goes in 1.0. */
359
+ export declare function traceInlay(rgba: ArrayLike<number>, width: number, height: number, options: InlayOptions): string;
360
+ /** Anything shaped like an AbortSignal (an AbortController's `signal`). */
361
+ type AbortSignalLike = {
362
+ readonly aborted: boolean;
363
+ readonly reason?: unknown;
364
+ };
365
+ type TraceAsyncOptions = TraceOptions & {
366
+ /** Stops the trace at its next pause: the promise rejects with the signal's reason. */
367
+ signal?: AbortSignalLike;
368
+ /** Called at each pause with the stage under way and how far through it (0 to 1). */
369
+ onProgress?: (step: TraceStep) => void;
370
+ };
280
371
  /**
281
- * A chain as its exact pixel boundary: a line between each pair of turns.
282
- * The points are pixel corners about a pixel apart, so a run of them in one
283
- * direction is one straight edge. A closed loop starts at a turn, so its seam
284
- * isn't a node in the middle of an edge.
372
+ * `trace`, but it pauses between its stages (and every few hundred edges
373
+ * while fitting) to report progress and let the thread get on with other
374
+ * work, and it stops when `signal` aborts. Same result as `trace`.
375
+ *
376
+ * const controller = new AbortController()
377
+ * const result = await traceAsync(image, { preset: 'poster', signal: controller.signal, onProgress: (s) => console.log(s.stage, s.done) })
285
378
  */
286
- export declare function staircase(pts: Pt[], closed: boolean): Cubic[];
287
- /** Relabel merged colours as their targets, following chains, in place. */
288
- export declare function mergeLabels(labels: Int32Array, colors: string[], merge: Record<string, string>): void;
289
- /** Otsu's threshold over opaque pixels: the split that best separates two populations. */
290
- export declare function otsu(lum: Uint8Array, alpha: Uint8Array): number;
291
- //#endregion
292
- //#region src/smooth.d.ts
379
+ export declare function traceAsync(image: ImageLike, options?: TraceAsyncOptions): Promise<InlayResult>;
293
380
  /**
294
381
  * Edge-preserving smoothing for painted art, before its palette is picked.
295
382
  *
@@ -333,8 +420,21 @@ export declare function smoothShading(rgba: ArrayLike<number>, width: number, he
333
420
  * enough to the dark grey on either side to be folded in as a sliver.
334
421
  */
335
422
  export declare function boostLines(rgba: ArrayLike<number>, width: number, height: number, radius?: number, lines?: Uint8Array): Uint8ClampedArray;
336
- //#endregion
337
- //#region src/centerline.d.ts
423
+ /**
424
+ * How soft the image's edges are, in px: the Gaussian blur a hard edge would
425
+ * need to look like the image's bold edges (their median). 0 when it has no
426
+ * bold edges. Crisp art reads under 1, anti-aliasing and all.
427
+ */
428
+ export declare function edgeBlur(rgba: ArrayLike<number>, width: number, height: number): number;
429
+ /**
430
+ * A copy of `rgba` (`width` × `height`, RGBA) with its blur taken out: flat
431
+ * colours with clean, anti-aliased edges where the image had soft ramps.
432
+ * `blur` is how soft its edges are (`edgeBlur`, measured when left out);
433
+ * below `SOFT_EDGES` the image is only copied. `scale` is how many times the
434
+ * image was enlarged before this: enlarging softens edges by as much, so the
435
+ * threshold grows with it. Alpha is kept as it is.
436
+ */
437
+ export declare function deblur(rgba: ArrayLike<number>, width: number, height: number, blurPx?: number, scale?: number): Uint8ClampedArray;
338
438
  type CenterlineOptions = {
339
439
  /** Ink is darker than this (0–255); 'auto' splits ink from paper by the image's histogram (Otsu); null compares each pixel with its neighbourhood instead. */
340
440
  threshold: number | 'auto' | null;
@@ -353,25 +453,22 @@ type CenterlineOptions = {
353
453
  /** How many times the drawing was enlarged before tracing: gap closing's pixel limits grow with it. Default 1. */
354
454
  scale?: number;
355
455
  };
356
- /** One stroked path: open subpaths (and closed loops), drawn with round caps and joins. */
357
- type CenterlinePath = {
358
- d: string;
359
- stroke: string;
360
- strokeWidth: number;
361
- };
362
- type CenterlineResult = {
363
- width: number;
364
- height: number;
365
- paths: CenterlinePath[];
366
- /** The stroke width measured from the ink, in pixels (whatever `strokeWidth` asked for). */
456
+ /**
457
+ * A centerline trace: the usual result, its paths stroked (`stroke` is the
458
+ * width, `fill` the colour, as Outline art's lines), and `measuredWidth`.
459
+ * @deprecated Since 0.4: it's `InlayResult`.
460
+ */
461
+ type CenterlineResult = InlayResult & {
367
462
  measuredWidth: number;
368
463
  };
369
- /** Trace to an SVG string; `centerline` gives the strokes as data. */
464
+ /**
465
+ * Trace to an SVG string; `centerline` gives the strokes as data.
466
+ * @deprecated Since 0.4: use `toSvg(trace(image, { preset: 'centerline' }))`.
467
+ */
370
468
  export declare const traceCenterline: (rgba: ArrayLike<number>, w: number, h: number, o: CenterlineOptions) => string;
371
- export declare function centerlineToSvg(r: CenterlineResult): string;
469
+ /** @deprecated Since 0.4: `toSvg` draws stroked paths the same way. */
470
+ export declare const centerlineToSvg: (r: InlayResult) => string;
372
471
  export declare function centerline(rgba: ArrayLike<number>, w: number, h: number, o: CenterlineOptions): CenterlineResult;
373
- //#endregion
374
- //#region src/symmetry.d.ts
375
472
  /**
376
473
  * Symmetry: find a likely mirror axis or rotational order in a raster.
377
474
  *
@@ -419,5 +516,4 @@ type SymmetryOptions = {
419
516
  * no foreground.
420
517
  */
421
518
  export declare function detectSymmetry(rgba: ArrayLike<number>, w: number, h: number, options?: SymmetryOptions): Symmetry[];
422
- //#endregion
423
- export type { CenterlineOptions, CenterlinePath, CenterlineResult, Cubic, FitOptions, Gradient, GradientStop, InlayOptions, InlayPath, InlayResult, MirrorSymmetry, PathNode, Pt, Rgb, RotationalSymmetry, Subpath, Symmetry, SymmetryOptions };
519
+ export type { AbortSignalLike, CenterlineOptions, CenterlineResult, Cubic, FitOptions, Gradient, GradientStop, ImageLike, InlayOptions, InlayPath, InlayResult, MirrorSymmetry, PathNode, PresetDefaults, PresetName, Pt, Rgb, RotationalSymmetry, Subpath, Symmetry, SymmetryOptions, TraceAsyncOptions, TraceOptions, TraceStage, TraceStep };