如何使用高斯内核在Tensorflow中实现2D低通(也称为模糊)滤波器?
答案 0 :(得分:14)
首先定义标准化的2D高斯核:
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)
接下来,使用tf.nn.conv2d将该内核与图像进行卷积:
# 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")
答案 1 :(得分:1)
Tensorflow 插件包含一个 2D Gaussian blur。这是函数签名:
@tf.function
tfa.image.gaussian_filter2d(
image: tfa.types.TensorLike,
filter_shape: Union[List[int], Tuple[int], int] = [3, 3],
sigma: Union[List[float], Tuple[float], float] = 1.0,
padding: str = 'REFLECT',
constant_values: tfa.types.TensorLike = 0,
name: Optional[str] = None
) -> tfa.types.TensorLike