Tensorflow 膨胀的行为不同于形态膨胀

Tensorflow dilation behave differently than morphological dilation

如下一段代码所示,tensorflow tf.nn.dilation2D function doesn't behave as a conventional dilation operator

import tensorflow as tf
tf.InteractiveSession()
A = [[0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 1, 0, 0],
     [0, 0, 0, 1, 1, 1, 0],
     [0, 0, 0, 0, 1, 0, 0],
     [0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0]]
kernel = tf.ones((3,3,1))
input4D = tf.cast(tf.expand_dims(tf.expand_dims(A, -1), 0), tf.float32)
output4D = tf.nn.dilation2d(input4D, filter=kernel, strides=(1,1,1,1), rates=(1,1,1,1), padding="SAME")
print(tf.cast(output4D[0,:,:,0], tf.int32).eval())

Returns 以下张量:

array([[1, 1, 1, 2, 2, 2, 1],
       [1, 1, 2, 2, 2, 2, 2],
       [1, 1, 2, 2, 2, 2, 2],
       [1, 1, 2, 2, 2, 2, 2],
       [1, 1, 1, 2, 2, 2, 1],
       [1, 1, 1, 1, 1, 1, 1]], dtype=int32)

我也不明白为什么它的行为是那样的,也不如何我应该使用tf.nn.dilation2d来检索预期输出:

array([[0, 0, 0, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 1, 1],
       [0, 0, 1, 1, 1, 1, 1],
       [0, 0, 1, 1, 1, 1, 1],
       [0, 0, 0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0]], dtype=int32)

有人可以启发 tensorflow 的简洁文档并解释 tf.nn.dilation2D 函数的作用吗?

如链接的文档页面中所述,

Computes the grayscale dilation of 4-D input and 3-D filter tensors.

In detail, the grayscale morphological 2-D dilation is the max-sum correlation [...]

意思是将内核的值与图像每个位置的值相加,然后取最大值作为输出值。

将此与相关性进行比较,用加法代替乘法,用最大值代替积分(或总和):

卷积:g(t) = ∫ f() h(-t) d

膨胀:g(t) = max { f () + h(-t) }

或者在离散世界中:

卷积:g[n] = ∑k f[k] h[k-n]

膨胀:g[n] = maxk { f[k] + h[k-n]}


具有二进制结构元素(内核,问题中称为“常规膨胀”)的膨胀使用仅包含 1 和 0 的结构元素(内核)。这些表示“包括”和“排除”。即1决定了结构元素的域。

要使用灰度值膨胀重新创建相同的行为,请将“包含”像素设置为 0,将“排除”像素设置为负无穷大。

例如,问题中使用的 3x3 方形结构元素应该是一个 3x3 的零矩阵。

可以这样做:

def dilation2d(self, img4D):
    '''
    '''
    with tf.variable_scope('dilation2d'):
        kernel = tf.ones((3, 3, img4D.get_shape()[3])) 
        output4D = tf.nn.dilation2d(img4D, filter=kernel, strides=(1,1,1,1), rates=(1,1,1,1), padding="SAME")
        output4D = output4D - tf.ones_like(output4D)

        return output4D