Tensorflow卷积

时间:2017-10-03 17:03:41

标签: python image tensorflow reshape convolution

我试图对可变尺寸的图像执行卷积(conv2d)。我有一维数组形式的图像,我想对它们进行卷积,但我对形状有很多麻烦。 这是我conv2d的代码:

tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')

其中x是输入图像。 错误是:

ValueError: Shape must be rank 4 but is rank 1 for 'Conv2D' (op: 'Conv2D') with input shapes: [1], [5,5,1,32].

我想我可能会重塑x,但我不知道正确的尺寸。当我尝试这段代码时:

x = tf.reshape(self.x, shape=[-1, 5, 5, 1]) # example

我明白了:

ValueError: Dimension size must be evenly divisible by 25 but is 1 for 'Reshape' (op: 'Reshape') with input shapes: [1], [4] and with input tensors computed as partial shapes: input[1] = [?,5,5,1].

1 个答案:

答案 0 :(得分:2)

你不能将conv2d用于等级1的张量。这是来自doc的描述:

  

4-D 输入和滤波器张量的情况下计算2-D卷积。

这四个维度是[batch, height, width, channels](正如Engineero已经写过的那样)。

如果您事先不知道图像的尺寸,则tensorflow允许提供动态形状:

x = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='x')
with tf.Session() as session:
    print session.run(x, feed_dict={x: data})

在此示例中,创建了4-D张量x,但只有静态已知通道数(3),其他所有内容都在运行时确定。因此,即使大小是动态的,您也可以将x传递给conv2d

但还有另一个问题。你没有说你的任务,但如果你正在构建一个卷积神经网络,我担心,你需要知道输入的大小,以确定所有池操作后FC层的大小 - 这个大小必须是静止的。如果是这种情况,我认为最好的解决方案实际上是在将输入传递到卷积网络之前将其扩展到通用大小。

UPD:

由于不清楚,以下是如何将任何图像重塑为4-D阵列。

a = np.zeros([50, 178, 3])
shape = a.shape
print shape    # prints (50, 178, 3)
a = a.reshape([1] + list(shape))
print a.shape  # prints (1, 50, 178, 3)