Last active
October 2, 2023 12:37
-
-
Save blzq/c87d42f45a8c5a53f5b393e27b1f5319 to your computer and use it in GitHub Desktop.
TensorFlow (Python) implementation of Gaussian blur of image with variable input kernel size and sigma
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def gaussian_blur(img, kernel_size=11, sigma=5): | |
| def gauss_kernel(channels, kernel_size, sigma): | |
| ax = tf.range(-kernel_size // 2 + 1.0, kernel_size // 2 + 1.0) | |
| xx, yy = tf.meshgrid(ax, ax) | |
| kernel = tf.exp(-(xx ** 2 + yy ** 2) / (2.0 * sigma ** 2)) | |
| kernel = kernel / tf.reduce_sum(kernel) | |
| kernel = tf.tile(kernel[..., tf.newaxis], [1, 1, channels]) | |
| return kernel | |
| gaussian_kernel = gauss_kernel(tf.shape(img)[-1], kernel_size, sigma) | |
| gaussian_kernel = gaussian_kernel[..., tf.newaxis] | |
| return tf.nn.depthwise_conv2d(img, gaussian_kernel, [1, 1, 1, 1], | |
| padding='SAME', data_format='NHWC') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment