Tensorflow:如何使用自定义常量过滤器对图像进行卷积

问题描述 投票:0回答:2

我有3个5x5滤镜我想在灰度图像(shape [nx,ny,1])输入上进行卷积。我已经预设了这些5x5过滤器中需要的硬编码值,我不希望它们被我的模型“学习”,而只是一个恒定的操作。

我该如何实现这一目标?

我正在研究使用tf.nn.conv2d()并且它说它的滤镜需要具有形状[高度,宽度,输入,输出]所以我试图使用tf.constant()来为我的形状滤镜创建张量[5,5,1,3](所以3个5x5形状的滤镜应用于1个通道的输入)但是tf.constant()的结果看起来并不正确。它出来是这样的:

 [[[[ -5   7  -12]]

   [[  21  0   2]]

   [[ -6   9  -6]]

   [[  2  -2   8]]

   [[-6   4  -1]]]


  [[[  2  -6   8]]

   [[ -6   2  -1]]

   [[  2  -2   2]]

   [[ -1   1   5]]

   [[  4   3   2]]]

 ...etc

它看起来不像3 5x5过滤器的形状。

如果我使用形状为[1,3,5,5]的tf.constant(),我会得到:

[[[[ -5   7  -12   21  0]
   [  2  -6   9  -6   2]
   [ -2   8 -6   4  -1]
   [  2  -6   8  -6   2]
   [ -1   2  -2   2  -1]]

  [[  1   5   4   3   2]
   [  4   0  -2   0   4]
   [  2  -1   7  -3   5]
   [  -1   0  -1   0  -1]
   [  5   0   9   0   5]]

   ...etc

它看起来像5x5过滤器,但它不是tf.nn.conv2d()采用的正确形状

所以我对这种不匹配感到困惑,不知道正确的做法是什么。

tensorflow machine-learning conv-neural-network convolution tensor
2个回答
1
投票

最好不要担心过滤器的外观。只需跟踪形状,确保它们有意义。

以下是将2个Sobel滤镜应用于图像的示例:

from skimage import data
img = np.expand_dims(data.camera(), -1)
img = np.expand_dims(img, 0)  # shape: (1, 512, 512, 1)

sobel_x = np.array([[-0.25, -0.2 ,  0.  ,  0.2 ,  0.25],
                   [-0.4 , -0.5 ,  0.  ,  0.5 ,  0.4 ],
                   [-0.5 , -1.  ,  0.  ,  1.  ,  0.5 ],
                   [-0.4 , -0.5 ,  0.  ,  0.5 ,  0.4 ],
                   [-0.25, -0.2 ,  0.  ,  0.2 ,  0.25]])

sobel_y = np.array([[-0.25, -0.4 , -0.5 , -0.4 , -0.25],
                   [-0.2 , -0.5 , -1.  , -0.5 , -0.2 ],
                   [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
                   [ 0.2 ,  0.5 ,  1.  ,  0.5 ,  0.2 ],
                   [ 0.25,  0.4 ,  0.5 ,  0.4 ,  0.25]])

filters = np.concatenate([[sobel_x], [sobel_y]])  # shape: (2, 5, 5)
filters = np.expand_dims(filters, -1)  # shape: (2, 5, 5, 1)
filters = filters.transpose(1, 2, 3, 0)  # shape: (5, 5, 1, 2)

# Convolve image
ans = tf.nn.conv2d((img / 255.0).astype('float32'),
                   filters,
                   strides=[1, 1, 1, 1],
                   padding='SAME')

with tf.Session() as sess:
    ans_np = sess.run(ans)  # shape: (1, 512, 512, 2)

filtered1 = ans_np[0, ..., 0]
filtered2 = ans_np[0, ..., 1]

图像与2个滤镜正确卷积,结果图像如下:

plt.matshow(filtered1)
plt.show()

enter image description here

plt.matshow(filtered2)
plt.show()

enter image description here


0
投票

第一种情况似乎是正确显示形状[5, 5, 1, 3]的过滤器。看一下方括号的数量 - tensorflow显示每个小方框的水平方向的第四维度,以及垂直方向的第二维度。 (第3个维度为1,因此没有必要显示)

© www.soinside.com 2019 - 2024. All rights reserved.