@instruments/quadrat 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.
Files changed (77) hide show
  1. package/README.md +40 -2
  2. package/dist/analysis/analyze-surface-regions.d.ts +34 -0
  3. package/dist/analysis/analyze-surface-regions.d.ts.map +1 -0
  4. package/dist/analysis/analyze-surface-regions.js +47 -0
  5. package/dist/analysis/decode.d.ts +23 -0
  6. package/dist/analysis/decode.d.ts.map +1 -0
  7. package/dist/analysis/decode.js +48 -0
  8. package/dist/analysis/descriptors.d.ts +112 -0
  9. package/dist/analysis/descriptors.d.ts.map +1 -0
  10. package/dist/analysis/descriptors.js +248 -0
  11. package/dist/analysis/diagnostics.d.ts +45 -0
  12. package/dist/analysis/diagnostics.d.ts.map +1 -0
  13. package/dist/analysis/diagnostics.js +34 -0
  14. package/dist/analysis/index.d.ts +6 -0
  15. package/dist/analysis/index.d.ts.map +1 -0
  16. package/dist/analysis/index.js +2 -0
  17. package/dist/analysis/outline.d.ts +44 -0
  18. package/dist/analysis/outline.d.ts.map +1 -0
  19. package/dist/analysis/outline.js +301 -0
  20. package/dist/analysis/rank-suggestions.d.ts +21 -0
  21. package/dist/analysis/rank-suggestions.d.ts.map +1 -0
  22. package/dist/analysis/rank-suggestions.js +150 -0
  23. package/dist/analysis/repetition.d.ts +31 -0
  24. package/dist/analysis/repetition.d.ts.map +1 -0
  25. package/dist/analysis/repetition.js +105 -0
  26. package/dist/analysis/segmentation.d.ts +26 -0
  27. package/dist/analysis/segmentation.d.ts.map +1 -0
  28. package/dist/analysis/segmentation.js +81 -0
  29. package/dist/analysis/square-geometry.d.ts +34 -0
  30. package/dist/analysis/square-geometry.d.ts.map +1 -0
  31. package/dist/analysis/square-geometry.js +91 -0
  32. package/dist/analysis/surface-candidates.d.ts +45 -0
  33. package/dist/analysis/surface-candidates.d.ts.map +1 -0
  34. package/dist/analysis/surface-candidates.js +471 -0
  35. package/dist/analysis/thresholds.d.ts +189 -0
  36. package/dist/analysis/thresholds.d.ts.map +1 -0
  37. package/dist/analysis/thresholds.js +189 -0
  38. package/dist/analysis/types.d.ts +42 -0
  39. package/dist/analysis/types.d.ts.map +1 -0
  40. package/dist/analysis/types.js +2 -0
  41. package/dist/crops/crop-editor-state.d.ts +88 -0
  42. package/dist/crops/crop-editor-state.d.ts.map +1 -0
  43. package/dist/crops/crop-editor-state.js +121 -0
  44. package/dist/crops/crop-entries.d.ts +47 -0
  45. package/dist/crops/crop-entries.d.ts.map +1 -0
  46. package/dist/crops/crop-entries.js +46 -0
  47. package/dist/crops/crop-export.d.ts +21 -0
  48. package/dist/crops/crop-export.d.ts.map +1 -0
  49. package/dist/crops/crop-export.js +38 -0
  50. package/dist/crops/crop-geometry.d.ts +130 -0
  51. package/dist/crops/crop-geometry.d.ts.map +1 -0
  52. package/dist/crops/crop-geometry.js +271 -0
  53. package/dist/crops/crop-gesture.d.ts +175 -0
  54. package/dist/crops/crop-gesture.d.ts.map +1 -0
  55. package/dist/crops/crop-gesture.js +188 -0
  56. package/dist/crops/index.d.ts +10 -0
  57. package/dist/crops/index.d.ts.map +1 -0
  58. package/dist/crops/index.js +5 -0
  59. package/dist/index.d.ts +19 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +8 -0
  62. package/dist/surface-types.d.ts +41 -0
  63. package/dist/surface-types.d.ts.map +1 -0
  64. package/dist/surface-types.js +1 -0
  65. package/dist/worker/index.d.ts +4 -0
  66. package/dist/worker/index.d.ts.map +1 -0
  67. package/dist/worker/index.js +1 -0
  68. package/dist/worker/protocol.d.ts +28 -0
  69. package/dist/worker/protocol.d.ts.map +1 -0
  70. package/dist/worker/protocol.js +1 -0
  71. package/dist/worker/run-analysis.d.ts +21 -0
  72. package/dist/worker/run-analysis.d.ts.map +1 -0
  73. package/dist/worker/run-analysis.js +36 -0
  74. package/dist/worker/surface-worker.d.ts +2 -0
  75. package/dist/worker/surface-worker.d.ts.map +1 -0
  76. package/dist/worker/surface-worker.js +36 -0
  77. package/package.json +123 -3
@@ -0,0 +1,471 @@
1
+ // Stages 1 to 3 of the pipeline in analyze-surface-regions.ts: windows, segments, then one checked square per region.
2
+ import { describeWindow, materialSignature, descriptorDistance, descriptorTerms, meanChromaticity, sampleQuality, pixelFields, } from "./descriptors.js";
3
+ import { record, stopwatch } from "./diagnostics.js";
4
+ import { regionOutline } from "./outline.js";
5
+ import { repeatingTexture, repeatsAtLeast } from "./repetition.js";
6
+ import { segmentGrid } from "./segmentation.js";
7
+ import { largestInteriorSquare, regionStats } from "./square-geometry.js";
8
+ import { thresholds } from "./thresholds.js";
9
+ /**
10
+ * Proposes squares of one consistent surface at several window scales.
11
+ * Each scale segments a grid of overlapping windows by descriptor distance, fits the largest square in
12
+ * every segment, and keeps it only if windows tiling the square agree with the square as a whole.
13
+ * A square must hold at least `minimumTiles` windows per side, so it contains repeats of any period a window spans;
14
+ * the scale at which a surface scores best is chosen later by ranking.
15
+ *
16
+ * Returns many overlapping candidates, unsorted: the same place usually appears once per scale, and once
17
+ * more if a union of segments also passed. Ranking tidies that up.
18
+ */
19
+ export function surfaceCandidates(image, diagnostics) {
20
+ const { width, height, data } = image;
21
+ const clock = stopwatch(diagnostics);
22
+ const fields = pixelFields(image);
23
+ const result = [];
24
+ for (const side of thresholds.descriptor.scales) {
25
+ // Windows sit half a side apart, so neighbors overlap by half; the grid is columns x rows windows.
26
+ const step = side / 2;
27
+ const columns = Math.floor((width - side) / step) + 1;
28
+ const rows = Math.floor((height - side) / step) + 1;
29
+ // Too few windows to have neighbors at this scale.
30
+ if (columns < 2 || rows < 2) {
31
+ continue;
32
+ }
33
+ // Names this scale in diagnostics and candidate ids, e.g. "w16".
34
+ const pass = `w${side}`;
35
+ const descriptors = [];
36
+ for (let row = 0; row < rows; row++) {
37
+ for (let column = 0; column < columns; column++) {
38
+ descriptors.push(describeWindow(fields, column * step, row * step, side, side));
39
+ }
40
+ }
41
+ clock.mark("Windows");
42
+ const { labels, sizes } = segmentGrid(columns, rows, Uint8Array.from(descriptors, (d) => (d ? 1 : 0)), (a, b) => descriptorDistance(descriptors[a], descriptors[b]), thresholds.segmentation);
43
+ const merged = mergeSimilarNeighbors(labels, descriptors, columns, rows, diagnostics, pass);
44
+ // Per-pixel label maps (analysis image size) for the plain segments and for the segments after joining.
45
+ const pixels = ownedPixels(labels, columns, rows, step, width, height);
46
+ const joinedPixels = ownedPixels(merged.labels, columns, rows, step, width, height);
47
+ record(diagnostics, {
48
+ labels: pixels,
49
+ outcome: "kept",
50
+ pass,
51
+ reason: `${sizes.size} segments from ${columns}x${rows} windows`,
52
+ stage: "segment",
53
+ });
54
+ // The same map after joining, so a union of segments can be drawn too.
55
+ record(diagnostics, {
56
+ labels: joinedPixels,
57
+ outcome: "kept",
58
+ pass: `${pass}+`,
59
+ reason: `${merged.sizes.size} regions after joining`,
60
+ stage: "segment",
61
+ });
62
+ const plainStats = regionStats(pixels, width, height);
63
+ const joinedStats = regionStats(joinedPixels, width, height);
64
+ clock.mark("Regions");
65
+ // Fit the plain segments, and also each union of segments: a union can fail where its parts pass,
66
+ // so both go to ranking and the larger passing square wins.
67
+ for (const [map, regions, tag] of [
68
+ [pixels, sizes, pass],
69
+ [joinedPixels, merged.sizes, `${pass}+`],
70
+ ]) {
71
+ for (const [region, windows] of regions) {
72
+ if (windows < thresholds.segmentation.minimumWindows) {
73
+ continue;
74
+ }
75
+ // Skip regions that are unchanged by joining; the plain pass already covered them.
76
+ if (map === joinedPixels && !merged.joined.has(region)) {
77
+ continue;
78
+ }
79
+ const candidate = regionCandidate(fields, data, map, region, (map === joinedPixels ? joinedStats : plainStats).get(region), side, diagnostics, tag);
80
+ if (candidate) {
81
+ result.push(candidate);
82
+ }
83
+ }
84
+ }
85
+ clock.mark("Squares");
86
+ }
87
+ clock.report();
88
+ return result;
89
+ }
90
+ /**
91
+ * Joins segments that touch and whose mean descriptors are close, using the same distance as the
92
+ * segmentation but a looser limit. Graph merging is local, so one material can stay split by a slow
93
+ * gradient; the union is refitted as a single, larger square.
94
+ *
95
+ * Touching includes diagonals. Joins chain (A to B and B to C makes one region). Returns the new window
96
+ * labels and sizes, and `joined`: the labels of regions that actually absorbed another, so unchanged ones can be skipped.
97
+ */
98
+ function mergeSimilarNeighbors(labels, descriptors, columns, rows, diagnostics, pass) {
99
+ // Average each segment's window descriptors: sum them per label, then divide by the window count below.
100
+ const means = new Map();
101
+ const counts = new Map();
102
+ descriptors.forEach((descriptor, i) => {
103
+ if (!descriptor) {
104
+ return;
105
+ }
106
+ const mean = means.get(labels[i]);
107
+ if (!mean) {
108
+ means.set(labels[i], {
109
+ cdf: Float32Array.from(descriptor.cdf),
110
+ energy: descriptor.energy,
111
+ orientations: Float32Array.from(descriptor.orientations),
112
+ });
113
+ counts.set(labels[i], 1);
114
+ return;
115
+ }
116
+ for (let k = 0; k < mean.cdf.length; k++) {
117
+ mean.cdf[k] += descriptor.cdf[k];
118
+ }
119
+ for (let k = 0; k < mean.orientations.length; k++) {
120
+ mean.orientations[k] += descriptor.orientations[k];
121
+ }
122
+ mean.energy += descriptor.energy;
123
+ counts.set(labels[i], counts.get(labels[i]) + 1);
124
+ });
125
+ for (const [label, mean] of means) {
126
+ const n = counts.get(label);
127
+ for (let k = 0; k < mean.cdf.length; k++) {
128
+ mean.cdf[k] /= n;
129
+ }
130
+ for (let k = 0; k < mean.orientations.length; k++) {
131
+ mean.orientations[k] /= n;
132
+ }
133
+ mean.energy /= n;
134
+ }
135
+ // Union-find over segment labels: follow `parent` to a group's representative.
136
+ const parent = new Map([...means.keys()].map((label) => [label, label]));
137
+ const find = (label) => {
138
+ while (parent.get(label) !== label) {
139
+ label = parent.get(label);
140
+ }
141
+ return label;
142
+ };
143
+ let unions = 0;
144
+ for (let y = 0; y < rows; y++) {
145
+ for (let x = 0; x < columns; x++) {
146
+ const a = labels[y * columns + x];
147
+ if (a < 0) {
148
+ continue;
149
+ }
150
+ // Right, below, below-right and below-left: with every cell visited, that covers all eight neighbors.
151
+ for (const [dx, dy] of [
152
+ [1, 0],
153
+ [0, 1],
154
+ [1, 1],
155
+ [-1, 1],
156
+ ]) {
157
+ const nx = x + dx;
158
+ const ny = y + dy;
159
+ if (nx < 0 || nx >= columns || ny >= rows) {
160
+ continue;
161
+ }
162
+ const b = labels[ny * columns + nx];
163
+ if (b < 0 || find(a) === find(b)) {
164
+ continue;
165
+ }
166
+ if (descriptorDistance(means.get(a), means.get(b)) < thresholds.segmentation.regionMergeDistance) {
167
+ parent.set(find(b), find(a));
168
+ unions++;
169
+ }
170
+ }
171
+ }
172
+ }
173
+ const result = new Int32Array(labels.length);
174
+ const sizes = new Map();
175
+ const joined = new Set();
176
+ for (const label of means.keys()) {
177
+ if (find(label) !== label) {
178
+ joined.add(find(label));
179
+ }
180
+ }
181
+ for (let i = 0; i < labels.length; i++) {
182
+ result[i] = labels[i] < 0 ? -1 : find(labels[i]);
183
+ if (result[i] >= 0) {
184
+ sizes.set(result[i], (sizes.get(result[i]) ?? 0) + 1);
185
+ }
186
+ }
187
+ record(diagnostics, {
188
+ outcome: "kept",
189
+ pass: `${pass}-merge`,
190
+ reason: `${unions} neighboring segments joined`,
191
+ stage: "segment",
192
+ });
193
+ return { joined, labels: result, sizes };
194
+ }
195
+ /**
196
+ * Turns window labels into a per-pixel label map (-1 where no window owns the pixel). Windows overlap, so
197
+ * each owns only its central step x step cell, which makes every pixel belong to exactly one window;
198
+ * windows on the border also own the strip out to the image edge.
199
+ */
200
+ function ownedPixels(labels, columns, rows, step, width, height) {
201
+ const pixels = new Int32Array(width * height).fill(-1);
202
+ for (let row = 0; row < rows; row++) {
203
+ for (let column = 0; column < columns; column++) {
204
+ const label = labels[row * columns + column];
205
+ if (label < 0) {
206
+ continue;
207
+ }
208
+ const xa = column === 0 ? 0 : column * step + step / 2;
209
+ const xb = column === columns - 1 ? width : column * step + step * 1.5;
210
+ const ya = row === 0 ? 0 : row * step + step / 2;
211
+ const yb = row === rows - 1 ? height : row * step + step * 1.5;
212
+ for (let y = Math.floor(ya); y < Math.floor(yb); y++) {
213
+ for (let x = Math.floor(xa); x < Math.floor(xb); x++)
214
+ pixels[y * width + x] = label;
215
+ }
216
+ }
217
+ }
218
+ return pixels;
219
+ }
220
+ /**
221
+ * The window sides tried when testing a square of `width` pixels: the fixed scales plus the largest that
222
+ * still tiles it, smallest first. Coarse patterns and veined stone only agree once windows are a large
223
+ * share of the square, whatever its size in pixels.
224
+ */
225
+ export const stationaritySides = (width) => {
226
+ const largest = Math.floor(width / thresholds.crop.minimumTiles);
227
+ return [...new Set([...thresholds.descriptor.scales, largest])].sort((a, b) => a - b);
228
+ };
229
+ /**
230
+ * The distance no window may exceed at this many tiles per side. Fewer tiles means weaker evidence, so the
231
+ * limit is shaved: x0.8 at two tiles, x0.9 at three, and so on.
232
+ */
233
+ export const stationarityLimit = (tiles) => thresholds.crop.dispersionLimit *
234
+ (1 - thresholds.crop.thinEvidencePenalty / (tiles - 1));
235
+ /**
236
+ * Where the sampled windows start along one side of a square `width` pixels wide, for windows of `side`
237
+ * pixels. At most `maximumTilesPerSide` windows are spread from edge to edge (with gaps if the square holds more);
238
+ * the same offsets serve rows and columns. Needs at least `minimumTiles` windows to fit.
239
+ */
240
+ export const tileOffsets = (width, side) => {
241
+ const used = Math.min(Math.floor(width / side), thresholds.crop.maximumTilesPerSide);
242
+ return Array.from({ length: used }, (_, i) => Math.round((i * (width - side)) / (used - 1)));
243
+ };
244
+ /**
245
+ * The worst comparison among `windows` and `whole` with lighting relief: light scales a surface's brightness
246
+ * and edge strength but keeps its hue and the way its edges run, so when every window is textured, its edges
247
+ * run the same way and its hue matches, the color term is divided by `relief`. Otherwise the plain distance.
248
+ */
249
+ const relievedWorst = (windows, whole, relief) => {
250
+ const terms = [];
251
+ for (let i = 0; i < windows.length; i += 1) {
252
+ terms.push(descriptorTerms(windows[i], whole));
253
+ for (let j = i + 1; j < windows.length; j += 1) {
254
+ terms.push(descriptorTerms(windows[i], windows[j]));
255
+ }
256
+ }
257
+ const { lightingChromaLimit, lightingOrientationLimit, lightingTextureEnergy, } = thresholds.crop;
258
+ const hues = [whole, ...windows].map(meanChromaticity);
259
+ const lit = windows.every((w) => w.energy >= lightingTextureEnergy) &&
260
+ terms.every((t) => t.orientation < lightingOrientationLimit) &&
261
+ hues.every((a) => hues.every((b) => Math.hypot(a[0] - b[0], a[1] - b[1]) < lightingChromaLimit));
262
+ const eased = lit ? relief : 1;
263
+ let worst = 0;
264
+ for (const t of terms) {
265
+ worst = Math.max(worst, Math.hypot(t.color / eased, t.orientation, t.energy));
266
+ }
267
+ return worst;
268
+ };
269
+ /**
270
+ * How far windows of the best-fitting scale stray. At each scale holding enough windows per side, up to
271
+ * `maximumTilesPerSide` windows are spread across the square. Two worst cases are taken: any window
272
+ * against the square as a whole (a mixture drags the whole away from its parts), and any window against
273
+ * any other (a lone seam, edge or object makes one pair disagree). Both are held to one limit, tighter
274
+ * with few windows since the evidence is thin; the scale with the smallest distance-to-limit ratio is the
275
+ * square's stationarity scale. A mixture has no scale at which its windows agree, while a pattern agrees
276
+ * once windows span its period.
277
+ *
278
+ * Returns `dispersion` (the worst distance at the best scale, in descriptor distance), that `scale` (window
279
+ * side in analysis pixels) and `ratio` (worst distance divided by that scale's limit). The square passes
280
+ * when `ratio` is under 1; `dispersion` then feeds the score.
281
+ */
282
+ function stationarity(fields, rect, whole, relief) {
283
+ let best = { dispersion: Infinity, ratio: Infinity, scale: 0 };
284
+ for (const side of stationaritySides(rect.width)) {
285
+ const tiles = Math.floor(rect.width / side);
286
+ if (tiles < thresholds.crop.minimumTiles) {
287
+ break;
288
+ }
289
+ const limit = stationarityLimit(tiles);
290
+ const used = Math.min(tiles, thresholds.crop.maximumTilesPerSide);
291
+ const offsets = tileOffsets(rect.width, side);
292
+ const windows = [];
293
+ for (let row = 0; row < used; row++) {
294
+ for (let column = 0; column < used; column++) {
295
+ windows.push(describeWindow(fields, rect.x + offsets[column], rect.y + offsets[row], side, side));
296
+ }
297
+ }
298
+ let worst = 0;
299
+ if (relief === 1) {
300
+ // Stops early once this scale can no longer beat the best so far; `worst` is then incomplete but unused.
301
+ for (let i = 0; i < windows.length && worst / limit < best.ratio; i++) {
302
+ worst = Math.max(worst, descriptorDistance(windows[i], whole));
303
+ for (let j = i + 1; j < windows.length; j++) {
304
+ worst = Math.max(worst, descriptorDistance(windows[i], windows[j]));
305
+ }
306
+ }
307
+ }
308
+ else {
309
+ worst = relievedWorst(windows, whole, relief);
310
+ }
311
+ const ratio = worst / limit;
312
+ if (ratio < best.ratio) {
313
+ best = { dispersion: worst, ratio, scale: side };
314
+ }
315
+ }
316
+ return best;
317
+ }
318
+ /**
319
+ * The acceptance tests every proposed square must pass, in order: fully opaque, windows agree
320
+ * (`stationarity`), useful as a sample (`sampleQuality`). Used for the trimmed crop and again for `maxCrop`.
321
+ */
322
+ const checkSquare = (fields, data, rect) => {
323
+ const whole = describeWindow(fields, rect.x, rect.y, rect.width, rect.height);
324
+ if (whole === null) {
325
+ return { ok: false, reason: "transparent pixels" };
326
+ }
327
+ let { dispersion, scale, ratio } = stationarity(fields, rect, whole, 1);
328
+ // A second chance for a strongly repeating print whose color drifts under uneven light (see `lightingRelief`).
329
+ // Easing one term by `lightingRelief` lowers the ratio by that factor at most, so a worse square is not
330
+ // retried; the costly repeat test runs only once the eased agreement has passed.
331
+ if (ratio >= 1 && ratio < thresholds.crop.lightingRelief) {
332
+ const eased = stationarity(fields, rect, whole, thresholds.crop.lightingRelief);
333
+ if (eased.ratio < 1 &&
334
+ repeatsAtLeast(data, fields.width, rect, thresholds.crop.lightingRepeatPeak)) {
335
+ ({ dispersion, scale, ratio } = eased);
336
+ }
337
+ }
338
+ if (ratio >= 1) {
339
+ return {
340
+ detail: { dispersion, scale },
341
+ ok: false,
342
+ reason: "windows disagree",
343
+ };
344
+ }
345
+ // A large square that agrees best in halves may hold the same blend in each half; a real pattern also repeats.
346
+ if (thresholds.crop.halvesRepeatPeak > 0 &&
347
+ scale > Math.max(...thresholds.descriptor.scales) &&
348
+ !repeatsAtLeast(data, fields.width, rect, thresholds.crop.halvesRepeatPeak)) {
349
+ return {
350
+ detail: { dispersion, scale },
351
+ ok: false,
352
+ reason: "agrees best in halves and does not repeat",
353
+ };
354
+ }
355
+ const quality = sampleQuality(fields, rect.x, rect.y, rect.width, rect.height, whole.energy);
356
+ if (quality < thresholds.quality.minimum) {
357
+ return { detail: { quality }, ok: false, reason: "not useful as a sample" };
358
+ }
359
+ return { dispersion, ok: true, quality, scale, whole };
360
+ };
361
+ /**
362
+ * Turns one region into a candidate, or null with a diagnostics reason. Steps: take the largest square
363
+ * inside the region, trim `insetFraction` off each side, reject it if too small or if `checkSquare` fails,
364
+ * then test whether the untrimmed square also passes (that becomes `maxCrop`, what Expand grows to) and score.
365
+ * `side` is the window side of this pass, used only for outline smoothing; `pass` names the pass in ids.
366
+ */
367
+ function regionCandidate(fields, data, pixels, region, bounds, side, diagnostics, pass) {
368
+ const { width, height } = fields;
369
+ const tag = `${pass}#${region}`;
370
+ const interior = largestInteriorSquare(pixels, region, width, height, thresholds.crop.erosionPixels, bounds);
371
+ // Trim both sides so the square stays clear of the segment's uncertain edge. `rect` is the proposed crop.
372
+ const inset = Math.ceil(interior.width * thresholds.crop.insetFraction);
373
+ const rect = {
374
+ height: interior.height - inset * 2,
375
+ width: interior.width - inset * 2,
376
+ x: interior.x + inset,
377
+ y: interior.y + inset,
378
+ };
379
+ // Share of the analysis image the whole region covers (not just the square).
380
+ const coverage = bounds.count / (width * height);
381
+ const reject = (reason, detail) => {
382
+ record(diagnostics, {
383
+ coverage,
384
+ detail,
385
+ interior,
386
+ outcome: "rejected",
387
+ pass: tag,
388
+ reason,
389
+ rect,
390
+ stage: "crop",
391
+ });
392
+ };
393
+ if (rect.width <
394
+ Math.min(width, height) * thresholds.crop.minimumSideFraction) {
395
+ reject("square too small");
396
+ return null;
397
+ }
398
+ const checked = checkSquare(fields, data, rect);
399
+ if (!checked.ok) {
400
+ reject(checked.reason, checked.detail);
401
+ return null;
402
+ }
403
+ const { whole, dispersion, scale, quality } = checked;
404
+ // The uninset interior is what Expand grows to, and window ownership extends to the image edge, so it
405
+ // can touch a seam or transparent fringe that the inset square avoids. It must pass the same checks.
406
+ const expanded = interior.width === rect.width ? null : checkSquare(fields, data, interior);
407
+ const maxRect = expanded !== null && expanded.ok ? interior : rect;
408
+ record(diagnostics, {
409
+ coverage,
410
+ detail: {
411
+ dispersion,
412
+ energy: whole.energy,
413
+ quality,
414
+ scale,
415
+ ...(expanded !== null && !expanded.ok
416
+ ? { expand: `refused: ${expanded.reason}` }
417
+ : {}),
418
+ },
419
+ interior,
420
+ outcome: interior.width === rect.width ? "kept" : "shrunk",
421
+ pass: tag,
422
+ reason: `inset ${interior.width} to ${rect.width}`,
423
+ rect,
424
+ stage: "crop",
425
+ });
426
+ // Below the noise floor there are no real edges, so the square is described by its color alone.
427
+ const flat = whole.energy < thresholds.descriptor.noiseEnergy;
428
+ return {
429
+ descriptor: whole,
430
+ outline: () => regionOutline(pixels, region, width, height, side / 2, rect, bounds),
431
+ // Square root of the area share is the side as a fraction of the image (0-1). Both this and `score`
432
+ // multiply that by agreement and quality, but this one punishes disagreement fully, so a tidy small
433
+ // square beats a larger, messier look-alike when ranking picks which to keep.
434
+ representative: Math.sqrt((rect.width * rect.height) / (width * height)) *
435
+ Math.max(0, 1 -
436
+ (thresholds.ranking.representativePenalty * dispersion) /
437
+ thresholds.crop.dispersionLimit) *
438
+ quality,
439
+ signature: materialSignature(data, width, rect.x, rect.y, rect.width, whole),
440
+ suggestion: {
441
+ // What the square was proposed on: plain color, a repeating pattern, or irregular texture.
442
+ basis: flat
443
+ ? "colour"
444
+ : repeatingTexture(data, width, rect)
445
+ ? "repetition"
446
+ : "texture",
447
+ coverage,
448
+ crop: {
449
+ height: (rect.height * 100) / height,
450
+ width: (rect.width * 100) / width,
451
+ x: (rect.x * 100) / width,
452
+ y: (rect.y * 100) / height,
453
+ },
454
+ id: `surface-${tag}`,
455
+ maxCrop: {
456
+ height: (maxRect.height * 100) / height,
457
+ width: (maxRect.width * 100) / width,
458
+ x: (maxRect.x * 100) / width,
459
+ y: (maxRect.y * 100) / height,
460
+ },
461
+ // Side as a fraction of the image, times agreement (1 for windows that match perfectly, falling to
462
+ // 0.5 at the dispersion limit), times sample quality (0-1). Not a probability.
463
+ score: Math.sqrt((rect.width * rect.height) / (width * height)) *
464
+ (1 -
465
+ (thresholds.crop.dispersionPenalty * dispersion) /
466
+ thresholds.crop.dispersionLimit) *
467
+ quality,
468
+ shape: "square",
469
+ },
470
+ };
471
+ }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Trial values tuned by inspecting this prototype's example crops, not prescribed by the papers.
3
+ * "Analysis pixels" are pixels of the small analysis image (decode.ts), not of the source photo.
4
+ * "Descriptor distance" (descriptors.ts `descriptorDistance`) is how different two windows look: 1 means
5
+ * color, edge direction and edge strength together differ by one scale unit. "Material distance"
6
+ * (`materialDistance`) is a separate, lighting-tolerant measure used only to decide whether two finished
7
+ * crops show the same material. These are read when the detector runs, so the eval harness can patch them per run.
8
+ */
9
+ export declare const thresholds: {
10
+ /** Stage 3, fitting and checking one square per region. Lengths in analysis pixels, shares as fractions (0-1), tile counts as plain counts, dispersion in descriptor distance. */
11
+ readonly crop: {
12
+ /**
13
+ * Largest feature distance between any window tiling the square and the square as a whole, or between any two windows.
14
+ * Squares that straddle materials or hold a lone object fail it; patterns whose windows agree pass.
15
+ */
16
+ readonly dispersionLimit: 2;
17
+ /** Score lost at the limit, as a fraction: 0.5 means a square at the limit keeps half its size-based score. */
18
+ readonly dispersionPenalty: 0.5;
19
+ /** Pixels eroded from a segment before the square is fitted: a pixel counts only if everything this close to it is in the segment. Window ownership is already conservative. */
20
+ readonly erosionPixels: 1;
21
+ /**
22
+ * Repeat correlation (-1..1, `repeatsAtLeast`) a square must reach when its windows agree best once they are
23
+ * larger than every fixed scale (`descriptor.scales`), that is in halves of the square. Each half of a wide
24
+ * blend (blind, glass and sofa across a bay window) holds the same mix, so the halves agree; a large check or
25
+ * print agrees there too but also repeats. The cost: a frame-filling print whose repeat is longer than
26
+ * `repetition.maximumLag` gets a smaller crop. 0 is off.
27
+ */
28
+ readonly halvesRepeatPeak: 0.45;
29
+ /** Share of the fitted square's side trimmed from each edge (0.04 is 4%), to stay clear of uncertain boundaries; the outline already keeps the fit conservative. */
30
+ readonly insetFraction: 0.04;
31
+ /** Largest brightness-normalized chromaticity difference (unitless, as `material.chromaScale`) between any two windows, or a window and the whole, for the lighting relief. */
32
+ readonly lightingChromaLimit: 0.15;
33
+ /** Largest edge-direction term (descriptor distance) of any comparison for the lighting relief. */
34
+ readonly lightingOrientationLimit: 0.3;
35
+ /**
36
+ * Light changes a surface's brightness and edge strength but not its hue or edge directions, so a shaded
37
+ * wallpaper drifts across a square while its print stays put. When every window is textured, edge directions
38
+ * agree within `lightingOrientationLimit` and hue within `lightingChromaLimit`, the color term is divided by
39
+ * this. Only a second chance: it applies to a square that failed agreement and repeats at least
40
+ * `lightingRepeatPeak`, so squares that already pass are scored as before. 1 is off.
41
+ */
42
+ readonly lightingRelief: 2;
43
+ /** Repeat correlation (-1..1, `repeatsAtLeast`) a failed square needs before the lighting relief is tried: a clear print, not a blend. */
44
+ readonly lightingRepeatPeak: 0.6;
45
+ /** Mean gradient (8-bit intensity per pixel) every window needs for the relief; flat paint relies on color alone. */
46
+ readonly lightingTextureEnergy: 3;
47
+ /** Most windows sampled per side when testing agreement; pairwise comparison is quadratic in their number. */
48
+ readonly maximumTilesPerSide: 4;
49
+ /** Smallest crop side as a fraction of the image's shorter side. */
50
+ readonly minimumSideFraction: 0.06;
51
+ /**
52
+ * Windows per side a square must hold at the scale used to test agreement. Two is the least that gives
53
+ * a comparison at all (four windows); it is weak evidence, so `thinEvidencePenalty` tightens the limit there.
54
+ * A mixture whose parts straddle the windows evenly can still agree; in halves of a large square, `halvesRepeatPeak` catches it.
55
+ */
56
+ readonly minimumTiles: 2;
57
+ /** Fraction of the dispersion limit withheld, scaled by 1 / (tiles - 1): 20% at two tiles, 10% at three, so thin evidence must agree more tightly. */
58
+ readonly thinEvidencePenalty: 0.2;
59
+ };
60
+ /** Stage 1, describing windows. Window sides in analysis pixels; the scales turn each term of `descriptorDistance` into "one unit". */
61
+ readonly descriptor: {
62
+ /** Color histogram bins per channel (count): 32 bins is 8 of the 256 levels each. */
63
+ readonly colorBins: 32;
64
+ /** 8-bit levels (0-255): the mean per-channel color shift that counts as one unit of descriptor distance. */
65
+ readonly colorScale: 20;
66
+ /** Natural-log units of edge-strength ratio that count as one unit: 0.6 is about a 1.8x difference. */
67
+ readonly energyScale: 0.6;
68
+ /** Mean gradient (8-bit intensity per pixel) below which a window counts as flat; also added to both energies in the ratio, and edge direction counts fully only above twice this. */
69
+ readonly noiseEnergy: 1.5;
70
+ /** Edge-direction bins over half a turn (count): 8 bins is 22.5 degrees each. */
71
+ readonly orientationBins: 8;
72
+ /** Edge-direction chi-square distance (0-1) that counts as one unit of descriptor distance. */
73
+ readonly orientationScale: 0.15;
74
+ /** Window sides in analysis pixels, overlapping by half. A window must span a pattern period to describe it; 96 reaches large inlays and slat repeats. */
75
+ readonly scales: readonly [8, 16, 32, 48, 64, 96];
76
+ };
77
+ /** Image limits, in analysis pixels except `opaqueAlpha`. */
78
+ readonly input: {
79
+ /** Longest side of the analysis image, in pixels; the shared decoder (decode.ts) shrinks photos to this and never upscales. */
80
+ readonly analysisSide: 320;
81
+ /** Shortest side the detector accepts, in pixels; a smaller image gets no suggestions. */
82
+ readonly minimumSide: 16;
83
+ /** 8-bit alpha (0-255) at or above which a pixel counts as opaque; a window or square with any other pixel is rejected. */
84
+ readonly opaqueAlpha: 250;
85
+ };
86
+ /** Stage 4, `materialDistance`: unitless terms divided by these scales, fitted on labeled same/different-surface pairs. */
87
+ readonly material: {
88
+ /** Brightness-normalized chromaticity distance (red-green and yellow-blue axes together, unitless) that counts as one unit. */
89
+ readonly chromaScale: 0.16;
90
+ /** Added to each square's contrast (edge strength relative to brightness, unitless) before the log ratio, so flat squares compare finitely. */
91
+ readonly contrastFloor: 0.02;
92
+ /** 8-bit luminance levels added to mean luminance when dividing edge strength by it (contrast), for the same reason. */
93
+ readonly contrastOffset: 16;
94
+ /** Natural-log units of contrast ratio that count as one unit: 0.6 is about a 1.8x difference. */
95
+ readonly contrastScale: 0.6;
96
+ /** 8-bit luminance levels added to a square's mean luminance before taking its log, so near-black squares do not blow up. */
97
+ readonly lightnessOffset: 8;
98
+ /** Natural-log luminance units: 0.44 means a 1.55x brightness ratio counts as one unit. Lighting changes this term most, so it is the loosest of the four. */
99
+ readonly lightnessScale: 0.44;
100
+ /** Edge-direction chi-square distance (0-1) that counts as one unit; looser than the window-level `descriptor.orientationScale`. */
101
+ readonly orientationScale: 0.5;
102
+ };
103
+ /** Stage 5, drawing the outline. Analysis pixels, except `sigmaCells` (window cells) and `minimumLoopFraction` (share of the image area). */
104
+ readonly outline: {
105
+ /** Cap on the blur sigma, in analysis pixels. */
106
+ readonly maximumSigma: 10;
107
+ /** Loops (outer or hole) smaller than this share of the image are dropped as specks. */
108
+ readonly minimumLoopFraction: 0.002;
109
+ /** Blur sigma in window cells (half a window side), capped in analysis pixels so large cells do not erase shape. */
110
+ readonly sigmaCells: 1;
111
+ /** Ramer-Douglas-Peucker tolerance in analysis pixels, before curves are fitted. */
112
+ readonly simplifyTolerance: 0.5;
113
+ };
114
+ /** Stage 3, `sampleQuality`: luminance in 8-bit levels (0-255), shares as fractions of a square's pixels, and unitless information terms. Three 0-1 factors multiply. */
115
+ readonly quality: {
116
+ /** Luminance counted as clipped (cream paper and pale stone sit below it). */
117
+ readonly blownLuma: 250;
118
+ /** Extra share of clipped pixels, beyond `blownTolerance`, over which the unclipped factor falls from 1 to 0. */
119
+ readonly blownSpan: 0.4;
120
+ /** Share of clipped pixels tolerated with no penalty. */
121
+ readonly blownTolerance: 0.05;
122
+ /** Mean channel spread (max minus min, 8-bit levels) that alone makes a square fully informative. */
123
+ readonly chromaScale: 25;
124
+ /** Mean luminance (0-255) at or below which a square is useless, and the span over which it recovers fully. */
125
+ readonly darkFloor: 25;
126
+ readonly darkSpan: 35;
127
+ /** Information: edge energy (as a share of the noise floor) plus mean channel spread over this scale. */
128
+ readonly energyShare: 1;
129
+ /** Squares scoring below this are dropped; above it quality scales the score. */
130
+ readonly minimum: 0.2;
131
+ };
132
+ /** Stage 4, ranking: fractions of crop area or side, a count for `suggestionLimit`, and material-distance units for the duplicate terms. */
133
+ readonly ranking: {
134
+ /** Two crops are one material when material distance - sizeWeight x ln(size ratio) is below this (material-distance units). */
135
+ readonly duplicateThreshold: 0.7;
136
+ /** Share of an inner crop's area (0-1) that must lie inside a larger crop for it to count as mixture evidence there. */
137
+ readonly mixtureContainment: 0.9;
138
+ /**
139
+ * A crop holding two smaller passing crops of clearly different materials is a mixture, however well its own
140
+ * coarse windows agree (each quarter can hold the same blend of blind, glass and sofa). Dropped when two such
141
+ * inner crops are further apart than this in material distance, eased by `sizeWeight` like duplicates. Infinity is off.
142
+ */
143
+ readonly mixtureDistance: 2;
144
+ /**
145
+ * Smallest inner crop counted as mixture evidence, as a share of the outer crop's side; tinier ones sample edges
146
+ * and specks. A trade-off: at 0.1 single pieces of a large inlay count, so the inlaid stone floor's crop shrinks
147
+ * from 218 to 160 analysis pixels; at 0.15 it stays 218, but the bay-window blend of blind, glass and sofa
148
+ * (whose pure parts are 0.1-0.2 of it) comes back as the top crop. A pure smaller crop is preferred.
149
+ */
150
+ readonly mixtureInnerSide: 0.1;
151
+ /** Overlap area as a fraction of the smaller crop's area; above it the lower-scoring crop is dropped. */
152
+ readonly overlapFraction: 0.5;
153
+ /** A crop under this share of the best crop's side is dropped: beside a frame-filling crop, small ones only sample its margins or the backdrop. */
154
+ readonly relativeSide: 0.25;
155
+ /** Homogeneity weight when choosing which of two look-alike crops to keep; heavier than in the ranking score, since a clean crop beats a bigger straddling one. */
156
+ readonly representativePenalty: 1;
157
+ /** Material-distance units forgiven per unit of ln(size ratio), because a close-up of a texture drifts from the wide view: a crop half the size gets about 0.2 off. */
158
+ readonly sizeWeight: 0.3;
159
+ /** Most suggestions returned (count). */
160
+ readonly suggestionLimit: 7;
161
+ };
162
+ /** Labeling a square as repeating (repetition.ts). Analysis pixels for shifts and subsampling; correlations are unitless (-1..1). */
163
+ readonly repetition: {
164
+ /** The largest shift is also capped at the square's side divided by this, so 3 means a third of the side. */
165
+ readonly cropLagDivisor: 3;
166
+ /** Largest shift tried, in analysis pixels. */
167
+ readonly maximumLag: 36;
168
+ /** Smallest shift tried when looking for a recovered peak. Neighboring pixels (shifts of 1-2) always correlate, so they say nothing about a repeat. */
169
+ readonly minimumLag: 3;
170
+ /** Correlation a peak must exceed. Rejects smooth gradients. */
171
+ readonly minimumPeak: 0.45;
172
+ /** How far the peak must rise above the lowest correlation seen at smaller shifts (from 2 up). Rejects smooth gradients. */
173
+ readonly minimumRecovery: 0.25;
174
+ /** Every nth pixel is read in each direction when correlating, to save time (analysis pixels). */
175
+ readonly sampleStep: 2;
176
+ };
177
+ /** Stage 2, segmentation. Descriptor-distance units unless stated; `minimumWindows` is a count of windows. */
178
+ readonly segmentation: {
179
+ /** Adaptive size term k: a region of n windows tolerates k / n extra internal distance, so small regions join freely. */
180
+ readonly componentScale: 4;
181
+ /** Hard cap on the descriptor distance that may join two windows. */
182
+ readonly mergeLimit: 1.5;
183
+ /** A segment needs this many windows before its square is considered. */
184
+ readonly minimumWindows: 4;
185
+ /** Touching segments whose mean descriptors are closer than this are joined before squares are fitted. */
186
+ readonly regionMergeDistance: 1;
187
+ };
188
+ };
189
+ //# sourceMappingURL=thresholds.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thresholds.d.ts","sourceRoot":"","sources":["../../src/analysis/thresholds.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU;IACrB,kLAAkL;aAClL,IAAI;QACF;;;WAGG;iBACH,eAAe,EAAE,CAAC;QAClB,+GAA+G;iBAC/G,iBAAiB,EAAE,GAAG;QACtB,gLAAgL;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