python has fspecial('gaussian', f_wid, sigma)
to make gaussian easy(link). Does Javascript has similar utils?
Asked
Active
Viewed 531 times
2

Jimmy
- 33
- 6
-
What exactly are you searching for? What have you tried to resolve your problem? Where are you stuck? – Nico Haase Sep 13 '22 at 09:42
-
@NicoHaase Good question template, I will do like that next time. Thank you. – Jimmy Sep 13 '22 at 10:13
1 Answers
4
Yes this is possible with Javascript, but it isn't as easy as it is with Python.
Since you are looking for a javascript solution, it is good to know that HTML5 Canvas element has some built-in filters. An example snippet of Canvas blur looks like this:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const texture = document.querySelector("img");
texture.onload = function(){
canvas.width = this.width;
canvas.height = this.height;
ctx.filter = 'blur(10px)';
ctx.drawImage(this, 0, 0);
}
Other approaches that work well for the web are CSS and SVG filters and they are compatible with Canvas as well. However, they are not well designed for cases where our code runs in Web Worker.
The makeGaussKernel function creates a one dimensional array with the appropriate filter size and coefficients.
function makeGaussKernel(sigma){
const GAUSSKERN = 6.0;
var dim = parseInt(Math.max(3.0, GAUSSKERN * sigma));
var sqrtSigmaPi2 = Math.sqrt(Math.PI*2.0)*sigma;
var s2 = 2.0 * sigma * sigma;
var sum = 0.0;
var kernel = new Float32Array(dim - !(dim & 1)); // Make it odd number
const half = parseInt(kernel.length / 2);
for (var j = 0, i = -half; j < kernel.length; i++, j++)
{
kernel[j] = Math.exp(-(i*i)/(s2)) / sqrtSigmaPi2;
sum += kernel[j];
}
// Normalize the gaussian kernel to prevent image darkening/brightening
for (var i = 0; i < dim; i++) {
kernel[i] /= sum;
}
return kernel;
}

FUZIION
- 1,606
- 1
- 6
- 19
-
2Please include enough information from the link in your answer, that your answer would be valid without it (E.g. if that link disappears in the future) – DBS Sep 13 '22 at 09:43
-