File size: 10,324 Bytes
5d2240d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/**
 * Traditional (non-learned) image segmentation.
 *
 * This file is the "classic computer vision" baseline for the mini-lab. Nothing
 * here is trained on data: every decision comes from pixel statistics. That is
 * exactly the point of the experiment — students can see where a purely
 * hand-designed rule succeeds and where it falls apart.
 *
 * Implemented methods:
 *   - global binary threshold with a manual cutoff
 *   - Otsu's method (automatic cutoff from the histogram)
 *   - adaptive local-mean threshold (handles uneven lighting)
 * followed by optional morphological cleanup and connected-component labelling.
 */

/** Rec. 601 luminance, the standard greyscale conversion. */
export function toGrayscale(imageData) {
  const { data, width, height } = imageData;
  const gray = new Uint8ClampedArray(width * height);
  for (let i = 0, p = 0; i < gray.length; i++, p += 4) {
    gray[i] = (data[p] * 0.299 + data[p + 1] * 0.587 + data[p + 2] * 0.114) | 0;
  }
  return gray;
}

export function buildHistogram(gray) {
  const histogram = new Uint32Array(256);
  for (let i = 0; i < gray.length; i++) histogram[gray[i]]++;
  return histogram;
}

/**
 * Otsu's method: pick the threshold that maximises between-class variance.
 * Equivalent to minimising the weighted sum of the two class variances.
 *
 * A perfectly bimodal histogram has a whole plateau of thresholds with the same
 * variance. Reporting the middle of that plateau rather than its first value
 * keeps the cutoff away from the noise of the lower mode.
 */
export function otsuThreshold(histogram, total) {
  let sum = 0;
  for (let t = 0; t < 256; t++) sum += t * histogram[t];

  let sumBackground = 0;
  let weightBackground = 0;
  let bestVariance = -1;
  let plateauLow = 0;
  let plateauHigh = 0;

  for (let t = 0; t < 256; t++) {
    weightBackground += histogram[t];
    if (weightBackground === 0) continue;

    const weightForeground = total - weightBackground;
    if (weightForeground === 0) break;

    sumBackground += t * histogram[t];
    const meanBackground = sumBackground / weightBackground;
    const meanForeground = (sum - sumBackground) / weightForeground;
    const delta = meanBackground - meanForeground;

    // Between-class variance, scaled by the class weights.
    const variance = weightBackground * weightForeground * delta * delta;

    if (variance > bestVariance + 1e-9) {
      bestVariance = variance;
      plateauLow = t;
      plateauHigh = t;
    } else if (Math.abs(variance - bestVariance) <= 1e-9) {
      plateauHigh = t;
    }
  }

  return Math.round((plateauLow + plateauHigh) / 2);
}

/** Mean grey value inside a clamped window, using a summed-area table. */
function buildIntegral(gray, width, height) {
  const integral = new Uint32Array((width + 1) * (height + 1));
  for (let y = 0; y < height; y++) {
    let rowSum = 0;
    for (let x = 0; x < width; x++) {
      rowSum += gray[y * width + x];
      integral[(y + 1) * (width + 1) + (x + 1)] = integral[y * (width + 1) + (x + 1)] + rowSum;
    }
  }
  return integral;
}

/**
 * Adaptive thresholding: compare each pixel with the mean of its local window.
 * Unlike a global cutoff this survives a lighting gradient, which is why it was
 * the workhorse of document scanning long before learned segmentation.
 */
export function adaptiveThreshold(gray, width, height, blockSize, constant) {
  const integral = buildIntegral(gray, width, height);
  const stride = width + 1;
  const radius = Math.max(1, Math.floor(blockSize / 2));
  const mask = new Uint8Array(width * height);

  for (let y = 0; y < height; y++) {
    const y0 = Math.max(0, y - radius);
    const y1 = Math.min(height - 1, y + radius);

    for (let x = 0; x < width; x++) {
      const x0 = Math.max(0, x - radius);
      const x1 = Math.min(width - 1, x + radius);

      const area = (x1 - x0 + 1) * (y1 - y0 + 1);
      const sum =
        integral[(y1 + 1) * stride + (x1 + 1)] -
        integral[y0 * stride + (x1 + 1)] -
        integral[(y1 + 1) * stride + x0] +
        integral[y0 * stride + x0];

      mask[y * width + x] = gray[y * width + x] > sum / area - constant ? 1 : 0;
    }
  }
  return mask;
}

/**
 * 3x3 dilation: a pixel survives if any neighbour in the window is foreground.
 */
function dilate(mask, width, height) {
  const out = new Uint8Array(mask.length);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      let hit = 0;
      for (let dy = -1; dy <= 1 && !hit; dy++) {
        const ny = y + dy;
        if (ny < 0 || ny >= height) continue;
        for (let dx = -1; dx <= 1; dx++) {
          const nx = x + dx;
          if (nx < 0 || nx >= width) continue;
          if (mask[ny * width + nx]) {
            hit = 1;
            break;
          }
        }
      }
      out[y * width + x] = hit;
    }
  }
  return out;
}

/**
 * 3x3 erosion: a pixel survives only if every neighbour in the window is
 * foreground. Out-of-frame neighbours are ignored rather than treated as
 * background, so blobs touching the border are not shaved off.
 */
function erode(mask, width, height) {
  const out = new Uint8Array(mask.length);
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      let keep = 1;
      for (let dy = -1; dy <= 1 && keep; dy++) {
        const ny = y + dy;
        if (ny < 0 || ny >= height) continue;
        for (let dx = -1; dx <= 1; dx++) {
          const nx = x + dx;
          if (nx < 0 || nx >= width) continue;
          if (!mask[ny * width + nx]) {
            keep = 0;
            break;
          }
        }
      }
      out[y * width + x] = keep;
    }
  }
  return out;
}

/**
 * Morphological opening followed by closing: the opening deletes specks the
 * threshold invented, the closing fills pinholes inside real objects.
 * Classic segmentation almost always needs this manual cleanup step — a detail
 * the learned models handle implicitly.
 */
export function denoiseMask(mask, width, height) {
  const opened = dilate(erode(mask, width, height), width, height);
  return erode(dilate(opened, width, height), width, height);
}

/**
 * Two-pass connected-component labelling (union-find, 8-connectivity).
 *
 * Returns `components` sorted by area, largest first, plus the `labels` map so
 * callers can paint each blob in its own colour — the same per-region view the
 * learned models get, rather than a bounding box.
 */
export function labelComponents(mask, width, height, minArea = 1) {
  const labels = new Int32Array(width * height).fill(-1);
  const parent = [];

  const find = (a) => {
    while (parent[a] !== a) {
      parent[a] = parent[parent[a]];
      a = parent[a];
    }
    return a;
  };
  const union = (a, b) => {
    const ra = find(a);
    const rb = find(b);
    if (ra !== rb) parent[rb] = ra;
  };

  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const i = y * width + x;
      if (!mask[i]) continue;

      const neighbours = [];
      if (x > 0 && labels[i - 1] >= 0) neighbours.push(labels[i - 1]);
      if (y > 0) {
        if (labels[i - width] >= 0) neighbours.push(labels[i - width]);
        if (x > 0 && labels[i - width - 1] >= 0) neighbours.push(labels[i - width - 1]);
        if (x < width - 1 && labels[i - width + 1] >= 0) neighbours.push(labels[i - width + 1]);
      }

      if (neighbours.length === 0) {
        labels[i] = parent.length;
        parent.push(parent.length);
      } else {
        const smallest = Math.min(...neighbours);
        labels[i] = smallest;
        for (const n of neighbours) union(smallest, n);
      }
    }
  }

  // Second pass: resolve every pixel to its root label and gather statistics.
  const stats = new Map();
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const i = y * width + x;
      if (labels[i] < 0) continue;

      const root = find(labels[i]);
      labels[i] = root;

      let entry = stats.get(root);
      if (!entry) {
        entry = { label: root, area: 0, xmin: x, ymin: y, xmax: x, ymax: y, sumX: 0, sumY: 0 };
        stats.set(root, entry);
      }
      entry.area++;
      entry.sumX += x;
      entry.sumY += y;
      if (x < entry.xmin) entry.xmin = x;
      if (y < entry.ymin) entry.ymin = y;
      if (x > entry.xmax) entry.xmax = x;
      if (y > entry.ymax) entry.ymax = y;
    }
  }

  const components = [...stats.values()]
    .filter((component) => component.area >= minArea)
    .map((component) => ({
      ...component,
      cx: component.sumX / component.area,
      cy: component.sumY / component.area,
    }))
    .sort((a, b) => b.area - a.area);

  return { components, labels };
}

/**
 * Run the whole classic pipeline for one image.
 *
 * @returns {{mask: Uint8Array, labels: Int32Array, threshold: number,
 *            foreground: number, components: object[],
 *            histogram: Uint32Array, method: string}}
 */
export function runThreshold(imageData, options = {}) {
  const method = options.method || 'otsu';
  const { width, height } = imageData;
  const gray = toGrayscale(imageData);
  const histogram = buildHistogram(gray);
  const total = width * height;

  let mask;
  let threshold;

  if (method === 'adaptive') {
    const blockSize = options.blockSize ?? 35;
    const constant = options.constant ?? 10;
    mask = adaptiveThreshold(gray, width, height, blockSize, constant);
    // Report the equivalent global cutoff so the slider still means something.
    threshold = otsuThreshold(histogram, total);
  } else {
    threshold = method === 'otsu' ? otsuThreshold(histogram, total) : Math.round(options.threshold ?? 128);
    mask = new Uint8Array(total);
    for (let i = 0; i < total; i++) mask[i] = gray[i] > threshold ? 1 : 0;
  }

  if (options.invert) {
    for (let i = 0; i < mask.length; i++) mask[i] = mask[i] ? 0 : 1;
  }

  if (options.denoise) {
    mask = denoiseMask(mask, width, height);
  }

  let foreground = 0;
  for (let i = 0; i < mask.length; i++) foreground += mask[i];

  // Ignore specks: anything under 0.05% of the frame is noise, not an object.
  const minArea = Math.max(1, Math.round(total * 0.0005));
  const { components, labels } = labelComponents(mask, width, height, minArea);

  return { mask, labels, threshold, foreground, components, histogram, method };
}