-
-
Save dtmrc/b1dc53797603255458609f57faab0af7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Adapted from: https://digitalbunker.dev/2020/09/13/understanding-gaussian-blurs/ | |
function gaussianBlurMatrix(blurRadius: number) { | |
if (blurRadius !== Math.round(blurRadius) || blurRadius <= 0) { | |
throw Error('Blur radius must be a positive integer') | |
} | |
const kernel: number[] = [] | |
const kernelWidth = 1 + 2 * blurRadius | |
const kernelSize = kernelWidth * kernelWidth | |
const sigma = Math.max(1, blurRadius / 2) | |
const exponentDenominator = 2 * sigma * sigma | |
let sum = 0 | |
for (let i = 0; i < kernelSize; i++) { | |
// Distance from center pixel | |
const x = (i % kernelWidth) - blurRadius | |
const y = Math.floor(i / kernelWidth) - blurRadius | |
const exponentNumerator = -(x * x + y * y) | |
const kernelValue = | |
Math.pow(Math.E, exponentNumerator / exponentDenominator) / | |
(Math.PI * exponentDenominator) | |
kernel[i] = kernelValue | |
sum += kernelValue | |
} | |
return kernel.reduce( | |
(matrix, k, i) => | |
matrix + k / sum + (i % kernelWidth == kernelWidth - 1 ? '\n' : ' '), | |
'' | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment