TensorFlow中的自定义卷积

3

假设我想更改卷积核的核心,使得内核权重基于内核中间的输入值而改变。 我该如何在tensorflow中编写这样的层?

 Kernel -> Image  

|a b c|    |2 3 2|
|d e f| -> |5 4 5|
|g h i|    |5 3 1|

----> because e would be 4, if both were overlapping, the other wheigths should change like f(x):

f(x)=x*wheigt

|4a 4b 4c|
|4d e  4f|
|4g 4h 4i|

所以至少,将所有权重都改为像f(x)中间一样的权重。

你会有多少输入和输出通道,只有一个吗? - jdehesa
我想要一个RGB或HSV图像作为输入,所以需要3个通道,输出也需要3个通道。PS:基本思路是通过卷积计算像素之间的欧几里得距离。但是在此基础上,欧几里得距离公式应该根据内核(中间权重)的输入值进行更改。 - Paul Higazi
1
啊,我明白了,但这是普通卷积(因此每个输出通道中的每个像素都是三个输入通道中像素的组合),还是可分离卷积(因此每个输出通道的像素仅从相应的输入通道中的像素计算)?我问这个问题是因为我认为在第二种情况下,它只是一个可分离卷积,然后再与输入进行逐元素乘法... - jdehesa
1
应该像以下伪代码示例一样分开:**(1)** 取红色通道的一个像素 --> 图像[10,10,0] (2) 计算到所有周围像素的距离(3x3卷积,因此有8个像素)。 (3) 根据图像[10,10,0]中的值对8个距离应用函数 --> (f(x))。 (4) 输出红色通道的新距离图。所以我认为应该是第二种,可分离卷积,这回答了你的问题吗? - Paul Higazi
1个回答

1
如果我理解正确,我认为这可以满足您的需求(在TF 2.x中,但在1.x中也是相同的):
import tensorflow as tf

# Input data
kernel = tf.constant([[1., 2., 3.],
                      [4., 5., 6.],
                      [7., 8., 9.]], dtype=tf.float32)
img = tf.reshape(tf.range(90, dtype=tf.float32), [1, 5, 6, 3])
# Do separable convolution
kernel_t = tf.tile(kernel[:, :, tf.newaxis, tf.newaxis], [1, 1, 3, 1])
eye = tf.eye(3, 3, batch_shape=[1, 1])  # Pointwise filter does nothing
conv = tf.nn.separable_conv2d(img, kernel_t, eye, strides=[1, 1, 1, 1], padding='SAME')
# Scale convolution result and subtract the scaling for the central value
result = conv * img - kernel[1, 1] * img * (img - 1)

# Check result
kernel_np = kernel.numpy()
img_np = img.numpy()
result_np = result.numpy()
# Coordinates of checked result
i, j, c = 3, 4, 1
# Image value
v = img_np[0, i, j, c]
# Image window aroud value
img_w = img_np[0, i - 1:i + 2, j - 1:j + 2, c]
# Kernel scaled by image value except at center
kernel_scaled = kernel_np * v
kernel_scaled[1, 1] = kernel_np[1, 1]
# Compute output value
val_test = (img_w * kernel_scaled).sum()
# Check against TF calculation
val_result = result_np[0, i, j, c]
print(val_test == val_result)
# True

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接