将图像提供给 TensorFlow 图形时出错

Error while feeding images to TensorFlow graph

我正在尝试将一些图像加载到 TensorFlow 图表中,该图表是 RGB,但是我希望图表在处理之前将它们转换为灰度。

x = tf.placeholder(tf.float32, shape=[None, 32, 32, 1], name='x')

gray = tf.image.rgb_to_grayscale(x, name='grayscale')

但是我收到了错误

ValueError: Cannot feed value of shape (250, 32, 32, 3) for Tensor 'x:0', which has shape '(?, 32, 32, 1)'

为了完整和简洁,我导出了 notebook 并作为 md 文件上传到 Github

我意识到错误是因为 x_batch 是 RGB 形状。

不过我认为 TensorFlow 会自动进行转换。

由于 tf.image.rgb_to_grayscale 包装输入,TF 不应该将 grayscaling 作为会话的一部分吗?

还是我误解了它的工作原理?

函数 tf.image.rgb_to_graycale 需要一个输入张量,其最后一个维度的大小为 3。例如,在您的情况下是一批形状为 (250, 32, 32, 3) 的图像,或者它可以是单个形状图像(32, 32, 3).

如果你想输入 RGB 图像并立即将它们处理成灰度,你可以这样做:

images = tf.placeholder(tf.float32, shape=[None, 32, 32, 3])
gray_images = tf.image.rgb_to_grayscale(images)  # has shape (None, 32, 32, 1)

错误是因为您想要加载 RGB 图像进行 RGB2 灰度转换,但在占位符中

x = tf.placeholder(tf.float32, shape=[None, 32, 32, 1], name='x')

x被定义为单维,将1改为3,错误将被移除。