【发布时间】:2019-01-31 10:02:39
【问题描述】:
如何使用高斯核在 Tensorflow 中实现 2D 低通(也称为模糊)滤波器?
【问题讨论】:
标签: tensorflow image-processing
如何使用高斯核在 Tensorflow 中实现 2D 低通(也称为模糊)滤波器?
【问题讨论】:
标签: tensorflow image-processing
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
【讨论】:
首先定义一个归一化的二维高斯核:
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")
【讨论】:
x = tf.stop_gradient(x) 停止传播梯度。 (这有效地阻止了它的训练)