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")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…