inlaytrace 0.1.3 → 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 CHANGED
@@ -1,17 +1,57 @@
1
1
  # inlaytrace
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Painted lines stay through smoothing and clean-up: `boostLines` can mark the pixels it darkens (a `lines` array), `smoothShading` takes a `keep` mask it leaves alone, and the tracer's new `lines` option stops a marked line from being folded into a neighbour as a sliver. A dark outline between two dark areas (trousers against a night background) now keeps them apart.
8
+ - New `boostLines(rgba, width, height, radius?)`: darkens faint painted outlines (thin lines darker than both their sides, found with a black-hat filter) before the palette is picked, so a mouth on a shadowed face or a line between two near-equal colours labels apart from them instead of being lost. Short dark marks are left alone as texture.
9
+ - New `smoothShading(rgba, width, height)`: an edge-preserving (bilateral) filter for painted art, run before picking the palette. Brush and JPEG noise inside a shadow evens out, so the shadow traces as one shape instead of flecks of its two nearest colours, while the edges between colours stay sharp.
10
+
11
+ ### Patch Changes
12
+
13
+ - `centerlineToSvg` escapes the drawing's width and height like every other value it writes.
14
+ - Faster colour labelling: converting colours to OKLab reads linear light from a table instead of a power per channel, which cut a 24-colour trace of an 820 × 1162 painted poster from 20 s to 11 s with the same output.
15
+ - Gradient fills no longer smear one shape into its neighbour on painted art (a face into the hair or shadow beside it): a gradient must stay within 20 RGB levels of the image, and must draw each of the bands it replaces no worse than that band's own colour did.
16
+ - Smaller files with Keep painted outlines: with the tracer's `lines` option, the pieces one painted line labels as (a few dark shades along its length) now join each other instead of each staying a shape, and a marked piece too short to part anything folds into its neighbour like any sliver. 9–15% smaller on a painted film poster, with its outlines kept.
17
+ - Strokes keep sharp corners sharp (a flag's swallowtail no longer comes out rounded), and in outline art a dot drawn on a line's end (a flagpole's knob) stays a shape instead of being lost under the stroke.
18
+
19
+ ## 0.2.0
20
+
21
+ ### Minor Changes
22
+
23
+ - `stacked: true` now works for flat art too: shapes come back to front, each whole, with the parts hidden behind other shapes completed (a disc behind a bar traces as a whole disc). Which shape is in front is read from the junctions where two shapes' shared edge ends. Photos (`photo: true`) stack as before.
24
+ - Flat outline illustrations (thin coloured outlines on white, pale tinted fills) now trace. Speck clean-up folds a speck into its nearest colour, and no longer dissolves a thin stroke that lossy compression split into two shades of its ink. `peakPalette` takes a new `width` option: given it, pale tints are found by their flatness (new options `minTint`, `minFlat`), and a colour that is only ever an anti-aliased edge is left out. Slivers under 2 px wide fold into a neighbour of nearly the same colour. New option `photo` keeps the old clean-up for photos (specks join the colour they share the most edge with, no sliver pass), which is what a stacked `quantizePalette` trace wants. Binary and centerline modes take `threshold: 'auto'` (Otsu, falling back to 128 on a page with nothing to split). A thin closed shape (a 3 px letter stem) no longer collapses to a line, and the fitter no longer grows spikes on thin letters. On a new outline fixture, Logo went from 13.0% to 2.1% of pixels wrong; the badge, emblems and photos (with `photo`) score the same.
25
+ - New `strokes` option for flat outline art: in palette mode, the colours drawn mostly as thin, long lines are traced down their middle as one stroked path each (`InlayPath.stroke` is the width measured from the ink), with their anti-aliased edges and darker shades joined in, and the shapes either side meet beneath them. Small lettering, short marks and solid shapes stay shapes. `scale` says how far the image was enlarged, so the line widths scale with it. Off by default; output without it is unchanged.
26
+
27
+ `toSvg` and `centerlineToSvg` now escape the attribute values they write, so a palette colour given with a quote in it can't end its attribute.
28
+ - `peakPalette` finds colours spread over several histogram bins (a photo's red lettering, a small decal) instead of stopping at the greys; flat art's palettes are unchanged. New option `minDetail`. Stacked shapes now reach under the neighbours painted after them, so no hairline seam shows where two shapes meet (12% closer on photos, about a third more path data).
29
+ - Lines within a degree of horizontal, vertical or 45° are now exactly that, so a square stays square after JPEG and lines either side of a junction line up. `fitChain` takes `snap: false` to keep lines as fitted.
30
+
31
+ ### Patch Changes
32
+
33
+ - `centerline(rgba, width, height, options)` (and `traceCenterline`, `centerlineToSvg`): single strokes down the middle of the ink, for pen plotters and engraving, with the stroke width measured from the ink or set.
34
+ - Add a funding link (Ko-fi) to the package metadata.
35
+ - New `gradients` option: soft shading that a palette splits into bands of tints is traced as one shape with a linear or radial gradient (`path.gradient`, written by `toSvg` as `<linearGradient>` / `<radialGradient>`), when the gradient fits much better than a flat colour. Off by default.
36
+ - Lines about a pixel wide stay in one piece at a slant, instead of breaking into dashes or vanishing.
37
+ - Centerline and outline-art strokes run straight through junctions. Thinning bends the skeleton toward each junction, so an X of thick strokes came out pinched at its crossing and a T's stem bent to meet the bar; within a stroke width of a junction the arms are now cut back and drawn straight on to where their own lines meet.
38
+ - Small text and dots beside flat art now trace. Thin anti-aliased strokes (1.5 px grey letters) were labelled as the paper, pale edges as a nearby colour, and each letter then cleared as a speck. In flat art (not `photo`), a pixel between colours and close to none of them is now read as a mix of the pair that explains it best; one next to only one other colour keeps its own; and a speck that stands well apart from every colour around it stays from an eighth of the speck area up, so raising `speckle` still clears it. Poster output is unchanged.
39
+ - In images with exactly flat colours, such as most PNG exports, edges are placed between pixels from their anti-aliasing instead of on the pixel grid: straight sides land where they really are, and small shapes come out cleaner (2–16% fewer wrong pixels on the PNG fixtures, for the same nodes). Whether an image qualifies is judged from its pixels, so typical JPEG and WebP traces and Poster are unchanged.
40
+ - `toSvg` escapes the drawing's width and height like every other value it writes.
41
+ - Lines one or two pixels wide keep their width to their ends. Where such a line's outline turned back at its end inside one fitted run (an arm of a T or a Y), its two sides were joined at a point, so each arm tapered to nothing and thin outlines looked broken.
42
+
3
43
  ## 0.1.3
4
44
 
5
45
  ### Patch Changes
6
46
 
7
- - f71beed: New `shapes` option: a closed outline that is a circle, an ellipse, a rectangle, a rounded rectangle or a regular polygon is drawn as that exact shape instead of fitted curves (on the sample badge, 0.70% → 0.54% wrong pixels). Off by default.
8
- - 074cc75: `detectSymmetry(rgba, width, height, options?)` finds the likeliest mirror axes (vertical and horizontal) and rotational orders (2–8 by default) in an image, each scored by the share of the drawing that matches its reflection or turn.
47
+ - New `shapes` option: a closed outline that is a circle, an ellipse, a rectangle, a rounded rectangle or a regular polygon is drawn as that exact shape instead of fitted curves (on the sample badge, 0.70% → 0.54% wrong pixels). Off by default.
48
+ - `detectSymmetry(rgba, width, height, options?)` finds the likeliest mirror axes (vertical and horizontal) and rotational orders (2–8 by default) in an image, each scored by the share of the drawing that matches its reflection or turn.
9
49
 
10
50
  ## 0.1.2
11
51
 
12
52
  ### Patch Changes
13
53
 
14
- - 679659c: Photos: `quantizePalette(rgba, n)` picks a photo's colours by k-means in OKLab (deterministic), and the `stacked` option draws each shape whole, larger shapes first, instead of cutting holes (same picture, less path data, no hairline seams). Also fixes speck merging, which could strand fragments of merged specks as new specks: on photos that left thousands of extra shapes, and a larger `speckle` gave more shapes rather than fewer.
54
+ - Photos: `quantizePalette(rgba, n)` picks a photo's colours by k-means in OKLab (deterministic), and the `stacked` option draws each shape whole, larger shapes first, instead of cutting holes (same picture, less path data, no hairline seams). Also fixes speck merging, which could strand fragments of merged specks as new specks: on photos that left thousands of extra shapes, and a larger `speckle` gave more shapes rather than fewer.
15
55
 
16
56
  ## 0.1.1
17
57
 
package/README.md CHANGED
@@ -42,7 +42,8 @@ const result = trace(rgba, width, height, {
42
42
  cornerAngle: 45, // turns sharper than this stay corners
43
43
  })
44
44
 
45
- result.paths // [{ d: 'M…Z', fill: '#rrggbb' }, …] largest first, nonzero fill
45
+ result.paths // [{ d: 'M…Z', fill: '#rrggbb' }, …] largest first, nonzero fill;
46
+ // with `strokes`, lines last: { d, fill, stroke: width }, stroked in `fill`, unfilled
46
47
  toSvg(result) // '<svg …>…</svg>'
47
48
  ```
48
49
 
@@ -50,11 +51,14 @@ toSvg(result) // '<svg …>…</svg>'
50
51
 
51
52
  | Options | For |
52
53
  | --- | --- |
53
- | `mode: 'palette', palette` | Flat colour art. `palette` is the colours to label pixels with: `peakPalette(rgba, n)` takes the sharp peaks of the histogram (flat art's real colours); `exactPalette(rgba, n)` takes the image's exact colours, most-used first. |
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. |
54
55
  | `mode: 'palette', palette, merge` | Fold colours together before regions are built, so the edge between them disappears: `{ '#from': '#into' }`. |
55
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. |
56
- | `mode: 'palette', palette: quantizePalette(…), stacked: 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. |
57
- | `mode: 'binary', threshold` | Line art: ink darker than `threshold` (0–255), or adaptive per neighbourhood when `null`. Only the ink is drawn. |
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. |
58
62
 
59
63
  ### Also exported
60
64
 
@@ -63,6 +67,9 @@ toSvg(result) // '<svg …>…</svg>'
63
67
  Béziers between them).
64
68
  - `parsePath(d)` / `serializePath(subpaths)`: path data as editable nodes with
65
69
  absolute handles, and back. Round trips are idempotent after the first pass.
70
+ - `centerline(rgba, width, height, options)` / `traceCenterline(…)`: single
71
+ strokes down the middle of the ink, for pen plotters and engraving, with the
72
+ stroke width measured from the ink (or set).
66
73
  - `detectSymmetry(rgba, width, height)`: the likeliest mirror axes and
67
74
  rotational orders in an image, each scored by how much of the drawing
68
75
  matches (the app offers to enforce one at 95% or more).
package/dist/index.d.ts CHANGED
@@ -47,6 +47,11 @@ type FitOptions = {
47
47
  * or a regular polygon as that exact shape (see shapes.ts). Default false.
48
48
  */
49
49
  shapes?: boolean;
50
+ /**
51
+ * Make lines within 1° of horizontal, vertical or 45° exactly that (see
52
+ * `snapLines`). Default true; exact shapes are never snapped.
53
+ */
54
+ snap?: boolean;
50
55
  };
51
56
  /** A cubic Bézier: start, two handles, end. A straight line has handles on the chord. */
52
57
  type Cubic = [Pt, Pt, Pt, Pt];
@@ -55,11 +60,101 @@ export declare function isFlat([p0, c1, c2, p3]: Cubic): boolean;
55
60
  /**
56
61
  * Fit a chain. Open: from points[0] to the last point, which stay fixed.
57
62
  * Closed: points[0] is not repeated at the end; the result is a loop that starts
58
- * at a corner if there is one.
63
+ * at a corner if there is one. `fine`, if given, is the same chain placed more
64
+ * exactly (between pixels) and is what gets fitted, exact shapes included;
65
+ * `points` stays the pixel outline that the area check measures.
59
66
  */
60
- export declare function fitChain(points: Pt[], closed: boolean, o: FitOptions): Cubic[];
67
+ export declare function fitChain(points: Pt[], closed: boolean, o: FitOptions, fine?: Pt[]): Cubic[];
61
68
  export declare function pointAt(b: Cubic, t: number): Pt;
62
69
  //#endregion
70
+ //#region src/palette.d.ts
71
+ /**
72
+ * Palette extraction for flat artwork.
73
+ *
74
+ * VTracer's own quantizer averages each cluster, so a flat colour that borders
75
+ * a lighter one drifts towards it: on the sample badge the gold sun (#e9a23b)
76
+ * came out pale peach (#e9c38f) — wrong enough to break a brand colour. Flat
77
+ * art has a property quantizers ignore: its real colours are sharp *peaks* in
78
+ * the histogram, and everything between them (anti-aliasing, JPEG ringing) is
79
+ * a thin spread of low-count shades. So instead of clustering, take the peaks:
80
+ *
81
+ * 1. Histogram at 5 bits per channel, keeping each bin's true mean colour.
82
+ * 2. Weigh each bin by the pixels within half the distinct-colour distance of
83
+ * it (OKLab), so a colour spread over several bins counts in full.
84
+ * 3. Walk bins from heaviest to lightest; accept a bin as a new colour only
85
+ * if it is perceptually distinct (OKLab distance) from every colour already
86
+ * accepted, and its weight is a meaningful share of the image. A smaller
87
+ * share (a decal, lettering) is still a colour if it isn't a blend of two
88
+ * colours already accepted (an anti-aliased edge between them).
89
+ * 4. Stop at the requested count.
90
+ * 5. Given the image's `width`, fill what's left of the count with pale tints:
91
+ * light flat colours (pixels that match their four neighbours) too close to a
92
+ * picked colour for step 3. A light-blue fill on white is 0.03 from it in
93
+ * OKLab and lies on the line from white to the blue ink, so step 3 calls
94
+ * it an edge between the two; but an edge is never flat, and a fill is.
95
+ *
96
+ * This is for logos and illustrations. Photos have no peaks (on a photo the
97
+ * peaks raised mean error from 9.9 to 15.3), so they use `quantizePalette`.
98
+ */
99
+ type Rgb = [number, number, number];
100
+ export declare function peakPalette(rgba: ArrayLike<number>, maxColors: number, { minDistance, minShare, minDetail, width, minTint, minFlat }?: {
101
+ minDistance?: number;
102
+ minShare?: number;
103
+ minDetail?: number;
104
+ width?: number;
105
+ minTint?: number;
106
+ minFlat?: number;
107
+ }): string[];
108
+ export declare function oklab([r, g, b]: Rgb): Rgb;
109
+ /**
110
+ * A photo's palette: `maxColors` colours that best summarise it, by k-means in
111
+ * OKLab (so the clusters are perceptual, not RGB boxes).
112
+ *
113
+ * It clusters a 5-bit-per-channel histogram, each bin weighted by its pixel
114
+ * count, rather than the pixels themselves: the same answer to within a bin,
115
+ * at a fraction of the work. It's deterministic: the first centre is the most
116
+ * common colour, and each next one is the colour farthest from those chosen,
117
+ * weighted by how common it is (k-means++ without the dice), so a photo traces
118
+ * the same way every time. Each colour returned is the true mean of the pixels
119
+ * in its cluster, most common first. `maxColors` is rounded and taken as at
120
+ * least 1 (so 0 or NaN gives one colour); fewer come back when the image has
121
+ * fewer distinct colours, and none when every pixel is transparent.
122
+ */
123
+ export declare function quantizePalette(rgba: ArrayLike<number>, maxColors: number, { iterations }?: {
124
+ iterations?: number;
125
+ }): string[];
126
+ /**
127
+ * Pixel art's palette: its colours exactly, most-used first. Pixel art has a
128
+ * handful of deliberate colours, and a one-pixel eye matters as much as the
129
+ * sky, so nothing is merged or dropped for being rare or close to another.
130
+ * Beyond `maxColors` distinct colours (a photo picked as pixel art), the
131
+ * rarest ones take their nearest kept colour when pixels are labelled.
132
+ */
133
+ export declare function exactPalette(rgba: ArrayLike<number>, maxColors: number): string[];
134
+ //#endregion
135
+ //#region src/gradient.d.ts
136
+ type GradientStop = {
137
+ offset: number;
138
+ color: string;
139
+ };
140
+ /** Coordinates in the trace's pixels (gradientUnits="userSpaceOnUse"). */
141
+ type Gradient = {
142
+ type: 'linear';
143
+ x1: number;
144
+ y1: number;
145
+ x2: number;
146
+ y2: number;
147
+ stops: GradientStop[];
148
+ } | {
149
+ type: 'radial';
150
+ cx: number;
151
+ cy: number;
152
+ r: number;
153
+ stops: GradientStop[];
154
+ };
155
+ /** A gradient's colour at a point. */
156
+ export declare const colorAt: (g: Gradient, x: number, y: number) => Rgb;
157
+ //#endregion
63
158
  //#region src/inlay.d.ts
64
159
  type InlayOptions = FitOptions & {
65
160
  /** Regions smaller than speckle × speckle pixels are merged into their surroundings. */
@@ -72,15 +167,59 @@ type InlayOptions = FitOptions & {
72
167
  pixels?: boolean;
73
168
  /**
74
169
  * Stacked shapes, for photos: each region is drawn whole, without the holes
75
- * other regions sit in, and larger shapes come first so smaller ones paint
76
- * over them. Every hole's outline is exactly the outline of what fills it,
77
- * so the picture is the same as cut-out shapes, with less path data (each
78
- * hole isn't drawn a second time) and no hairline seams where anti-aliased
79
- * edges meet. A hole with transparency anywhere inside it, however deep, is
170
+ * other regions sit in, larger shapes first so smaller ones paint over them,
171
+ * and reaching under every neighbour painted after it. So each shared edge
172
+ * is drawn once, by the later shape over the earlier one's colour, and no
173
+ * hairline seam shows where anti-aliased edges meet (on photos, 12% closer
174
+ * to the photo than without, for about a third more path data). A hole with transparency anywhere inside it, however deep, is
80
175
  * kept, so transparency stays transparent. Default: cut out, which is what a
81
176
  * vinyl cutter or a screen printer wants.
177
+ *
178
+ * For flat art (not `photo`) it means layers instead: shapes in front-to-back
179
+ * order, each whole. Which of two touching shapes is in front is read from
180
+ * the junctions where their boundary ends, and a shape behind another is
181
+ * completed under it (its circle, its corner, or a smooth continuation),
182
+ * so a moon behind a bar is one disc. Holes that later shapes fill are
183
+ * dropped, as for photos.
82
184
  */
83
185
  stacked?: boolean;
186
+ /**
187
+ * Photos: specks join the colour they share the most edge with, and slivers
188
+ * are left alone. Flat art's clean-up (specks join the nearest colour, and
189
+ * slivers of one ink's two shades fold together) keeps thin strokes whole,
190
+ * but on photos it kept so many real regions that files grew by half.
191
+ */
192
+ photo?: boolean;
193
+ /**
194
+ * Outline art: draw thin lines of ink as lines. A colour that is mostly
195
+ * thin, long regions (outlines, small lettering) is traced down its middle
196
+ * as round-capped strokes of the width measured from it, and the shapes
197
+ * around each line grow to meet under it, so a line can be moved or
198
+ * restyled without a gap opening. Palette mode only; ignored for photos
199
+ * and pixel art.
200
+ */
201
+ strokes?: boolean;
202
+ /**
203
+ * How many times the drawing was enlarged before tracing (an upscaled small
204
+ * image, or a full-size trace of one usually traced smaller). The widths
205
+ * `strokes` takes as lines (2.5–8 px) grow with it. Default 1.
206
+ */
207
+ scale?: number;
208
+ /**
209
+ * Soft shading as gradients: neighbouring tints that are bands of one
210
+ * smooth shade become one shape with a linear or radial gradient, when it
211
+ * fits much better than a flat colour (gradient.ts). Palette mode only, not
212
+ * pixel art. Off by default: a cutter or a plotter can't draw a gradient.
213
+ */
214
+ gradients?: boolean;
215
+ /**
216
+ * Painted lines (one entry per pixel, non-zero on a line), as `boostLines`
217
+ * marks them. A region mostly on them is a drawn line, not one ink's two
218
+ * shades, so it folds only into another piece of line: a dark outline
219
+ * between two dark shapes is nearly their colour, and folding it in joined
220
+ * them.
221
+ */
222
+ lines?: ArrayLike<number>;
84
223
  } & (
85
224
  /**
86
225
  * `merge` folds colours together before any region is built, so the edge
@@ -93,18 +232,28 @@ type InlayOptions = FitOptions & {
93
232
  merge?: Record<string, string>;
94
233
  } |
95
234
  /**
96
- * Ink is darker than `threshold` (0–255). When null, each pixel is compared
97
- * with its neighbourhood instead, for photos of paper under uneven light.
235
+ * Ink is darker than `threshold` (0–255). With 'auto', the threshold is
236
+ * the image's own split between ink and paper (Otsu's), so coloured ink
237
+ * works as well as black (a page with no clear ink, such as a blank
238
+ * scan, falls back to 128). When null, each pixel is compared with its
239
+ * neighbourhood instead, for photos of paper under uneven light.
98
240
  * Only ink is drawn.
99
241
  */
100
242
  {
101
243
  mode: 'binary';
102
- threshold: number | null;
244
+ threshold: number | 'auto' | null;
103
245
  });
104
- /** One filled shape: path data (M/L/C/Z, absolute, nonzero fill) and its colour. */
246
+ /**
247
+ * One filled shape: path data (M/L/C/Z, absolute, nonzero fill) and its
248
+ * colour. With `stroke` (a width in px), a line drawn in that colour instead,
249
+ * with round caps and joins. With `gradient`, the shape is filled with it, and
250
+ * `fill` is its average colour, for anything that can only draw flat colour.
251
+ */
105
252
  type InlayPath = {
106
253
  d: string;
107
254
  fill: string;
255
+ stroke?: number;
256
+ gradient?: Gradient;
108
257
  };
109
258
  /** A trace: the drawing's size in pixels and its shapes, largest first (paint order). */
110
259
  type InlayResult = {
@@ -133,57 +282,83 @@ export declare function mergeLabels(labels: Int32Array, colors: string[], merge:
133
282
  /** Otsu's threshold over opaque pixels: the split that best separates two populations. */
134
283
  export declare function otsu(lum: Uint8Array, alpha: Uint8Array): number;
135
284
  //#endregion
136
- //#region src/palette.d.ts
285
+ //#region src/smooth.d.ts
137
286
  /**
138
- * Palette extraction for flat artwork.
139
- *
140
- * VTracer's own quantizer averages each cluster, so a flat colour that borders
141
- * a lighter one drifts towards it: on the sample badge the gold sun (#e9a23b)
142
- * came out pale peach (#e9c38f) — wrong enough to break a brand colour. Flat
143
- * art has a property quantizers ignore: its real colours are sharp *peaks* in
144
- * the histogram, and everything between them (anti-aliasing, JPEG ringing) is
145
- * a thin spread of low-count shades. So instead of clustering, take the peaks:
287
+ * Edge-preserving smoothing for painted art, before its palette is picked.
146
288
  *
147
- * 1. Histogram at 5 bits per channel, keeping each bin's true mean colour.
148
- * 2. Walk bins from most to least frequent; accept a bin as a new colour only
149
- * if it is perceptually distinct (OKLab distance) from every colour already
150
- * accepted, and holds a meaningful share of the image.
151
- * 3. Stop at the requested count.
289
+ * A painted poster's skin shadow is a soft ramp with brush and JPEG noise on
290
+ * it. Labelled pixel by pixel, the noise flips each pixel between the two
291
+ * nearest palette colours, and the shadow traces as ragged patches. A
292
+ * bilateral filter averages each pixel with neighbours of a similar colour
293
+ * only, so the noise inside a shadow evens out and the edges between colours
294
+ * (an arm against the dark coat, a line on a face) stay where they are.
152
295
  *
153
- * This is for logos and illustrations. Photos have no peaks (on a photo the
154
- * peaks raised mean error from 9.9 to 15.3), so they use `quantizePalette`.
296
+ * On a painted film poster traced at 2× in Illustration, this turned the
297
+ * blotchy arm and neck shadows into whole shapes, kept the face lines, and cut
298
+ * the file from 3.3 MB to 2.1 MB; the filter took 4 s of the trace. Stronger
299
+ * (radius 6, three passes at sigma 25) began to wash out lines in the hair.
155
300
  */
156
- type Rgb = [number, number, number];
157
- export declare function peakPalette(rgba: ArrayLike<number>, maxColors: number, { minDistance, minShare }?: {
158
- minDistance?: number;
159
- minShare?: number;
160
- }): string[];
161
- export declare function oklab([r, g, b]: Rgb): Rgb;
162
301
  /**
163
- * A photo's palette: `maxColors` colours that best summarise it, by k-means in
164
- * OKLab (so the clusters are perceptual, not RGB boxes).
165
- *
166
- * It clusters a 5-bit-per-channel histogram, each bin weighted by its pixel
167
- * count, rather than the pixels themselves: the same answer to within a bin,
168
- * at a fraction of the work. It's deterministic: the first centre is the most
169
- * common colour, and each next one is the colour farthest from those chosen,
170
- * weighted by how common it is (k-means++ without the dice), so a photo traces
171
- * the same way every time. Each colour returned is the true mean of the pixels
172
- * in its cluster, most common first. `maxColors` is rounded and taken as at
173
- * least 1 (so 0 or NaN gives one colour); fewer come back when the image has
174
- * fewer distinct colours, and none when every pixel is transparent.
302
+ * A smoothed copy of `rgba` (`width` × `height`, RGBA). Transparent pixels, and
303
+ * any marked in `keep` (one entry per pixel, non-zero to keep), are left as
304
+ * they are and never averaged into their neighbours.
175
305
  */
176
- export declare function quantizePalette(rgba: ArrayLike<number>, maxColors: number, { iterations }?: {
177
- iterations?: number;
178
- }): string[];
306
+ export declare function smoothShading(rgba: ArrayLike<number>, width: number, height: number, keep?: ArrayLike<number>): Uint8ClampedArray;
179
307
  /**
180
- * Pixel art's palette: its colours exactly, most-used first. Pixel art has a
181
- * handful of deliberate colours, and a one-pixel eye matters as much as the
182
- * sky, so nothing is merged or dropped for being rare or close to another.
183
- * Beyond `maxColors` distinct colours (a photo picked as pixel art), the
184
- * rarest ones take their nearest kept colour when pixels are labelled.
308
+ * Painted outlines made plain, before the palette is picked. A painter's line
309
+ * between two near-equal colours (a mouth on a shadowed face, dark trousers
310
+ * against a dark background) is only a few levels darker than either side, so
311
+ * it labels as one of them and is lost. A black-hat filter (the image's
312
+ * closing minus the image, over `radius` px) finds lines up to about twice
313
+ * that wide that are darker than both sides; each is darkened by twice its
314
+ * depth, at most LINE_MAX, colour kept, so it labels apart from both sides.
315
+ * Only lines that run a while are kept: brick, foliage and brush texture are
316
+ * dark too, but short. When `lines` (one entry per pixel) is given, each
317
+ * pixel darkened is marked in it with 1, for `smoothShading`'s `keep` and
318
+ * the tracer's `lines`, which leave them be.
319
+ *
320
+ * On a painted film poster at 2× (radius 3), with smoothing, this brought back
321
+ * the mouth, eyes, brows and jaw lines Illustration lost, and the outline
322
+ * parting dark trousers from a dark background, for twice the paths (2.1 to
323
+ * 3.6 MB). The trousers merged with the background until the lines were marked:
324
+ * the outline was found, but smoothing blurred it back into its sides, and,
325
+ * left unsmoothed, it labelled as the near-black of the trousers, close
326
+ * enough to the dark grey on either side to be folded in as a sliver.
185
327
  */
186
- export declare function exactPalette(rgba: ArrayLike<number>, maxColors: number): string[];
328
+ export declare function boostLines(rgba: ArrayLike<number>, width: number, height: number, radius?: number, lines?: Uint8Array): Uint8ClampedArray;
329
+ //#endregion
330
+ //#region src/centerline.d.ts
331
+ type CenterlineOptions = {
332
+ /** 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. */
333
+ threshold: number | 'auto' | null;
334
+ /** Ink and paper regions smaller than speckle × speckle pixels are folded into their surroundings. */
335
+ speckle: number;
336
+ /** Max distance in pixels between the skeleton and the fitted stroke. */
337
+ tolerance: number;
338
+ /** Turns sharper than this (degrees from straight) are corners. */
339
+ cornerAngle: number;
340
+ /** The stroke width in pixels; measured from the ink when left out. */
341
+ strokeWidth?: number;
342
+ /** The stroke colour. Default black. */
343
+ color?: string;
344
+ };
345
+ /** One stroked path: open subpaths (and closed loops), drawn with round caps and joins. */
346
+ type CenterlinePath = {
347
+ d: string;
348
+ stroke: string;
349
+ strokeWidth: number;
350
+ };
351
+ type CenterlineResult = {
352
+ width: number;
353
+ height: number;
354
+ paths: CenterlinePath[];
355
+ /** The stroke width measured from the ink, in pixels (whatever `strokeWidth` asked for). */
356
+ measuredWidth: number;
357
+ };
358
+ /** Trace to an SVG string; `centerline` gives the strokes as data. */
359
+ export declare const traceCenterline: (rgba: ArrayLike<number>, w: number, h: number, o: CenterlineOptions) => string;
360
+ export declare function centerlineToSvg(r: CenterlineResult): string;
361
+ export declare function centerline(rgba: ArrayLike<number>, w: number, h: number, o: CenterlineOptions): CenterlineResult;
187
362
  //#endregion
188
363
  //#region src/symmetry.d.ts
189
364
  /**
@@ -234,4 +409,4 @@ type SymmetryOptions = {
234
409
  */
235
410
  export declare function detectSymmetry(rgba: ArrayLike<number>, w: number, h: number, options?: SymmetryOptions): Symmetry[];
236
411
  //#endregion
237
- export type { Cubic, FitOptions, InlayOptions, InlayPath, InlayResult, MirrorSymmetry, PathNode, Pt, Rgb, RotationalSymmetry, Subpath, Symmetry, SymmetryOptions };
412
+ export type { CenterlineOptions, CenterlinePath, CenterlineResult, Cubic, FitOptions, Gradient, GradientStop, InlayOptions, InlayPath, InlayResult, MirrorSymmetry, PathNode, Pt, Rgb, RotationalSymmetry, Subpath, Symmetry, SymmetryOptions };