How can I implement a 2D low pass (also known as blurring) filter in Tensorflow using a gaussian kernel?
Brief Description. The Gaussian smoothing operator is a 2-D convolution operator that is used to `blur' images and remove detail and noise. In this sense it is similar to the mean filter, but it uses a different kernel that represents the shape of a Gaussian (`bell-shaped') hump.
In electronics and signal processing, a Gaussian filter is a filter whose impulse response is a Gaussian function (or an approximation to it, since a true Gaussian response would have infinite impulse response).
As a general rule of thumb - if your noise is salt-n-pepper you should use the median filter. If you assume that the original signal is low frequency (like a smooth surface with no texture) then the gaussian filter is a good choice. Box filter (mean) is usually used to approximate the gaussian filter.
When we consider only the time parameter, then the Median filter gives better results in less time in comparison to a Gaussian filter and a denoise autoencoder filter.
First define a normalized 2D gaussian kernel:
def gaussian_kernel(size: int,
mean: float,
std: float,
):
"""Makes 2D gaussian Kernel for convolution."""
d = tf.distributions.Normal(mean, std)
vals = d.prob(tf.range(start = -size, limit = size + 1, dtype = tf.float32))
gauss_kernel = tf.einsum('i,j->ij',
vals,
vals)
return gauss_kernel / tf.reduce_sum(gauss_kernel)
Next, use tf.nn.conv2d to convolve this kernel with an image:
# Make Gaussian Kernel with desired specs.
gauss_kernel = gaussian_kernel( ... )
# Expand dimensions of `gauss_kernel` for `tf.nn.conv2d` signature.
gauss_kernel = gauss_kernel[:, :, tf.newaxis, tf.newaxis]
# Convolve.
tf.nn.conv2d(image, gauss_kernel, strides=[1, 1, 1, 1], padding="SAME")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With