/
laplacian.js
68 lines (65 loc) · 1.38 KB
/
laplacian.js
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
/**
* Laplacian edge detection
*/
export default class Laplacian {
// https://algorithm.joho.info/image-processing/laplacian-filter/
/**
* @param {number} th Threshold
* @param {4 | 8} [n] Number of neighborhoods
*/
constructor(th, n = 4) {
this._threshold = th
this._n = n
}
_convolute(x, kernel) {
const a = []
for (let i = 0; i < x.length; i++) {
a[i] = []
for (let j = 0; j < x[i].length; j++) {
let v = 0
for (let s = 0; s < kernel.length; s++) {
let n = i + s - Math.floor(kernel.length / 2)
n = Math.max(0, Math.min(x.length - 1, n))
for (let t = 0; t < kernel[s].length; t++) {
let m = j + t - Math.floor(kernel[s].length / 2)
m = Math.max(0, Math.min(x[n].length - 1, m))
v += x[n][m] * kernel[s][t]
}
}
a[i][j] = v
}
}
return a
}
/**
* Returns predicted edge flags.
*
* @param {Array<Array<number>>} x Training data
* @returns {Array<Array<boolean>>} Predicted values. `true` if a pixel is edge.
*/
predict(x) {
let k = null
if (this._n === 4) {
k = [
[0, 1, 0],
[1, -4, 1],
[0, 1, 0],
]
} else {
k = [
[1, 1, 1],
[1, -8, 1],
[1, 1, 1],
]
}
const gl = this._convolute(x, k)
const g = []
for (let i = 0; i < gl.length; i++) {
g[i] = []
for (let j = 0; j < gl[i].length; j++) {
g[i][j] = gl[i][j] > this._threshold
}
}
return g
}
}