How can I implement a 2D low pass (also known as blurring) filter in Tensorflow using a gaussian kernel?
Answers
To implement a 2D low-pass (blurring) filter in TensorFlow using a Gaussian kernel, you can use the tf.nn.conv2d
function to perform convolution between the input image and the Gaussian kernel. Here's how you can implement it:
import tensorflow as tf
import numpy as np
def gaussian_kernel(kernel_size: int, sigma: float) -> np.ndarray:
"""Generates a 2D Gaussian kernel."""
x = np.linspace(-kernel_size // 2 + 1, kernel_size // 2, kernel_size)
y = np.linspace(-kernel_size // 2 + 1, kernel_size // 2, kernel_size)
x, y = np.meshgrid(x, y)
kernel = np.exp(-(x**2 + y**2) / (2 * sigma**2))
kernel = kernel / np.sum(kernel)
return kernel
def gaussian_blur(image: tf.Tensor, kernel_size: int, sigma: float) -> tf.Tensor:
"""Applies Gaussian blur to the input image."""
# Generate Gaussian kernel
kernel = gaussian_kernel(kernel_size, sigma)
kernel = np.expand_dims(np.expand_dims(kernel, axis=-1), axis=-1)
kernel = tf.constant(kernel, dtype=tf.float32)
# Apply convolution
blurred_image = tf.nn.conv2d(image, kernel, strides=[1, 1, 1, 1], padding='SAME')
return blurred_image
# Example usage
input_image = tf.placeholder(tf.float32, shape=[None, None, None, 3]) # Input image placeholder
blurred_image = gaussian_blur(input_image, kernel_size=5, sigma=1.0) # Apply Gaussian blur
# Run a session to blur an image
with tf.Session() as sess:
# Assuming 'image' is your input image
input_image_data = ... # Load or generate your input image data
blurred_image_data = sess.run(blurred_image, feed_dict={input_image: input_image_data})
In this code:
gaussian_kernel
: This function generates a 2D Gaussian kernel given the kernel size and standard deviation (sigma).gaussian_blur
: This function applies Gaussian blur to the input image using thetf.nn.conv2d
function with the generated Gaussian kernel.input_image
: This is a placeholder for the input image tensor.blurred_image
: This is the output tensor representing the blurred image.
You can adjust the kernel_size
and sigma
parameters to control the blurring effect. Larger kernel_size
and smaller sigma
values result in stronger blurring.