# Difference between revisions of "Spatially Varying Blur"

Spatially varying blur can be important for a number of effects, not the least of which is depth-of-field. Unfortunately SVG does not support this directly and we need to make some approximation of the effect.

One possibility is to do a simple linear interpolation between two blurs, but this tends to give an effective kernel which is only a very poor fit to the true kernel desired, it tends to give a much too sharp result.

This page looks at possibilities for creating an improved spatially varying blur.

## L2-minimized fit

In general the easiest global error metric to minimize is the l2-norm. This is simply (the root of) the integral of the squared error. Which in this case can be formulated as ($\displaystyle{ g(\sigma) }$ is the kernel of a Gaussian blur with standard deviation $\displaystyle{ \sigma }$, $\displaystyle{ G(\sigma_a,\sigma_b) }$ is the integral of the product of two kernels, $\displaystyle{ \sigma_1\lt \sigma\lt \sigma_2 }$ and $\displaystyle{ 0\lt a\lt 1 }$)

\displaystyle{ \begin{align} e(\sigma,\sigma_1,\sigma_2,a)&=\int_{-\infty}^{\infty}\left[g(\sigma)-\left((1-a)g(\sigma_1)+a\,g(\sigma_2)\right)\right]^2dx \\&=\int_{-\infty}^{\infty}g(\sigma)^2-2g(\sigma)\left((1-a)g(\sigma_1)+a\,g(\sigma_2)\right)+\left((1-a)g(\sigma_1)+a\,g(\sigma_2)\right)^2dx \\&=G(\sigma,\sigma)-2\left[(1-a)G(\sigma,\sigma_1)+a\,G(\sigma,\sigma_2)\right]+(1-a)^2G(\sigma_1,\sigma_1)+2a(1-a)G(\sigma_1,\sigma_2)+a^2\,G(\sigma_2,\sigma_2) .\end{align} }

Equating the derivative to zero (in order to minimize the quadratic equation in $\displaystyle{ a }$) we get

\displaystyle{ \begin{align} 0&=2\left[G(\sigma,\sigma_1)-\,G(\sigma,\sigma_2)\right]-2(1-a)G(\sigma_1,\sigma_1)+2(1-2a)G(\sigma_1,\sigma_2)+2a\,G(\sigma_2,\sigma_2) \\0&=G(\sigma,\sigma_1)-\,G(\sigma,\sigma_2)-G(\sigma_1,\sigma_1)+a\,G(\sigma_1,\sigma_1)+G(\sigma_1,\sigma_2)-2a\,G(\sigma_1,\sigma_2)+a\,G(\sigma_2,\sigma_2) \\a&=\frac{G(\sigma,\sigma_2)-G(\sigma,\sigma_1)+G(\sigma_1,\sigma_1)-G(\sigma_1,\sigma_2)}{G(\sigma_1,\sigma_1)-2\,G(\sigma_1,\sigma_2)+G(\sigma_2,\sigma_2)} .\end{align} }

This uses

\displaystyle{ \begin{align} g(\sigma)&=\frac{1}{\sqrt{2\pi\sigma^2}}e^{-x^2/(2\sigma^2)} \\G(\sigma_a,\sigma_b)&=\frac{1}{\sqrt{2\pi(\sigma_a^2+\sigma_b^2)}} .\end{align} }