-
Notifications
You must be signed in to change notification settings - Fork 0
/
sobel.js
76 lines (65 loc) · 2.22 KB
/
sobel.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
69
70
71
72
73
74
75
76
function Sobel(imageData, shreshold) {
var width = imageData.width;
var height = imageData.height;
var kernelX = [
[-1,0,1],
[-2,0,2],
[-1,0,1]
];
var kernelY = [
[-1,-2,-1],
[0,0,0],
[1,2,1]
];
var pointCollection = [];
var grayscaleData = [];
function bindPixelAt(data) {
return function(x, y, i) {
i = i || 0;
return data[((width * y) + x) * 4 + i];
};
}
var data = imageData.data;
var pixelAt = bindPixelAt(data);
var x, y;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
var r = pixelAt(x, y, 0);
var g = pixelAt(x, y, 1);
var b = pixelAt(x, y, 2);
var avg = (r + g + b) / 3;
grayscaleData.push(avg, avg, avg, 255);
}
}
pixelAt = bindPixelAt(grayscaleData);
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
var pixelX = (
(kernelX[0][0] * pixelAt(x - 1, y - 1)) +
(kernelX[0][1] * pixelAt(x, y - 1)) +
(kernelX[0][2] * pixelAt(x + 1, y - 1)) +
(kernelX[1][0] * pixelAt(x - 1, y)) +
(kernelX[1][1] * pixelAt(x, y)) +
(kernelX[1][2] * pixelAt(x + 1, y)) +
(kernelX[2][0] * pixelAt(x - 1, y + 1)) +
(kernelX[2][1] * pixelAt(x, y + 1)) +
(kernelX[2][2] * pixelAt(x + 1, y + 1))
);
var pixelY = (
(kernelY[0][0] * pixelAt(x - 1, y - 1)) +
(kernelY[0][1] * pixelAt(x, y - 1)) +
(kernelY[0][2] * pixelAt(x + 1, y - 1)) +
(kernelY[1][0] * pixelAt(x - 1, y)) +
(kernelY[1][1] * pixelAt(x, y)) +
(kernelY[1][2] * pixelAt(x + 1, y)) +
(kernelY[2][0] * pixelAt(x - 1, y + 1)) +
(kernelY[2][1] * pixelAt(x, y + 1)) +
(kernelY[2][2] * pixelAt(x + 1, y + 1))
);
var magnitude = Math.sqrt((pixelX * pixelX) + (pixelY * pixelY))>>>0;
if (magnitude > shreshold)
pointCollection.push([x, y]);
}
}
return pointCollection;
}