Showing posts with label source code. Show all posts
Showing posts with label source code. Show all posts

Monday, October 12, 2020

Gaussian Filter in Keras (code snippet)

Very often we need to perform basic vision operations on a computational graph like building a Laplacian pyramid or filter a tensor with a specific precalculated filter. 

Below i present a code snippet for building a fixed non-trainable gaussian filter in keras.

import keras
import numpy as np
import scipy.stats as st

def gaussian_filter_block(input_layer,
kernel_size=3,
strides=(1, 1),
dilation_rate=(1, 1),
padding="same",
activation=None,
trainable=False,
use_bias=False):
"""
Build a gaussian filter block
:return:
"""

def _gaussian_kernel(kernlen=[21, 21], nsig=[3, 3]):
"""
Returns a 2D Gaussian kernel array
"""
assert len(nsig) == 2
assert len(kernlen) == 2
kern1d = []
for i in range(2):
interval = (2 * nsig[i] + 1.) / (kernlen[i])
x = np.linspace(-nsig[i] - interval / 2., nsig[i] + interval / 2.,
kernlen[i] + 1)
kern1d.append(np.diff(st.norm.cdf(x)))

kernel_raw = np.sqrt(np.outer(kern1d[0], kern1d[1]))
# divide by sum so they all add up to 1
kernel = kernel_raw / kernel_raw.sum()
return kernel

# Initialise to set kernel to required value
def kernel_init(shape, dtype):
kernel = np.zeros(shape)
kernel[:, :, 0, 0] = _gaussian_kernel([shape[0], shape[1]])
return kernel

return keras.layers.DepthwiseConv2D(
kernel_size=kernel_size,
strides=strides,
padding=padding,
depth_multiplier=1,
dilation_rate=dilation_rate,
activation=activation,
use_bias=use_bias,
trainable=trainable,
depthwise_initializer=kernel_init,
kernel_initializer=kernel_init)(input_layer)

from my open source project https://github.com/NikolasMarkou/multiscale_variational_autoencoder

gaussian filter seminar ppt