-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgaussian.js
65 lines (56 loc) · 1.9 KB
/
gaussian.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
(function (imageproc) {
"use strict";
/*
* Apply a Gaussian filter to the input data
*/
imageproc.gaussianBlur = function (inputData, outputData, size) {
/* Calculate the sigma value */
var sigma = size / 4;
var halfSize = Math.floor(size / 2);
/* Calculate the row/column matrix */
var rowMatrix = [];
for (var i = 0; i < size; i++) {
rowMatrix[i] =
Math.exp(-Math.pow(i - halfSize, 2) / (2 * Math.pow(sigma, 2))) /
(Math.sqrt(2 * Math.PI) * sigma);
}
/* Create the kernel */
var kernel = [];
var divisor = 0;
for (var i = 0; i < size; i++) {
kernel[i] = [];
for (var j = 0; j < size; j++) {
kernel[i][j] = rowMatrix[i] * rowMatrix[j];
divisor += kernel[i][j];
}
}
/***** DO NOT REMOVE - for marking *****/
console.log("Sigma:", sigma);
console.log("Kernel:", kernel.toString());
console.log("Divisor:", divisor);
/***** DO NOT REMOVE - for marking *****/
/* Apply the gaussian filter */
for (var y = 0; y < inputData.height; y++) {
for (var x = 0; x < inputData.width; x++) {
var sumR = 0,
sumG = 0,
sumB = 0;
/* Sum the product of the kernel on the pixels */
for (var j = -halfSize; j <= halfSize; j++) {
for (var i = -halfSize; i <= halfSize; i++) {
var pixel = imageproc.getPixel(inputData, x + i, y + j);
var coeff = kernel[j + halfSize][i + halfSize];
sumR += pixel.r * coeff;
sumG += pixel.g * coeff;
sumB += pixel.b * coeff;
}
}
/* Set the averaged pixel to the output data */
var i = (x + y * outputData.width) * 4;
outputData.data[i] = sumR / divisor;
outputData.data[i + 1] = sumG / divisor;
outputData.data[i + 2] = sumB / divisor;
}
}
};
})((window.imageproc = window.imageproc || {}));