How to obtain a gaussian filter in javascript

Viewed 37

python has fspecial('gaussian', f_wid, sigma) to make gaussian easy(link). Does Javascript has similar utils?

1 Answers

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;
}

Source Fiveko

Related