Skip to content

Instantly share code, notes, and snippets.

@kchapelier
Created June 18, 2017 09:07
Show Gist options
  • Save kchapelier/b1fd7e71f5378b871e3d6daa5ae193dc to your computer and use it in GitHub Desktop.
Save kchapelier/b1fd7e71f5378b871e3d6daa5ae193dc to your computer and use it in GitHub Desktop.
1D gaussian kernel
// based on https://warpycode.wordpress.com/2009/04/13/computing-a-1d-gaussian-kernel/
// see http://www.stat.wisc.edu/~mchung/teaching/MIA/reading/diffusion.gaussian.kernel.pdf.pdf for more info
var gaussianKernel1d = (function () {
var sqr2pi = Math.sqrt(2 * Math.PI);
return function gaussianKernel1d (size, sigma) {
"use strict";
// ensure size is even and prepare variables
var width = (size / 2) | 0,
kernel = new Array(width * 2 + 1),
norm = 1.0 / (sqr2pi * sigma),
coefficient = 2 * sigma * sigma,
total = 0,
x;
// set values and increment total
for (x = -width; x <= width; x++) {
total += kernel[width + x] = norm * Math.exp(-x * x / coefficient);
}
// divide by total to make sure the sum of all the values is equal to 1
for (x = 0; x < kernel.length; x++) {
kernel[x] /= total;
}
return kernel;
};
}());
module.exports = gaussianKernel1d;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment