Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a 2D Gaussian Filter in Tensorflow?

How can I implement a 2D low pass (also known as blurring) filter in Tensorflow using a gaussian kernel?

like image 813
zephyrus Avatar asked Aug 24 '18 23:08

zephyrus


People also ask

What is a 2d Gaussian filter?

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.

How do you define a Gaussian filter?

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).

Which is better Gaussian or median filter?

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.

Is Gaussian filter faster than median 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.


1 Answers

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")
like image 96
zephyrus Avatar answered Sep 20 '22 12:09

zephyrus